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.
- checksums.yaml +7 -0
- data/Cargo.lock +495 -0
- data/Cargo.toml +23 -0
- data/DIVERGENCES.md +23 -0
- data/LICENSE +22 -0
- data/README.md +111 -0
- data/THIRD_PARTY_NOTICES.md +70 -0
- data/crates/flay-cli/Cargo.toml +22 -0
- data/crates/flay-cli/src/bin/flay-matcher-parity.rs +195 -0
- data/crates/flay-cli/src/main.rs +202 -0
- data/crates/flay-core/Cargo.toml +20 -0
- data/crates/flay-core/src/attach_comments.rs +353 -0
- data/crates/flay-core/src/erb.rs +418 -0
- data/crates/flay-core/src/lib.rs +488 -0
- data/crates/flay-core/src/matcher/parser.rs +345 -0
- data/crates/flay-core/src/matcher/regexp.rs +1243 -0
- data/crates/flay-core/src/matcher/ruby_text.rs +413 -0
- data/crates/flay-core/src/matcher/serialized.rs +340 -0
- data/crates/flay-core/src/matcher.rs +487 -0
- data/crates/flay-core/src/process.rs +312 -0
- data/crates/flay-core/src/report.rs +567 -0
- data/crates/flay-core/src/ruby2ruby.rs +3291 -0
- data/crates/flay-core/src/ruby_format.rs +163 -0
- data/crates/flay-core/src/ruby_sort.rs +246 -0
- data/crates/flay-core/src/sexp.rs +639 -0
- data/crates/flay-core/src/translate.rs +2290 -0
- data/crates/flay-core/tests/ruby2ruby_parity.rs +101 -0
- data/ext/flay_rs/Cargo.toml +17 -0
- data/ext/flay_rs/extconf.rb +6 -0
- data/ext/flay_rs/src/filters.rs +186 -0
- data/ext/flay_rs/src/lib.rs +544 -0
- data/lib/flay_rs/version.rb +8 -0
- data/lib/flay_rs.rb +18 -0
- metadata +94 -0
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
# Third-party notices
|
|
2
|
+
|
|
3
|
+
`flay-rs` ports code from the projects below. Their copyright notices and
|
|
4
|
+
licenses apply to the parts ported from them.
|
|
5
|
+
|
|
6
|
+
## Flay 2.14.5
|
|
7
|
+
|
|
8
|
+
Structural hashing, mass, pruning, the identical check, reports and the `flay_erb` plugin (`crates/flay-core`, `ext/flay_rs`).
|
|
9
|
+
|
|
10
|
+
Copyright (c) Ryan Davis, Seattle.rb
|
|
11
|
+
|
|
12
|
+
License: MIT (text below).
|
|
13
|
+
|
|
14
|
+
## sexp_processor 4.17.6
|
|
15
|
+
|
|
16
|
+
`Sexp#mass`, `Sexp#==`, `Sexp::Matcher` (`crates/flay-core/src/sexp.rs`, `matcher/`).
|
|
17
|
+
|
|
18
|
+
Copyright (c) Ryan Davis, seattle.rb
|
|
19
|
+
|
|
20
|
+
License: MIT (text below).
|
|
21
|
+
|
|
22
|
+
## ruby2ruby 2.6.2
|
|
23
|
+
|
|
24
|
+
`crates/flay-core/src/ruby2ruby.rs`.
|
|
25
|
+
|
|
26
|
+
Copyright (c) Ryan Davis, seattle.rb
|
|
27
|
+
|
|
28
|
+
License: MIT (text below).
|
|
29
|
+
|
|
30
|
+
## Erubi 1.13.1
|
|
31
|
+
|
|
32
|
+
The ERB engine Flay's `flay_erb` plugin uses (`crates/flay-core/src/erb.rs`).
|
|
33
|
+
|
|
34
|
+
copyright(c) 2006-2011 kuwata-lab.com all rights reserved.
|
|
35
|
+
copyright(c) 2016-2021 Jeremy Evans
|
|
36
|
+
|
|
37
|
+
License: MIT (text below).
|
|
38
|
+
|
|
39
|
+
## Prism 2.1.0
|
|
40
|
+
|
|
41
|
+
`Prism::Translation::RubyParser` (`translate.rs`, `attach_comments.rs`).
|
|
42
|
+
|
|
43
|
+
Copyright 2022-present, Ruby developers
|
|
44
|
+
|
|
45
|
+
License: MIT (text below).
|
|
46
|
+
|
|
47
|
+
## License texts
|
|
48
|
+
|
|
49
|
+
### MIT
|
|
50
|
+
|
|
51
|
+
```
|
|
52
|
+
Permission is hereby granted, free of charge, to any person obtaining
|
|
53
|
+
a copy of this software and associated documentation files (the
|
|
54
|
+
"Software"), to deal in the Software without restriction, including
|
|
55
|
+
without limitation the rights to use, copy, modify, merge, publish,
|
|
56
|
+
distribute, sublicense, and/or sell copies of the Software, and to
|
|
57
|
+
permit persons to whom the Software is furnished to do so, subject to
|
|
58
|
+
the following conditions:
|
|
59
|
+
|
|
60
|
+
The above copyright notice and this permission notice shall be
|
|
61
|
+
included in all copies or substantial portions of the Software.
|
|
62
|
+
|
|
63
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
|
64
|
+
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
|
65
|
+
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
|
66
|
+
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
|
|
67
|
+
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
|
68
|
+
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
|
69
|
+
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
|
70
|
+
```
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
[package]
|
|
2
|
+
name = "flay-cli"
|
|
3
|
+
version.workspace = true
|
|
4
|
+
edition.workspace = true
|
|
5
|
+
rust-version.workspace = true
|
|
6
|
+
license.workspace = true
|
|
7
|
+
authors.workspace = true
|
|
8
|
+
homepage.workspace = true
|
|
9
|
+
repository.workspace = true
|
|
10
|
+
description = "flay-rs: Flay 2.14.5's structural duplication analysis for Ruby files, as JSON"
|
|
11
|
+
readme = "README.md"
|
|
12
|
+
keywords = ["ruby", "flay", "duplication", "static-analysis", "cli"]
|
|
13
|
+
categories = ["development-tools", "command-line-utilities"]
|
|
14
|
+
|
|
15
|
+
[dependencies]
|
|
16
|
+
flay-core = { version = "0.1.0", path = "../flay-core" }
|
|
17
|
+
rayon.workspace = true
|
|
18
|
+
serde_json = { version = "1.0.154", features = ["preserve_order"] }
|
|
19
|
+
|
|
20
|
+
[[bin]]
|
|
21
|
+
name = "flay-rs"
|
|
22
|
+
path = "src/main.rs"
|
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
//! `flay-matcher-parity`: recomputes the records `parity/matcher_oracle.rb`
|
|
2
|
+
//! writes from their inputs with flay-core's `matcher` module, and writes
|
|
3
|
+
//! them in the same format (see the oracle for the records).
|
|
4
|
+
//!
|
|
5
|
+
//! flay-matcher-parity [--ruby-version=V] ORACLE.jsonl > OURS.jsonl
|
|
6
|
+
|
|
7
|
+
use std::process::ExitCode;
|
|
8
|
+
|
|
9
|
+
use flay_core::matcher::{filter_sexp, to_s, Filter};
|
|
10
|
+
use flay_core::sexp::{dump, RubyString, SexpId, Tree, Value};
|
|
11
|
+
use flay_core::{parse_file, RubyException};
|
|
12
|
+
use serde_json::{json, Map, Value as Json};
|
|
13
|
+
|
|
14
|
+
fn main() -> ExitCode {
|
|
15
|
+
let mut ruby_version = "latest".to_string();
|
|
16
|
+
let mut oracle = None;
|
|
17
|
+
for argument in std::env::args().skip(1) {
|
|
18
|
+
match argument.strip_prefix("--ruby-version=") {
|
|
19
|
+
Some(version) => ruby_version = version.to_string(),
|
|
20
|
+
None => oracle = Some(argument),
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
let Some(oracle) = oracle else {
|
|
24
|
+
eprintln!("usage: flay-matcher-parity [--ruby-version=V] ORACLE.jsonl");
|
|
25
|
+
return ExitCode::FAILURE;
|
|
26
|
+
};
|
|
27
|
+
let text = match std::fs::read_to_string(&oracle) {
|
|
28
|
+
Ok(text) => text,
|
|
29
|
+
Err(error) => {
|
|
30
|
+
eprintln!("{oracle}: {error}");
|
|
31
|
+
return ExitCode::FAILURE;
|
|
32
|
+
}
|
|
33
|
+
};
|
|
34
|
+
|
|
35
|
+
let mut subjects = Vec::new();
|
|
36
|
+
let mut file: Option<(String, Tree, SexpId)> = None;
|
|
37
|
+
for line in text.lines() {
|
|
38
|
+
let record: Map<String, Json> = serde_json::from_str(line).expect("the oracle writes JSON objects");
|
|
39
|
+
let output = match record["section"].as_str().unwrap() {
|
|
40
|
+
"subjects" => {
|
|
41
|
+
subjects = record["subjects"].as_array().unwrap().iter().map(|subject| ruby_string(subject.as_str().unwrap())).collect();
|
|
42
|
+
Json::Object(record)
|
|
43
|
+
}
|
|
44
|
+
"parse" => parse_record(&record),
|
|
45
|
+
"regexp" => regexp_record(&record, &subjects),
|
|
46
|
+
"unsupported" => {
|
|
47
|
+
let input = &record["filter"];
|
|
48
|
+
let class = build_filter(input).err().map_or("", |error| error.class);
|
|
49
|
+
json!({"section": "unsupported", "filter": input, "error_class": class})
|
|
50
|
+
}
|
|
51
|
+
section @ ("to_s" | "filter") => {
|
|
52
|
+
let path = record["path"].as_str().unwrap();
|
|
53
|
+
if file.as_ref().is_none_or(|(loaded, _, _)| loaded != path) {
|
|
54
|
+
let parsed = parse_file(path, &ruby_version);
|
|
55
|
+
file = match parsed.outcome {
|
|
56
|
+
Ok((tree, Value::Sexp(root))) => Some((path.to_string(), tree, root)),
|
|
57
|
+
_ => None,
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
match &file {
|
|
61
|
+
None => json!({"section": section, "path": path, "skipped": true}),
|
|
62
|
+
Some((_, tree, root)) if section == "to_s" => to_s_record(path, tree, *root),
|
|
63
|
+
Some((_, tree, root)) => filter_record(&record, tree, *root),
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
other => panic!("unknown section {other}"),
|
|
67
|
+
};
|
|
68
|
+
println!("{output}");
|
|
69
|
+
}
|
|
70
|
+
ExitCode::SUCCESS
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/// A String from the oracle's `ENCODING:HEX`.
|
|
74
|
+
fn ruby_string(text: &str) -> RubyString {
|
|
75
|
+
let (encoding, hex) = text.split_once(':').unwrap();
|
|
76
|
+
let encoding: &'static str = Box::leak(encoding.to_string().into_boxed_str());
|
|
77
|
+
RubyString::new(unhex(hex), encoding)
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
fn unhex(hex: &str) -> Vec<u8> {
|
|
81
|
+
(0..hex.len()).step_by(2).map(|index| u8::from_str_radix(&hex[index..index + 2], 16).unwrap()).collect()
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
fn hex(bytes: &[u8]) -> String {
|
|
85
|
+
bytes.iter().map(|byte| format!("{byte:02x}")).collect()
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
fn error_text(error: &RubyException) -> String {
|
|
89
|
+
format!("{}: {}", error.class, error.message)
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
fn parse_record(record: &Map<String, Json>) -> Json {
|
|
93
|
+
let source = record["source"].as_str().unwrap();
|
|
94
|
+
match Filter::parse(source) {
|
|
95
|
+
Ok(filter) => json!({"section": "parse", "source": source, "result": filter.serialize()}),
|
|
96
|
+
Err(error) => json!({"section": "parse", "source": source, "error": error_text(&error)}),
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/// The filter a record names: `{"source"}` for `Sexp::Matcher.parse`,
|
|
101
|
+
/// `{"serialized"}` for one built in Ruby.
|
|
102
|
+
fn build_filter(input: &Json) -> Result<Filter, RubyException> {
|
|
103
|
+
match (input.get("source"), input.get("serialized")) {
|
|
104
|
+
(Some(source), _) => Filter::parse(source.as_str().unwrap()),
|
|
105
|
+
(_, Some(serialized)) => Filter::from_serialized(serialized.as_str().unwrap()),
|
|
106
|
+
_ => panic!("a filter needs a source or a serialized form"),
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/// `satisfy?` for each value: `1`, `0` or `E`, and the distinct errors.
|
|
111
|
+
fn satisfy_results(filter: &Filter, tree: &Tree, values: impl IntoIterator<Item = Value>) -> (String, Vec<String>) {
|
|
112
|
+
let mut errors = Vec::new();
|
|
113
|
+
let results = values
|
|
114
|
+
.into_iter()
|
|
115
|
+
.map(|value| match filter.satisfy(tree, &value) {
|
|
116
|
+
Ok(true) => '1',
|
|
117
|
+
Ok(false) => '0',
|
|
118
|
+
Err(error) => {
|
|
119
|
+
let text = error_text(&error);
|
|
120
|
+
if !errors.contains(&text) {
|
|
121
|
+
errors.push(text);
|
|
122
|
+
}
|
|
123
|
+
'E'
|
|
124
|
+
}
|
|
125
|
+
})
|
|
126
|
+
.collect();
|
|
127
|
+
(results, errors)
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
fn regexp_record(record: &Map<String, Json>, subjects: &[RubyString]) -> Json {
|
|
131
|
+
let input = &record["filter"];
|
|
132
|
+
match build_filter(input) {
|
|
133
|
+
Ok(filter) => {
|
|
134
|
+
let values = subjects.iter().map(|subject| Value::string(subject.clone()));
|
|
135
|
+
let (results, errors) = satisfy_results(&filter, &Tree::default(), values);
|
|
136
|
+
json!({"section": "regexp", "filter": input, "results": results, "errors": errors})
|
|
137
|
+
}
|
|
138
|
+
Err(error) => json!({"section": "regexp", "filter": input, "error": error_text(&error)}),
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/// The root and every sexp below it, in pre-order.
|
|
143
|
+
fn sexps(tree: &Tree, root: SexpId) -> Vec<SexpId> {
|
|
144
|
+
let mut sexps = vec![root];
|
|
145
|
+
tree.deep_each(root, |sexp| {
|
|
146
|
+
sexps.push(sexp);
|
|
147
|
+
true
|
|
148
|
+
});
|
|
149
|
+
sexps
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
fn to_s_record(path: &str, tree: &Tree, root: SexpId) -> Json {
|
|
153
|
+
let mut values = Vec::new();
|
|
154
|
+
for sexp in sexps(tree, root) {
|
|
155
|
+
for element in &tree.get(sexp).elements {
|
|
156
|
+
if matches!(element, Value::Sexp(_)) {
|
|
157
|
+
continue;
|
|
158
|
+
}
|
|
159
|
+
values.push(match to_s(tree, element) {
|
|
160
|
+
Ok(text) if text.bytes.is_ascii() => format!("ascii:{}", hex(&text.bytes)),
|
|
161
|
+
Ok(text) => format!("{}:{}", text.encoding, hex(&text.bytes)),
|
|
162
|
+
Err(error) => format!("error:{}", error_text(&error)),
|
|
163
|
+
});
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
json!({"section": "to_s", "path": path, "values": values})
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
fn filter_record(record: &Map<String, Json>, tree: &Tree, root: SexpId) -> Json {
|
|
170
|
+
let inputs = record["filters"].as_array().unwrap();
|
|
171
|
+
let mut output = json!({"section": "filter", "path": record["path"], "filters": inputs});
|
|
172
|
+
let filters: Result<Vec<Filter>, RubyException> = inputs.iter().map(build_filter).collect();
|
|
173
|
+
let filters = match filters {
|
|
174
|
+
Ok(filters) => filters,
|
|
175
|
+
Err(error) => {
|
|
176
|
+
output["build_error"] = json!(error_text(&error));
|
|
177
|
+
return output;
|
|
178
|
+
}
|
|
179
|
+
};
|
|
180
|
+
if let [filter] = filters.as_slice() {
|
|
181
|
+
let (results, errors) = satisfy_results(filter, tree, sexps(tree, root).into_iter().map(Value::Sexp));
|
|
182
|
+
output["satisfy"] = json!(results);
|
|
183
|
+
output["errors"] = json!(errors);
|
|
184
|
+
}
|
|
185
|
+
let mut copy = tree.clone();
|
|
186
|
+
match filter_sexp(&mut copy, root, &filters) {
|
|
187
|
+
Ok(()) => {
|
|
188
|
+
let filtered = dump(©, &Value::Sexp(root));
|
|
189
|
+
let original = dump(tree, &Value::Sexp(root));
|
|
190
|
+
output["tree"] = json!(if filtered == original { "=".to_string() } else { filtered });
|
|
191
|
+
}
|
|
192
|
+
Err(error) => output["error"] = json!(error_text(&error)),
|
|
193
|
+
}
|
|
194
|
+
output
|
|
195
|
+
}
|
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
//! `flay-rs`: Flay 2.14.5 results as JSON.
|
|
2
|
+
//!
|
|
3
|
+
//! flay-rs [--mass=N] [--ruby-version=V] [--files-from=LIST] PATHS...
|
|
4
|
+
//! flay-rs --dump [--ruby-version=V] [--files-from=LIST] PATHS...
|
|
5
|
+
//! flay-rs --erb-dump [--ruby-version=V] [--files-from=LIST] FILES...
|
|
6
|
+
//!
|
|
7
|
+
//! `--files-from` reads more paths from a file, one per line.
|
|
8
|
+
//!
|
|
9
|
+
//! `--ruby-version` is the `RUBY_VERSION` whose syntax Flay would parse with
|
|
10
|
+
//! (default: latest).
|
|
11
|
+
//!
|
|
12
|
+
//! The default mode processes all files as one `Flay` instance would, runs
|
|
13
|
+
//! `analyze`, and writes one JSON object in the format `parity/oracle.rb`
|
|
14
|
+
//! writes: the skipped files, `total`, and `hashes`, `masses` and
|
|
15
|
+
//! `identical` in Flay's order.
|
|
16
|
+
//!
|
|
17
|
+
//! `--dump` writes one JSON line per file with its translated sexp tree as
|
|
18
|
+
//! text, or the reason it was skipped.
|
|
19
|
+
//!
|
|
20
|
+
//! `--erb-dump` reads every file as an ERB template, as Flay's `flay_erb.rb`
|
|
21
|
+
//! plugin does, and writes one JSON line per file in the format
|
|
22
|
+
//! `parity/erb_oracle.rb` writes: the Ruby `Flay::Erubi` generates (`src`) or
|
|
23
|
+
//! the exception it raises (`src_error`), and the translated tree or the
|
|
24
|
+
//! reason the file was skipped. Directories are not expanded in this mode.
|
|
25
|
+
//!
|
|
26
|
+
//! Directories are expanded to the `.rb` files under them, sorted. Files are
|
|
27
|
+
//! parsed in parallel and processed in input order.
|
|
28
|
+
|
|
29
|
+
use std::path::Path;
|
|
30
|
+
use std::process::ExitCode;
|
|
31
|
+
|
|
32
|
+
use flay_core::erb::{erb_to_ruby, parse_erb_source};
|
|
33
|
+
use flay_core::{dump_tree, parse_file, Flay, ParsedFile, Skip, DEFAULT_MASS};
|
|
34
|
+
use rayon::prelude::*;
|
|
35
|
+
use serde_json::{json, Value};
|
|
36
|
+
|
|
37
|
+
struct Arguments {
|
|
38
|
+
mass: u64,
|
|
39
|
+
dump: bool,
|
|
40
|
+
erb_dump: bool,
|
|
41
|
+
ruby_version: String,
|
|
42
|
+
paths: Vec<String>,
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
fn parse_arguments() -> Result<Arguments, String> {
|
|
46
|
+
let mut arguments =
|
|
47
|
+
Arguments { mass: DEFAULT_MASS, dump: false, erb_dump: false, ruby_version: "latest".to_string(), paths: Vec::new() };
|
|
48
|
+
for argument in std::env::args().skip(1) {
|
|
49
|
+
match argument.as_str() {
|
|
50
|
+
"--dump" => arguments.dump = true,
|
|
51
|
+
"--erb-dump" => arguments.erb_dump = true,
|
|
52
|
+
other if other.starts_with("--ruby-version=") => {
|
|
53
|
+
arguments.ruby_version = other["--ruby-version=".len()..].to_string();
|
|
54
|
+
}
|
|
55
|
+
other if other.starts_with("--files-from=") => {
|
|
56
|
+
let list = &other["--files-from=".len()..];
|
|
57
|
+
let text = std::fs::read_to_string(list).map_err(|error| format!("{list}: {error}"))?;
|
|
58
|
+
arguments.paths.extend(text.lines().filter(|line| !line.is_empty()).map(str::to_string));
|
|
59
|
+
}
|
|
60
|
+
other if other.starts_with("--mass=") => {
|
|
61
|
+
let value = &other["--mass=".len()..];
|
|
62
|
+
arguments.mass = value.parse().map_err(|_| format!("bad mass: {value}"))?;
|
|
63
|
+
}
|
|
64
|
+
other if other.starts_with('-') => return Err(format!("unknown option: {other}")),
|
|
65
|
+
path => arguments.paths.push(path.to_string()),
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
Ok(arguments)
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
fn expand_paths(paths: &[String]) -> Vec<String> {
|
|
72
|
+
let mut files = Vec::new();
|
|
73
|
+
for path in paths {
|
|
74
|
+
if Path::new(path).is_dir() {
|
|
75
|
+
let mut found = Vec::new();
|
|
76
|
+
collect_ruby_files(Path::new(path), &mut found);
|
|
77
|
+
found.sort();
|
|
78
|
+
files.extend(found);
|
|
79
|
+
} else {
|
|
80
|
+
files.push(path.clone());
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
files
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
fn collect_ruby_files(dir: &Path, found: &mut Vec<String>) {
|
|
87
|
+
let Ok(entries) = std::fs::read_dir(dir) else { return };
|
|
88
|
+
for entry in entries.flatten() {
|
|
89
|
+
let path = entry.path();
|
|
90
|
+
if path.is_dir() {
|
|
91
|
+
collect_ruby_files(&path, found);
|
|
92
|
+
} else if path.extension().is_some_and(|extension| extension == "rb") {
|
|
93
|
+
found.push(path.to_string_lossy().into_owned());
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
fn skip_text(skip: &Skip) -> String {
|
|
99
|
+
match skip {
|
|
100
|
+
Skip::Unreadable(message) => format!("Errno: {message}"),
|
|
101
|
+
Skip::SyntaxError(message) => format!("RubyParser::SyntaxError: {message}"),
|
|
102
|
+
Skip::Raised(exception) => format!("{}: {}", exception.class, exception.message),
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/// One `--erb-dump` record: the converted Ruby, then the translated tree.
|
|
107
|
+
fn erb_dump_record(path: &str, ruby_version: &str) -> Value {
|
|
108
|
+
let source = match std::fs::read(path) {
|
|
109
|
+
Ok(source) => source,
|
|
110
|
+
Err(error) => return json!({ "path": path, "skipped": skip_text(&Skip::Unreadable(error.to_string())) }),
|
|
111
|
+
};
|
|
112
|
+
let mut record = json!({ "path": path });
|
|
113
|
+
match erb_to_ruby(&source) {
|
|
114
|
+
Ok(ruby) => record["src"] = json!(String::from_utf8_lossy(&ruby)),
|
|
115
|
+
Err(exception) => record["src_error"] = json!(format!("{}: {}", exception.class, exception.message)),
|
|
116
|
+
}
|
|
117
|
+
let parsed = parse_erb_source(&source, path, ruby_version);
|
|
118
|
+
match (dump_tree(&parsed), &parsed.outcome) {
|
|
119
|
+
(Some(tree), _) => record["tree"] = json!(tree),
|
|
120
|
+
(None, Err(skip)) => record["skipped"] = json!(skip_text(skip)),
|
|
121
|
+
(None, Ok(_)) => record["tree"] = json!("nil"),
|
|
122
|
+
}
|
|
123
|
+
record
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
fn analysis_json(flay: &Flay, skipped: Vec<Value>) -> Value {
|
|
127
|
+
let hashes: Vec<Value> = flay
|
|
128
|
+
.hashes()
|
|
129
|
+
.iter()
|
|
130
|
+
.map(|(hash, nodes)| {
|
|
131
|
+
let nodes: Vec<Value> = nodes
|
|
132
|
+
.iter()
|
|
133
|
+
.map(|node| {
|
|
134
|
+
let info = flay.node(*node);
|
|
135
|
+
json!([String::from_utf8_lossy(info.sexp_type), info.file, info.line, info.mass])
|
|
136
|
+
})
|
|
137
|
+
.collect();
|
|
138
|
+
json!([hash, nodes])
|
|
139
|
+
})
|
|
140
|
+
.collect();
|
|
141
|
+
let masses: Vec<Value> = flay.masses().iter().map(|(hash, mass)| json!([hash, mass])).collect();
|
|
142
|
+
let identical: Vec<Value> = flay.identical().iter().map(|(hash, same)| json!([hash, same])).collect();
|
|
143
|
+
json!({
|
|
144
|
+
"skipped": skipped,
|
|
145
|
+
"total": flay.total(),
|
|
146
|
+
"hashes": hashes,
|
|
147
|
+
"masses": masses,
|
|
148
|
+
"identical": identical,
|
|
149
|
+
})
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
fn main() -> ExitCode {
|
|
153
|
+
let arguments = match parse_arguments() {
|
|
154
|
+
Ok(arguments) => arguments,
|
|
155
|
+
Err(message) => {
|
|
156
|
+
eprintln!("flay-rs: {message}");
|
|
157
|
+
return ExitCode::from(2);
|
|
158
|
+
}
|
|
159
|
+
};
|
|
160
|
+
let files = expand_paths(&arguments.paths);
|
|
161
|
+
|
|
162
|
+
// Deeply nested code recurses deeply in the translator.
|
|
163
|
+
let pool = rayon::ThreadPoolBuilder::new().stack_size(256 << 20).build().expect("thread pool");
|
|
164
|
+
|
|
165
|
+
if arguments.erb_dump {
|
|
166
|
+
let records: Vec<Value> = pool.install(|| {
|
|
167
|
+
arguments.paths.par_iter().map(|path| erb_dump_record(path, &arguments.ruby_version)).collect()
|
|
168
|
+
});
|
|
169
|
+
for record in records {
|
|
170
|
+
println!("{record}");
|
|
171
|
+
}
|
|
172
|
+
return ExitCode::SUCCESS;
|
|
173
|
+
}
|
|
174
|
+
let parsed: Vec<ParsedFile> =
|
|
175
|
+
pool.install(|| files.par_iter().map(|path| parse_file(path, &arguments.ruby_version)).collect());
|
|
176
|
+
|
|
177
|
+
if arguments.dump {
|
|
178
|
+
for file in &parsed {
|
|
179
|
+
let record = match dump_tree(file) {
|
|
180
|
+
Some(tree) => json!({ "path": file.path, "tree": tree }),
|
|
181
|
+
None => match &file.outcome {
|
|
182
|
+
Err(skip) => json!({ "path": file.path, "skipped": skip_text(skip) }),
|
|
183
|
+
Ok(_) => json!({ "path": file.path, "tree": "nil" }),
|
|
184
|
+
},
|
|
185
|
+
};
|
|
186
|
+
println!("{record}");
|
|
187
|
+
}
|
|
188
|
+
return ExitCode::SUCCESS;
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
let skipped: Vec<Value> = parsed
|
|
192
|
+
.iter()
|
|
193
|
+
.filter_map(|file| file.outcome.as_ref().err().map(|skip| json!([file.path, skip_text(skip)])))
|
|
194
|
+
.collect();
|
|
195
|
+
let mut flay = Flay::new();
|
|
196
|
+
for file in parsed {
|
|
197
|
+
flay.process_parsed(file, flay_core::ProcessOptions { mass_threshold: arguments.mass, fuzzy: None });
|
|
198
|
+
}
|
|
199
|
+
flay.analyze(false);
|
|
200
|
+
println!("{}", analysis_json(&flay, skipped));
|
|
201
|
+
ExitCode::SUCCESS
|
|
202
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
[package]
|
|
2
|
+
name = "flay-core"
|
|
3
|
+
version.workspace = true
|
|
4
|
+
edition.workspace = true
|
|
5
|
+
rust-version.workspace = true
|
|
6
|
+
license.workspace = true
|
|
7
|
+
authors.workspace = true
|
|
8
|
+
homepage.workspace = true
|
|
9
|
+
repository.workspace = true
|
|
10
|
+
description = "Flay 2.14.5's structural duplication analysis for Ruby, computed from Prism's syntax tree"
|
|
11
|
+
readme = "README.md"
|
|
12
|
+
keywords = ["ruby", "flay", "duplication", "static-analysis", "prism"]
|
|
13
|
+
categories = ["development-tools"]
|
|
14
|
+
|
|
15
|
+
[dependencies]
|
|
16
|
+
crc32fast.workspace = true
|
|
17
|
+
indexmap.workspace = true
|
|
18
|
+
rayon.workspace = true
|
|
19
|
+
ruby-prism.workspace = true
|
|
20
|
+
ruby-prism-sys.workspace = true
|