flay-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.
@@ -0,0 +1,488 @@
1
+ //! Flay 2.14.5's duplication analysis, computed in Rust from Prism's syntax
2
+ //! tree.
3
+ //!
4
+ //! Flay parses each file with `Prism::Translation::RubyParser`, hashes the
5
+ //! structure of every sexp in the resulting tree, and reports structures
6
+ //! that appear more than once. [`parse_source`] builds the same sexp tree
7
+ //! (module `translate`); [`Flay`] keeps Flay's state across files and runs
8
+ //! the same steps: `process_sexp`, `prune`, the identical check and
9
+ //! `update_masses`.
10
+ //!
11
+ //! Also ported: the `fuzzy` and `liberal` options, ERB files (module
12
+ //! `erb`, Flay's `flay_erb` plugin), the report items, summary and report
13
+ //! (module `report`).
14
+
15
+ mod attach_comments;
16
+ pub mod erb;
17
+ pub mod matcher;
18
+ pub mod process;
19
+ pub mod report;
20
+ pub mod ruby2ruby;
21
+ pub mod ruby_format;
22
+ pub mod ruby_sort;
23
+ pub mod sexp;
24
+ mod translate;
25
+
26
+ use indexmap::{IndexMap, IndexSet};
27
+
28
+ use sexp::{SexpId, Tree, Value};
29
+
30
+ /// The Flay version whose results this crate reproduces.
31
+ pub const FLAY_COMPAT: &str = "2.14.5";
32
+
33
+ /// `Flay.default_options[:mass]`.
34
+ pub const DEFAULT_MASS: u64 = 16;
35
+
36
+ /// A Ruby exception: its class name and message.
37
+ #[derive(Clone, Debug, PartialEq)]
38
+ pub struct RubyException {
39
+ pub class: &'static str,
40
+ pub message: String,
41
+ }
42
+
43
+ /// Why Flay skipped a file. Flay prints a warning and goes on to the next.
44
+ #[derive(Clone, Debug, PartialEq)]
45
+ pub enum Skip {
46
+ /// The file could not be read (`File.binread` raised); the message of
47
+ /// Ruby's `SystemCallError` (see [`read_error_message`]).
48
+ Unreadable(String),
49
+ /// Prism reported a parse error; the translator raises
50
+ /// `RubyParser::SyntaxError, "file:line :: message"`.
51
+ SyntaxError(String),
52
+ /// The translator raised another exception.
53
+ Raised(RubyException),
54
+ }
55
+
56
+ /// One file parsed and translated, ready for [`Flay::process_parsed`].
57
+ #[derive(Clone, Debug)]
58
+ pub struct ParsedFile {
59
+ pub path: String,
60
+ pub outcome: Result<(Tree, Value), Skip>,
61
+ }
62
+
63
+ /// The Prism syntax version that `Prism.parse` uses by default under the
64
+ /// given Ruby version (`RUBY_VERSION`): the running Ruby's own syntax, 3.3
65
+ /// for older Rubies, and the latest syntax for newer ones or `"latest"`.
66
+ ///
67
+ /// Flay's results depend on this: under Ruby 3.3, `it` in a block is a
68
+ /// method call; under 3.4 it is a local variable.
69
+ pub fn syntax_version_for_ruby(ruby_version: &str) -> ruby_prism::Version {
70
+ use ruby_prism::Version;
71
+ let mut parts = ruby_version.split('.');
72
+ match (parts.next(), parts.next()) {
73
+ (Some("3"), Some("3")) => Version::CRuby3_3,
74
+ (Some("3"), Some("4")) => Version::CRuby3_4,
75
+ (Some("3"), Some("5")) | (Some("4"), Some("0")) => Version::CRuby4_0,
76
+ (Some("4"), Some("1")) => Version::CRuby4_1,
77
+ _ if ruby_version != "latest" && ruby_version < "3.3" => Version::CRuby3_3,
78
+ _ => Version::Latest,
79
+ }
80
+ }
81
+
82
+ /// Parses and translates Ruby source as `Flay#process_rb` does
83
+ /// (`NotRubyParser.new.process(File.binread(file), file)`).
84
+ pub fn parse_source(source: &[u8], path: &str, ruby_version: &str) -> ParsedFile {
85
+ let options = ruby_prism::Options::default()
86
+ .filepath(path)
87
+ .partial_script(true)
88
+ .version(syntax_version_for_ruby(ruby_version))
89
+ .build();
90
+ let parse_result = ruby_prism::parse_with_options(source, &options);
91
+
92
+ let outcome = if let Some(error) = parse_result.errors().next() {
93
+ Err(Skip::SyntaxError(format!(
94
+ "{}:{} :: {}",
95
+ path,
96
+ error.location().start_line(),
97
+ String::from_utf8_lossy(error.message())
98
+ )))
99
+ } else if let Some(exception) = attach_comments::attach_comments_exception(source, &parse_result) {
100
+ Err(Skip::Raised(exception))
101
+ } else {
102
+ let encoding = attach_comments::source_encoding(source);
103
+ translate::translate(&parse_result.node(), encoding).map_err(Skip::Raised)
104
+ };
105
+ ParsedFile { path: path.to_string(), outcome }
106
+ }
107
+
108
+ /// Reads, parses and translates a file.
109
+ pub fn parse_file(path: &str, ruby_version: &str) -> ParsedFile {
110
+ match std::fs::read(path) {
111
+ Ok(source) => parse_source(&source, path, ruby_version),
112
+ Err(error) => ParsedFile { path: path.to_string(), outcome: Err(Skip::Unreadable(read_error_message(&error, path))) },
113
+ }
114
+ }
115
+
116
+ /// The message of the `SystemCallError` that `File.binread(path)` (or
117
+ /// `File.read`) raises: the C library's text for the error, then where
118
+ /// Ruby saw it. A directory opens and fails on reading (`io_fread`); every
119
+ /// other error fails on opening (`rb_sysopen`).
120
+ pub fn read_error_message(error: &std::io::Error, path: &str) -> String {
121
+ let text = error.to_string();
122
+ let text = match text.rfind(" (os error ") {
123
+ Some(suffix) => text[..suffix].to_string(),
124
+ None => text,
125
+ };
126
+ let function = if error.kind() == std::io::ErrorKind::IsADirectory { "io_fread" } else { "rb_sysopen" };
127
+ format!("{text} @ {function} - {path}")
128
+ }
129
+
130
+ /// A node in `Flay#hashes`: a sexp in one of the files Flay processed, or a
131
+ /// sexp the `fuzzy` option made from one. Equal `NodeRef`s are the same
132
+ /// Ruby object (`equal?`).
133
+ #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
134
+ pub struct NodeRef {
135
+ file: u32,
136
+ /// The sexp, or for a fuzzy node the sexp it was copied from.
137
+ pub sexp: SexpId,
138
+ /// Index in `Flay::fuzzy_nodes` for a node `process_fuzzy` made.
139
+ fuzzy: Option<u32>,
140
+ }
141
+
142
+ /// A sexp `process_fuzzy` made: a copy of `NodeRef::sexp` with some of its
143
+ /// code removed, marked `modified`. It keeps the original's file and line.
144
+ #[derive(Clone, Debug)]
145
+ struct FuzzyNode {
146
+ elements: Vec<Value>,
147
+ mass: u64,
148
+ structural_hash: u32,
149
+ }
150
+
151
+ /// The parts of a sexp Flay's results show.
152
+ #[derive(Clone, Debug, PartialEq)]
153
+ pub struct NodeInfo<'a> {
154
+ /// `sexp_type`, a Symbol's bytes.
155
+ pub sexp_type: &'a [u8],
156
+ /// `file`: the path given to `process`.
157
+ pub file: &'a str,
158
+ pub line: i32,
159
+ pub mass: u64,
160
+ /// `modified?`: true for the nodes the `fuzzy` option made.
161
+ pub modified: bool,
162
+ }
163
+
164
+ /// `Flay::MAX_NODE_SIZE`: `process_fuzzy` skips sexps with more elements.
165
+ const MAX_NODE_SIZE: usize = 10;
166
+
167
+ /// `Flay::MAX_AVG_MASS`: `process_fuzzy` skips sexps whose mass per element
168
+ /// is higher.
169
+ const MAX_AVG_MASS: u64 = 12;
170
+
171
+ /// The options that change what [`Flay::process_parsed`] adds.
172
+ #[derive(Clone, Copy, Debug, PartialEq, Eq)]
173
+ pub struct ProcessOptions {
174
+ /// `mass_threshold`.
175
+ pub mass_threshold: u64,
176
+ /// `option[:fuzzy]`: how many code elements a fuzzy match may lack, or
177
+ /// `None` when the option is off.
178
+ pub fuzzy: Option<i64>,
179
+ }
180
+
181
+ /// The state of one `Flay` instance: `hashes`, `identical`, `masses` and
182
+ /// `total`, in Flay's insertion order.
183
+ #[derive(Clone, Debug, Default)]
184
+ pub struct Flay {
185
+ /// Path and tree of each file that contributed a node.
186
+ files: Vec<(String, Tree)>,
187
+ fuzzy_nodes: Vec<FuzzyNode>,
188
+ hashes: IndexMap<u32, Vec<NodeRef>>,
189
+ identical: IndexMap<u32, bool>,
190
+ masses: IndexMap<u32, u64>,
191
+ total: u64,
192
+ }
193
+
194
+ impl Flay {
195
+ pub fn new() -> Self {
196
+ Self::default()
197
+ }
198
+
199
+ /// `Flay#process_sexp` for one parsed file: every sexp below the root
200
+ /// that has a sexp child and a mass of at least `mass_threshold` goes
201
+ /// into the bucket for its structural hash, followed by its fuzzy
202
+ /// variants when `fuzzy` is set. A skipped file adds nothing.
203
+ pub fn process_parsed(&mut self, parsed: ParsedFile, options: ProcessOptions) {
204
+ let Ok((tree, Value::Sexp(root))) = parsed.outcome else {
205
+ return;
206
+ };
207
+ let file = self.files.len() as u32;
208
+ let mut nodes = Vec::new();
209
+ tree.deep_each(root, |sexp| {
210
+ if tree.each_sexp(sexp).next().is_none() || tree.mass(sexp) < options.mass_threshold {
211
+ return false;
212
+ }
213
+ nodes.push(sexp);
214
+ true
215
+ });
216
+ if nodes.is_empty() {
217
+ return;
218
+ }
219
+ self.files.push((parsed.path, tree));
220
+ for sexp in nodes {
221
+ let node = NodeRef { file, sexp, fuzzy: None };
222
+ let hash = self.files[file as usize].1.structural_hash(sexp);
223
+ self.hashes.entry(hash).or_default().push(node);
224
+ if let Some(difference) = options.fuzzy {
225
+ self.process_fuzzy(node, difference, options.mass_threshold);
226
+ }
227
+ }
228
+ }
229
+
230
+ /// `Flay#process_fuzzy`: for a sexp with a code section (see
231
+ /// [`code_index`]) and at most [`MAX_NODE_SIZE`] elements, adds each
232
+ /// copy that lacks 1 to `difference` of its code elements (in
233
+ /// `Array#combination` order), unless the copy has no sexp element, is
234
+ /// lighter than `mass_threshold`, or its bucket already holds a node
235
+ /// from the same file and line.
236
+ fn process_fuzzy(&mut self, node: NodeRef, difference: i64, mass_threshold: u64) {
237
+ let (path, tree) = &self.files[node.file as usize];
238
+ let elements = &tree.get(node.sexp).elements;
239
+ let Some(index) = code_index(tree.type_name(node.sexp)) else {
240
+ return;
241
+ };
242
+ let size = elements.len();
243
+ let average_mass = tree.mass(node.sexp) / size as u64;
244
+ if size > MAX_NODE_SIZE || average_mass > MAX_AVG_MASS {
245
+ return;
246
+ }
247
+ // `split_code`: `self[0..index]` and `self[index + 1..-1]`.
248
+ let split = (index + 1).min(size);
249
+ let (template, code) = elements.split_at(split);
250
+ let line = tree.line(node.sexp);
251
+
252
+ let code_size = code.len() as i64;
253
+ let mut new_nodes = Vec::new();
254
+ for count in (code_size - difference..code_size).rev() {
255
+ let Ok(count) = usize::try_from(count) else { break };
256
+ for subcode in combinations(code.len(), count) {
257
+ let elements: Vec<Value> =
258
+ template.iter().cloned().chain(subcode.iter().map(|&i| code[i].clone())).collect();
259
+ if !elements.iter().any(|element| element.as_sexp().is_some()) {
260
+ continue;
261
+ }
262
+ let mass = tree.elements_mass(&elements);
263
+ if mass < mass_threshold {
264
+ continue;
265
+ }
266
+ let structural_hash = tree.elements_structural_hash(&elements);
267
+ new_nodes.push(FuzzyNode { elements, mass, structural_hash });
268
+ }
269
+ }
270
+
271
+ let path = path.clone();
272
+ for fuzzy_node in new_nodes {
273
+ let bucket = self.hashes.entry(fuzzy_node.structural_hash).or_default();
274
+ let same_place = bucket.iter().any(|other| {
275
+ let (other_path, other_tree) = &self.files[other.file as usize];
276
+ *other_path == path && other_tree.line(other.sexp) == line
277
+ });
278
+ if same_place {
279
+ continue;
280
+ }
281
+ bucket.push(NodeRef { fuzzy: Some(self.fuzzy_nodes.len() as u32), ..node });
282
+ self.fuzzy_nodes.push(fuzzy_node);
283
+ }
284
+ }
285
+
286
+ /// `Flay#analyze` without building the report items: `prune`, the
287
+ /// identical check, then `update_masses`.
288
+ pub fn analyze(&mut self, liberal: bool) {
289
+ self.prune(liberal);
290
+ self.check_identical();
291
+ self.update_masses();
292
+ }
293
+
294
+ /// `Flay#prune`: drops buckets with one node and buckets of fuzzy nodes
295
+ /// only, then prunes liberally or conservatively.
296
+ pub fn prune(&mut self, liberal: bool) {
297
+ self.hashes.retain(|_, nodes| nodes.len() != 1);
298
+ // `nodes.all?(&:modified?)`, which is also true for an empty bucket.
299
+ self.hashes.retain(|_, nodes| !nodes.iter().all(|node| node.fuzzy.is_some()));
300
+ if liberal {
301
+ self.prune_liberally();
302
+ } else {
303
+ self.prune_conservatively();
304
+ }
305
+ }
306
+
307
+ /// `Flay#prune_conservatively`: drops every bucket whose structure
308
+ /// appears inside the first node of a bucket.
309
+ fn prune_conservatively(&mut self) {
310
+ let mut hashes_to_prune = IndexSet::new();
311
+ for nodes in self.hashes.values() {
312
+ let first = nodes[0];
313
+ let tree = self.tree(first);
314
+ self.deep_each(first, |sexp| {
315
+ hashes_to_prune.insert(tree.structural_hash(sexp));
316
+ });
317
+ }
318
+ self.hashes.retain(|hash, _| !hashes_to_prune.contains(hash));
319
+ }
320
+
321
+ /// `Flay#prune_liberally`: after `update_masses`, removes from each
322
+ /// bucket the nodes that are inside a node of another bucket whose mass
323
+ /// is at least the inner bucket's, then drops buckets left with one
324
+ /// node or none.
325
+ fn prune_liberally(&mut self) {
326
+ self.update_masses();
327
+
328
+ let mut hashes_to_prune: IndexMap<u32, IndexSet<NodeRef>> = IndexMap::new();
329
+ for nodes in self.hashes.values() {
330
+ for &node in nodes {
331
+ let top_score = self.masses.get(&self.structural_hash(node)).copied();
332
+ let tree = self.tree(node);
333
+ self.deep_each(node, |sexp| {
334
+ let sub_hash = tree.structural_hash(sexp);
335
+ let sub_score = self.masses.get(&sub_hash).copied();
336
+ if let (Some(sub_score), Some(top_score)) = (sub_score, top_score) {
337
+ if sub_score > top_score {
338
+ return;
339
+ }
340
+ }
341
+ hashes_to_prune.entry(sub_hash).or_default().insert(NodeRef { sexp, fuzzy: None, ..node });
342
+ });
343
+ }
344
+ }
345
+
346
+ for (hash, nodes) in self.hashes.iter_mut() {
347
+ if let Some(pruned) = hashes_to_prune.get(hash) {
348
+ nodes.retain(|node| !pruned.contains(node));
349
+ }
350
+ }
351
+ self.hashes.retain(|_, nodes| nodes.len() > 1);
352
+ }
353
+
354
+ /// `Sexp#deep_each` on a node: every sexp below it, in pre-order.
355
+ fn deep_each(&self, node: NodeRef, mut visit: impl FnMut(SexpId)) {
356
+ let tree = self.tree(node);
357
+ for child in self.elements(node).iter().filter_map(Value::as_sexp) {
358
+ visit(child);
359
+ tree.deep_each(child, |sexp| {
360
+ visit(sexp);
361
+ true
362
+ });
363
+ }
364
+ }
365
+
366
+ /// `identical[hash] = nodes[1..-1].all? { |n| n == nodes.first }`.
367
+ pub fn check_identical(&mut self) {
368
+ for (hash, nodes) in &self.hashes {
369
+ let first = nodes[0];
370
+ let same = nodes[1..].iter().all(|node| {
371
+ sexp::elements_eq(self.tree(*node), self.elements(*node), self.tree(first), self.elements(first))
372
+ });
373
+ self.identical.insert(*hash, same);
374
+ }
375
+ }
376
+
377
+ /// `Flay#update_masses`: each bucket's mass is the first node's mass
378
+ /// times the number of nodes, times that number again when identical.
379
+ pub fn update_masses(&mut self) {
380
+ self.total = 0;
381
+ self.masses.clear();
382
+ for (hash, nodes) in &self.hashes {
383
+ let size = nodes.len() as u64;
384
+ let mut mass = self.node(nodes[0]).mass * size;
385
+ if self.identical.get(hash).copied().unwrap_or(false) {
386
+ mass *= size;
387
+ }
388
+ self.masses.insert(*hash, mass);
389
+ self.total += mass;
390
+ }
391
+ }
392
+
393
+ fn tree(&self, node: NodeRef) -> &Tree {
394
+ &self.files[node.file as usize].1
395
+ }
396
+
397
+ /// The node's elements: its sexp's, or the fuzzy copy's.
398
+ fn elements(&self, node: NodeRef) -> &[Value] {
399
+ match node.fuzzy {
400
+ Some(index) => &self.fuzzy_nodes[index as usize].elements,
401
+ None => &self.tree(node).get(node.sexp).elements,
402
+ }
403
+ }
404
+
405
+ fn structural_hash(&self, node: NodeRef) -> u32 {
406
+ match node.fuzzy {
407
+ Some(index) => self.fuzzy_nodes[index as usize].structural_hash,
408
+ None => self.tree(node).structural_hash(node.sexp),
409
+ }
410
+ }
411
+
412
+ pub fn node(&self, node: NodeRef) -> NodeInfo<'_> {
413
+ let (path, tree) = &self.files[node.file as usize];
414
+ let mass = match node.fuzzy {
415
+ Some(index) => self.fuzzy_nodes[index as usize].mass,
416
+ None => tree.mass(node.sexp),
417
+ };
418
+ NodeInfo {
419
+ sexp_type: tree.type_name(node.sexp),
420
+ file: path,
421
+ line: tree.line(node.sexp),
422
+ mass,
423
+ modified: node.fuzzy.is_some(),
424
+ }
425
+ }
426
+
427
+ /// The node's tree and elements, for [`ruby2ruby`].
428
+ pub fn node_sexp(&self, node: NodeRef) -> (&Tree, &[Value]) {
429
+ (self.tree(node), self.elements(node))
430
+ }
431
+
432
+ /// `hashes`: structural hash to nodes, in insertion order.
433
+ pub fn hashes(&self) -> &IndexMap<u32, Vec<NodeRef>> {
434
+ &self.hashes
435
+ }
436
+
437
+ pub fn identical(&self) -> &IndexMap<u32, bool> {
438
+ &self.identical
439
+ }
440
+
441
+ pub fn masses(&self) -> &IndexMap<u32, u64> {
442
+ &self.masses
443
+ }
444
+
445
+ pub fn total(&self) -> u64 {
446
+ self.total
447
+ }
448
+ }
449
+
450
+ /// `Sexp#code_index`: the index of the last element before the code of a
451
+ /// `block`, `class`, `module`, `defn`, `defs` or `iter`; `None` for other
452
+ /// types (`has_code?` is false).
453
+ fn code_index(sexp_type: &[u8]) -> Option<usize> {
454
+ match sexp_type {
455
+ b"block" => Some(0),
456
+ b"module" => Some(1),
457
+ b"class" | b"defn" | b"iter" => Some(2),
458
+ b"defs" => Some(3),
459
+ _ => None,
460
+ }
461
+ }
462
+
463
+ /// `(0...size).to_a.combination(count)`: every choice of `count` indexes,
464
+ /// in Ruby's (lexicographic) order.
465
+ fn combinations(size: usize, count: usize) -> Vec<Vec<usize>> {
466
+ if count > size {
467
+ return Vec::new();
468
+ }
469
+ let mut result = Vec::new();
470
+ let mut indexes: Vec<usize> = (0..count).collect();
471
+ loop {
472
+ result.push(indexes.clone());
473
+ let Some(position) = (0..count).rev().find(|&i| indexes[i] != i + size - count) else {
474
+ return result;
475
+ };
476
+ indexes[position] += 1;
477
+ for i in position + 1..count {
478
+ indexes[i] = indexes[i - 1] + 1;
479
+ }
480
+ }
481
+ }
482
+
483
+ /// The translated tree of a parsed file as text (see `parity/oracle.rb`),
484
+ /// or `None` when the file was skipped.
485
+ pub fn dump_tree(parsed: &ParsedFile) -> Option<String> {
486
+ let (tree, root) = parsed.outcome.as_ref().ok()?;
487
+ Some(sexp::dump(tree, root))
488
+ }