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,544 @@
|
|
|
1
|
+
//! Ruby binding for flay-core: `FlayRs::Flay`, the public API of `::Flay`
|
|
2
|
+
//! 2.14.5 that tools such as RubyCritic use, and the `FlayRs::Node`,
|
|
3
|
+
//! `FlayRs::Flay::Item` and `FlayRs::Flay::Location` structs its results
|
|
4
|
+
//! are made of.
|
|
5
|
+
|
|
6
|
+
mod filters;
|
|
7
|
+
|
|
8
|
+
use std::cell::{Cell, RefCell};
|
|
9
|
+
use std::collections::{HashMap, HashSet};
|
|
10
|
+
use std::sync::atomic::{AtomicBool, Ordering};
|
|
11
|
+
|
|
12
|
+
use flay_core::process::{
|
|
13
|
+
handler_for, parse_files, processing_warning, skip_reason, skip_warnings, unknown_file_type_warning, FileHandler,
|
|
14
|
+
Handler, SkipReason, PROCESS_FUZZY_MESSAGE,
|
|
15
|
+
};
|
|
16
|
+
use flay_core::report::{Item, ReportOptions, TypeFilter};
|
|
17
|
+
use flay_core::ruby2ruby::{sexp_to_ruby, Comments};
|
|
18
|
+
use flay_core::sexp::{RubyString, SexpId, Tree, Value as SexpValue};
|
|
19
|
+
use flay_core::{erb, Flay, ProcessOptions, RubyException};
|
|
20
|
+
use magnus::{
|
|
21
|
+
function, method, prelude::*, scan_args::scan_args, typed_data::Obj, value::ReprValue, Attr, Error, RArray,
|
|
22
|
+
RClass, RHash, RModule, Ruby, Symbol, TryConvert, Value,
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
/// `Flay::DEFAULT_IGNORE`.
|
|
26
|
+
const DEFAULT_IGNORE: &str = ".flayignore";
|
|
27
|
+
|
|
28
|
+
/// Whether `FlayRs::Flay.load_plugins` ran: Flay processes `.erb` files
|
|
29
|
+
/// only once its `flay_erb` plugin is loaded.
|
|
30
|
+
static ERB_PLUGIN_LOADED: AtomicBool = AtomicBool::new(false);
|
|
31
|
+
|
|
32
|
+
/// One `FlayRs::Flay` instance: Flay's state, whether the Ruby views of it
|
|
33
|
+
/// (`@hashes`, `@identical`, `@masses`, `@total`) are current, and the
|
|
34
|
+
/// files it processed as ERB (`diff` reads their Ruby again).
|
|
35
|
+
#[magnus::wrap(class = "FlayRs::Flay", free_immediately, size)]
|
|
36
|
+
#[derive(Default)]
|
|
37
|
+
struct NativeFlay {
|
|
38
|
+
flay: RefCell<Flay>,
|
|
39
|
+
synced: Cell<bool>,
|
|
40
|
+
erb_paths: RefCell<HashSet<String>>,
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
type FlayObj = Obj<NativeFlay>;
|
|
44
|
+
|
|
45
|
+
/// `Flay.default_options`, without `:parser`: FlayRs always parses as
|
|
46
|
+
/// Flay's default parser, `Prism::Translation::RubyParser`, does.
|
|
47
|
+
fn default_options(ruby: &Ruby) -> Result<RHash, Error> {
|
|
48
|
+
let options = ruby.hash_new();
|
|
49
|
+
let entries: [(&str, Value); 10] = [
|
|
50
|
+
("diff", ruby.qfalse().as_value()),
|
|
51
|
+
("mass", ruby.integer_from_i64(flay_core::DEFAULT_MASS as i64).as_value()),
|
|
52
|
+
("summary", ruby.qfalse().as_value()),
|
|
53
|
+
("verbose", ruby.qfalse().as_value()),
|
|
54
|
+
("number", ruby.qtrue().as_value()),
|
|
55
|
+
("timeout", ruby.integer_from_i64(10).as_value()),
|
|
56
|
+
("liberal", ruby.qfalse().as_value()),
|
|
57
|
+
("fuzzy", ruby.qfalse().as_value()),
|
|
58
|
+
("only", ruby.qnil().as_value()),
|
|
59
|
+
("filters", ruby.ary_new().as_value()),
|
|
60
|
+
];
|
|
61
|
+
for (name, value) in entries {
|
|
62
|
+
options.aset(ruby.to_symbol(name), value)?;
|
|
63
|
+
}
|
|
64
|
+
Ok(options)
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/// `Flay.load_plugins`: loads `flay_erb`, the plugin that ships with Flay,
|
|
68
|
+
/// so `process` parses `.erb` files as ERB. Returns the plugin names.
|
|
69
|
+
fn load_plugins(ruby: &Ruby) -> RArray {
|
|
70
|
+
ERB_PLUGIN_LOADED.store(true, Ordering::Relaxed);
|
|
71
|
+
ruby.ary_from_vec(vec!["erb"])
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/// `Flay#initialize(option = {})`.
|
|
75
|
+
fn initialize(ruby: &Ruby, rb_self: FlayObj, args: &[Value]) -> Result<(), Error> {
|
|
76
|
+
let args = scan_args::<(), (Option<Value>,), (), (), (), ()>(args)?;
|
|
77
|
+
let option: Value = match args.optional.0 {
|
|
78
|
+
Some(option) => default_options(ruby)?.funcall("merge", (option,))?,
|
|
79
|
+
None => default_options(ruby)?.as_value(),
|
|
80
|
+
};
|
|
81
|
+
rb_self.ivar_set("@option", option)?;
|
|
82
|
+
let mass: Value = option.funcall("[]", (ruby.to_symbol("mass"),))?;
|
|
83
|
+
rb_self.ivar_set("@mass_threshold", mass)?;
|
|
84
|
+
rb_self.synced.set(false);
|
|
85
|
+
Ok(())
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/// `option[name]`.
|
|
89
|
+
fn option(ruby: &Ruby, rb_self: FlayObj, name: &str) -> Result<Value, Error> {
|
|
90
|
+
rb_self.ivar_get::<_, Value>("@option")?.funcall("[]", (ruby.to_symbol(name),))
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/// `Flay#process(*files)`: parses the files and applies `option[:filters]`
|
|
94
|
+
/// in parallel, then processes them in order with the warnings Flay prints
|
|
95
|
+
/// for each. An exception a filter raises is raised when its file's turn
|
|
96
|
+
/// comes, as Flay's `filter_sexp` raises it out of `process`.
|
|
97
|
+
fn process(ruby: &Ruby, rb_self: FlayObj, files: &[Value]) -> Result<RArray, Error> {
|
|
98
|
+
let paths: Vec<String> = files.iter().map(|file| file.to_r_string()?.to_string()).collect::<Result<_, _>>()?;
|
|
99
|
+
let erb_plugin_loaded = ERB_PLUGIN_LOADED.load(Ordering::Relaxed);
|
|
100
|
+
let handlers: Vec<FileHandler> = paths.iter().map(|path| handler_for(path, erb_plugin_loaded)).collect();
|
|
101
|
+
let kinds: Vec<Handler> = handlers.iter().map(|handler| handler.handler).collect();
|
|
102
|
+
|
|
103
|
+
let version = ruby_version(ruby)?;
|
|
104
|
+
let filters = filters::convert(ruby, option(ruby, rb_self, "filters")?)?;
|
|
105
|
+
let parsed = parse_files(&paths, &kinds, &version, &filters)
|
|
106
|
+
.map_err(|error| Error::new(ruby.exception_runtime_error(), error.to_string()))?;
|
|
107
|
+
|
|
108
|
+
let verbose = option(ruby, rb_self, "verbose")?.to_bool();
|
|
109
|
+
let options = process_options(ruby, rb_self)?;
|
|
110
|
+
for ((path, handler), parsed) in paths.iter().zip(&handlers).zip(parsed) {
|
|
111
|
+
if verbose {
|
|
112
|
+
warn(ruby, processing_warning(path))?;
|
|
113
|
+
}
|
|
114
|
+
if handler.handler == Handler::Unknown {
|
|
115
|
+
warn(ruby, unknown_file_type_warning(&handler.extension))?;
|
|
116
|
+
}
|
|
117
|
+
if let Some(reason) = skip_reason(handler.handler, parsed.as_ref()) {
|
|
118
|
+
let message = skip_message(ruby, rb_self, handler.handler, path, reason)?;
|
|
119
|
+
for warning in skip_warnings(path, &message) {
|
|
120
|
+
warn(ruby, warning)?;
|
|
121
|
+
}
|
|
122
|
+
continue;
|
|
123
|
+
}
|
|
124
|
+
let Some(filtered) = parsed else { continue };
|
|
125
|
+
if let Err(exception) = filtered.filter_result {
|
|
126
|
+
rb_self.synced.set(false);
|
|
127
|
+
return Err(ruby_exception(ruby, &exception));
|
|
128
|
+
}
|
|
129
|
+
if handler.handler == Handler::Erb {
|
|
130
|
+
rb_self.erb_paths.borrow_mut().insert(path.clone());
|
|
131
|
+
}
|
|
132
|
+
rb_self.flay.borrow_mut().process_parsed(filtered.parsed, options);
|
|
133
|
+
}
|
|
134
|
+
rb_self.synced.set(false);
|
|
135
|
+
Ok(ruby.ary_from_iter(files.iter().copied()))
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/// The options `process_parsed` reads: `mass_threshold` and `fuzzy`.
|
|
139
|
+
fn process_options(ruby: &Ruby, rb_self: FlayObj) -> Result<ProcessOptions, Error> {
|
|
140
|
+
let mass_threshold: u64 = rb_self.ivar_get("@mass_threshold")?;
|
|
141
|
+
let fuzzy = option(ruby, rb_self, "fuzzy")?;
|
|
142
|
+
let fuzzy = if fuzzy.to_bool() { Some(i64::try_convert(fuzzy)?) } else { None };
|
|
143
|
+
Ok(ProcessOptions { mass_threshold, fuzzy })
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/// The message of the exception that made Flay skip a file, in Ruby's own
|
|
147
|
+
/// wording where Ruby raises it. With `verbose`, an ERB file whose Ruby
|
|
148
|
+
/// failed to parse first has that Ruby printed, as `Flay#process_erb` does.
|
|
149
|
+
fn skip_message(
|
|
150
|
+
ruby: &Ruby,
|
|
151
|
+
rb_self: FlayObj,
|
|
152
|
+
handler: Handler,
|
|
153
|
+
path: &str,
|
|
154
|
+
reason: SkipReason,
|
|
155
|
+
) -> Result<String, Error> {
|
|
156
|
+
let parses_ruby = matches!(reason, SkipReason::SyntaxError(_) | SkipReason::Raised(_));
|
|
157
|
+
if handler == Handler::Erb && parses_ruby && option(ruby, rb_self, "verbose")?.to_bool() {
|
|
158
|
+
let source = std::fs::read(path).unwrap_or_default();
|
|
159
|
+
if let Ok(generated) = erb::erb_to_ruby(&source) {
|
|
160
|
+
warn(ruby, String::from_utf8_lossy(&generated))?;
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
Ok(match reason {
|
|
164
|
+
SkipReason::ProcessSexp => process_sexp_message(ruby, path)?,
|
|
165
|
+
SkipReason::ProcessFuzzy => PROCESS_FUZZY_MESSAGE.to_string(),
|
|
166
|
+
SkipReason::Unreadable(_) => read_error_message(ruby, path, handler)?,
|
|
167
|
+
SkipReason::SyntaxError(message) => message.to_string(),
|
|
168
|
+
SkipReason::Raised(exception) => exception.message.clone(),
|
|
169
|
+
})
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/// The message of the exception `File.binread` (or `File.read` for ERB)
|
|
173
|
+
/// raises for a file that can't be read.
|
|
174
|
+
fn read_error_message(ruby: &Ruby, path: &str, handler: Handler) -> Result<String, Error> {
|
|
175
|
+
let file_class: RClass = ruby.class_object().const_get("File")?;
|
|
176
|
+
let read = if handler == Handler::Erb { "read" } else { "binread" };
|
|
177
|
+
match file_class.funcall::<_, _, Value>(read, (path,)) {
|
|
178
|
+
Ok(_) => Ok(format!("could not read {path}")),
|
|
179
|
+
Err(error) => exception_message(error),
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/// The message of the NoMethodError `process_sexp(file)` raises when
|
|
184
|
+
/// `filter_sexp` calls `delete_if` on the file name.
|
|
185
|
+
fn process_sexp_message(ruby: &Ruby, path: &str) -> Result<String, Error> {
|
|
186
|
+
match ruby.str_new(path).funcall::<_, _, Value>("delete_if", ()) {
|
|
187
|
+
Ok(_) => Ok(String::new()),
|
|
188
|
+
Err(error) => exception_message(error),
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
fn exception_message(error: Error) -> Result<String, Error> {
|
|
193
|
+
match error.value() {
|
|
194
|
+
Some(exception) => exception.funcall("message", ()),
|
|
195
|
+
None => Err(error),
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/// `Kernel#warn`, so messages go to `$stderr` as Flay's do.
|
|
200
|
+
fn warn(ruby: &Ruby, message: impl AsRef<str>) -> Result<(), Error> {
|
|
201
|
+
ruby.module_kernel().funcall::<_, _, Value>("warn", (message.as_ref(),))?;
|
|
202
|
+
Ok(())
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
/// `RUBY_VERSION`, which decides the syntax Prism parses.
|
|
206
|
+
fn ruby_version(ruby: &Ruby) -> Result<String, Error> {
|
|
207
|
+
ruby.class_object().const_get("RUBY_VERSION")
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
/// `Flay#analyze(filter = nil)`: prunes, finds identical nodes, updates
|
|
211
|
+
/// masses, and returns the report items sorted by mass.
|
|
212
|
+
fn analyze(ruby: &Ruby, rb_self: FlayObj, args: &[Value]) -> Result<RArray, Error> {
|
|
213
|
+
let args = scan_args::<(), (Option<Value>,), (), (), (), ()>(args)?;
|
|
214
|
+
let filter = type_filter(args.optional.0.unwrap_or_else(|| ruby.qnil().as_value()));
|
|
215
|
+
let liberal = option(ruby, rb_self, "liberal")?.to_bool();
|
|
216
|
+
let items = rb_self.flay.borrow_mut().analyze_items(liberal, &filter);
|
|
217
|
+
rb_self.synced.set(false);
|
|
218
|
+
let array = ruby.ary_new_capa(items.len());
|
|
219
|
+
for item in &items {
|
|
220
|
+
array.push(item_to_ruby(ruby, item)?)?;
|
|
221
|
+
}
|
|
222
|
+
Ok(array)
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
/// The `filter` of `Flay#analyze`, compared to each item's `sexp_type`
|
|
226
|
+
/// with `==`.
|
|
227
|
+
fn type_filter(filter: Value) -> TypeFilter {
|
|
228
|
+
if !filter.to_bool() {
|
|
229
|
+
return TypeFilter::All;
|
|
230
|
+
}
|
|
231
|
+
match Symbol::from_value(filter).map(|symbol| symbol.name().map(|name| name.into_owned())) {
|
|
232
|
+
Some(Ok(name)) => TypeFilter::Only(name.into_bytes()),
|
|
233
|
+
_ => TypeFilter::Nothing,
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
/// A `FlayRs::Flay::Item` with its `FlayRs::Flay::Location`s.
|
|
238
|
+
fn item_to_ruby(ruby: &Ruby, item: &Item) -> Result<Value, Error> {
|
|
239
|
+
let flay_class = flay_class(ruby)?;
|
|
240
|
+
let location_class: RClass = flay_class.const_get("Location")?;
|
|
241
|
+
let locations = ruby.ary_new_capa(item.locations.len());
|
|
242
|
+
for location in &item.locations {
|
|
243
|
+
let fuzzy = if location.fuzzy { ruby.to_symbol("fuzzy").as_value() } else { ruby.qnil().as_value() };
|
|
244
|
+
locations.push(location_class.new_instance((location.file.as_str(), location.line, fuzzy))?)?;
|
|
245
|
+
}
|
|
246
|
+
let item_class: RClass = flay_class.const_get("Item")?;
|
|
247
|
+
let name = ruby.to_symbol(String::from_utf8_lossy(&item.name));
|
|
248
|
+
item_class.new_instance((item.structural_hash, name, item.bonus.clone(), item.mass, locations))
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
fn flay_rs_module(ruby: &Ruby) -> Result<RModule, Error> {
|
|
252
|
+
ruby.class_object().const_get("FlayRs")
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
fn flay_class(ruby: &Ruby) -> Result<RClass, Error> {
|
|
256
|
+
flay_rs_module(ruby)?.const_get("Flay")
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
/// `Flay#prune`, conservative or (with `liberal`) liberal.
|
|
260
|
+
fn prune(ruby: &Ruby, rb_self: FlayObj) -> Result<(), Error> {
|
|
261
|
+
let liberal = option(ruby, rb_self, "liberal")?.to_bool();
|
|
262
|
+
rb_self.flay.borrow_mut().prune(liberal);
|
|
263
|
+
rb_self.synced.set(false);
|
|
264
|
+
Ok(())
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
/// `Flay#update_masses`.
|
|
268
|
+
fn update_masses(rb_self: FlayObj) {
|
|
269
|
+
rb_self.flay.borrow_mut().update_masses();
|
|
270
|
+
rb_self.synced.set(false);
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
/// `{ structural_hash => [FlayRs::Node, ...] }`, in Flay's order.
|
|
274
|
+
fn hashes(ruby: &Ruby, rb_self: FlayObj) -> Result<Value, Error> {
|
|
275
|
+
sync(ruby, rb_self)?;
|
|
276
|
+
rb_self.ivar_get("@hashes")
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
/// `{ structural_hash => true/false }`.
|
|
280
|
+
fn identical(ruby: &Ruby, rb_self: FlayObj) -> Result<Value, Error> {
|
|
281
|
+
sync(ruby, rb_self)?;
|
|
282
|
+
rb_self.ivar_get("@identical")
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
/// `{ structural_hash => mass }`.
|
|
286
|
+
fn masses(ruby: &Ruby, rb_self: FlayObj) -> Result<Value, Error> {
|
|
287
|
+
sync(ruby, rb_self)?;
|
|
288
|
+
rb_self.ivar_get("@masses")
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
fn total(rb_self: FlayObj) -> u64 {
|
|
292
|
+
rb_self.flay.borrow().total()
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
/// Builds the Ruby views of the state after it changed. `@hashes` has
|
|
296
|
+
/// Flay's default (`Hash.new { |h, k| h[k] = [] }`).
|
|
297
|
+
fn sync(ruby: &Ruby, rb_self: FlayObj) -> Result<(), Error> {
|
|
298
|
+
if rb_self.synced.get() {
|
|
299
|
+
return Ok(());
|
|
300
|
+
}
|
|
301
|
+
let node_class: RClass = flay_rs_module(ruby)?.const_get("Node")?;
|
|
302
|
+
let default = ruby.proc_from_fn(|ruby, args, _block| -> Result<Value, Error> {
|
|
303
|
+
let hash = RHash::from_value(args[0]).expect("Hash default proc receives the hash");
|
|
304
|
+
let list = ruby.ary_new();
|
|
305
|
+
hash.aset(args[1], list)?;
|
|
306
|
+
Ok(list.as_value())
|
|
307
|
+
});
|
|
308
|
+
let hashes: RHash = ruby.class_hash().funcall_with_block("new", (), default)?;
|
|
309
|
+
let identical = ruby.hash_new();
|
|
310
|
+
let masses = ruby.hash_new();
|
|
311
|
+
{
|
|
312
|
+
let flay = rb_self.flay.borrow();
|
|
313
|
+
for (hash, nodes) in flay.hashes() {
|
|
314
|
+
let list = ruby.ary_new_capa(nodes.len());
|
|
315
|
+
for node in nodes {
|
|
316
|
+
let info = flay.node(*node);
|
|
317
|
+
let sexp_type = ruby.to_symbol(String::from_utf8_lossy(info.sexp_type));
|
|
318
|
+
list.push(node_class.new_instance((sexp_type, info.file, info.line, info.mass, *hash, info.modified))?)?;
|
|
319
|
+
}
|
|
320
|
+
hashes.aset(*hash, list)?;
|
|
321
|
+
}
|
|
322
|
+
for (hash, same) in flay.identical() {
|
|
323
|
+
identical.aset(*hash, *same)?;
|
|
324
|
+
}
|
|
325
|
+
for (hash, mass) in flay.masses() {
|
|
326
|
+
masses.aset(*hash, *mass)?;
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
rb_self.ivar_set("@hashes", hashes)?;
|
|
330
|
+
rb_self.ivar_set("@identical", identical)?;
|
|
331
|
+
rb_self.ivar_set("@masses", masses)?;
|
|
332
|
+
rb_self.synced.set(true);
|
|
333
|
+
Ok(())
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
/// `Flay#summary`: `{ file => score }` (`Hash.new 0`).
|
|
337
|
+
fn summary(ruby: &Ruby, rb_self: FlayObj) -> Result<RHash, Error> {
|
|
338
|
+
let score = ruby.hash_new();
|
|
339
|
+
score.funcall::<_, _, Value>("default=", (0,))?;
|
|
340
|
+
for (file, value) in rb_self.flay.borrow().summary() {
|
|
341
|
+
score.aset(file, value)?;
|
|
342
|
+
}
|
|
343
|
+
Ok(score)
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
/// `Flay#report(io = $stdout)`: analyzes, then writes Flay's report to `io`
|
|
347
|
+
/// with `puts`, then raises the exception Flay raises, if any.
|
|
348
|
+
fn report(ruby: &Ruby, rb_self: FlayObj, args: &[Value]) -> Result<(), Error> {
|
|
349
|
+
let args = scan_args::<(), (Option<Value>,), (), (), (), ()>(args)?;
|
|
350
|
+
let io = match args.optional.0 {
|
|
351
|
+
Some(io) => io,
|
|
352
|
+
None => ruby.eval("$stdout")?,
|
|
353
|
+
};
|
|
354
|
+
let options = ReportOptions {
|
|
355
|
+
only: type_filter(option(ruby, rb_self, "only")?),
|
|
356
|
+
summary: option(ruby, rb_self, "summary")?.to_bool(),
|
|
357
|
+
number: option(ruby, rb_self, "number")?.to_bool(),
|
|
358
|
+
diff: option(ruby, rb_self, "diff")?.to_bool(),
|
|
359
|
+
liberal: option(ruby, rb_self, "liberal")?.to_bool(),
|
|
360
|
+
};
|
|
361
|
+
let mut sources = DiffSources { erb_paths: &rb_self.erb_paths.borrow(), comments: HashMap::new(), read_error: None };
|
|
362
|
+
let mut lines = Vec::new();
|
|
363
|
+
let result = rb_self.flay.borrow_mut().report(
|
|
364
|
+
&options,
|
|
365
|
+
|path, tree, sexp, elements| sources.sexp_to_rb(ruby, path, tree, sexp, elements),
|
|
366
|
+
&mut lines,
|
|
367
|
+
);
|
|
368
|
+
rb_self.synced.set(false);
|
|
369
|
+
// Flay prints each line as it goes, so the lines before an exception
|
|
370
|
+
// are printed.
|
|
371
|
+
for line in lines {
|
|
372
|
+
io.funcall::<_, _, Value>("puts", (ruby_string(ruby, &line)?,))?;
|
|
373
|
+
}
|
|
374
|
+
if let Some(error) = sources.read_error {
|
|
375
|
+
return Err(error);
|
|
376
|
+
}
|
|
377
|
+
result.map_err(|exception| ruby_exception(ruby, &exception))
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
/// What the `diff` report needs to write a node as Ruby: the comments of
|
|
381
|
+
/// each file's tree, read again from the file (for an ERB file, from the
|
|
382
|
+
/// Ruby its ERB compiles to).
|
|
383
|
+
struct DiffSources<'a> {
|
|
384
|
+
erb_paths: &'a HashSet<String>,
|
|
385
|
+
comments: HashMap<String, Comments>,
|
|
386
|
+
/// The error reading a file raised; the report stops at it.
|
|
387
|
+
read_error: Option<Error>,
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
impl DiffSources<'_> {
|
|
391
|
+
/// `Flay#sexp_to_rb`, with Ruby2Ruby ported to Rust.
|
|
392
|
+
fn sexp_to_rb(
|
|
393
|
+
&mut self,
|
|
394
|
+
ruby: &Ruby,
|
|
395
|
+
path: &str,
|
|
396
|
+
tree: &Tree,
|
|
397
|
+
sexp: SexpId,
|
|
398
|
+
elements: &[SexpValue],
|
|
399
|
+
) -> Result<RubyString, RubyException> {
|
|
400
|
+
if !self.comments.contains_key(path) {
|
|
401
|
+
let source = self.source(ruby, path)?;
|
|
402
|
+
self.comments.insert(path.to_string(), Comments::new(&source, tree));
|
|
403
|
+
}
|
|
404
|
+
sexp_to_ruby(tree, &self.comments[path], sexp, elements)
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
/// The Ruby source of a processed file.
|
|
408
|
+
fn source(&mut self, ruby: &Ruby, path: &str) -> Result<Vec<u8>, RubyException> {
|
|
409
|
+
let file_class: RClass = ruby.class_object().const_get("File").map_err(|error| self.stop(error))?;
|
|
410
|
+
let contents: magnus::RString = file_class.funcall("binread", (path,)).map_err(|error| self.stop(error))?;
|
|
411
|
+
// SAFETY: the bytes are copied before any Ruby code runs.
|
|
412
|
+
let bytes = unsafe { contents.as_slice() }.to_vec();
|
|
413
|
+
if self.erb_paths.contains(path) {
|
|
414
|
+
return erb::erb_to_ruby(&bytes);
|
|
415
|
+
}
|
|
416
|
+
Ok(bytes)
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
/// Keeps a Ruby error to raise once the report stops.
|
|
420
|
+
fn stop(&mut self, error: Error) -> RubyException {
|
|
421
|
+
self.read_error = Some(error);
|
|
422
|
+
RubyException { class: "RuntimeError", message: String::new() }
|
|
423
|
+
}
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
/// A flay-core exception as a Ruby error of the same class.
|
|
427
|
+
fn ruby_exception(ruby: &Ruby, exception: &RubyException) -> Error {
|
|
428
|
+
// `Object.const_get` resolves nested names such as
|
|
429
|
+
// `Encoding::CompatibilityError`.
|
|
430
|
+
let class = match ruby.class_object().funcall::<_, _, magnus::ExceptionClass>("const_get", (exception.class,)) {
|
|
431
|
+
Ok(class) => class,
|
|
432
|
+
Err(error) => return error,
|
|
433
|
+
};
|
|
434
|
+
let mut message = exception.message.clone();
|
|
435
|
+
if exception.class == "NoMethodError" {
|
|
436
|
+
if let Some(ruby_message) = no_method_error_message_for_literal(ruby, &message) {
|
|
437
|
+
message = ruby_message;
|
|
438
|
+
} else if quotes_method_names_with_apostrophes(ruby) {
|
|
439
|
+
message = message.replacen('`', "'", 1);
|
|
440
|
+
}
|
|
441
|
+
}
|
|
442
|
+
if exception.class == "Encoding::CompatibilityError" {
|
|
443
|
+
match binary_encoding_name(ruby) {
|
|
444
|
+
Ok(name) => message = message.replace("ASCII-8BIT", &name),
|
|
445
|
+
Err(error) => return error,
|
|
446
|
+
}
|
|
447
|
+
}
|
|
448
|
+
Error::new(class, message)
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
/// For a NoMethodError message flay-core writes for nil, true or false
|
|
452
|
+
/// (`` undefined method `name' for nil ``), the message the running Ruby
|
|
453
|
+
/// gives: Ruby 3.4 and later quote `'name'`.
|
|
454
|
+
fn no_method_error_message_for_literal(ruby: &Ruby, message: &str) -> Option<String> {
|
|
455
|
+
let rest = message.strip_prefix("undefined method `")?;
|
|
456
|
+
let (name, receiver) = rest.split_once("' for ")?;
|
|
457
|
+
let receiver = match receiver {
|
|
458
|
+
"nil" => ruby.qnil().as_value(),
|
|
459
|
+
"true" => ruby.qtrue().as_value(),
|
|
460
|
+
"false" => ruby.qfalse().as_value(),
|
|
461
|
+
_ => return None,
|
|
462
|
+
};
|
|
463
|
+
let error = receiver.funcall::<_, _, Value>("public_send", (ruby.to_symbol(name),)).err()?;
|
|
464
|
+
if !error.is_kind_of(ruby.exception_no_method_error()) {
|
|
465
|
+
return None;
|
|
466
|
+
}
|
|
467
|
+
exception_message(error).ok()
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
/// Whether NoMethodError messages quote the method name as `'name'`, as
|
|
471
|
+
/// Ruby 3.4 and later do. flay-core writes them as Ruby 3.3 does:
|
|
472
|
+
/// `` `name' ``.
|
|
473
|
+
fn quotes_method_names_with_apostrophes(ruby: &Ruby) -> bool {
|
|
474
|
+
match ruby.qnil().funcall::<_, _, Value>("flay_rs_undefined_method", ()) {
|
|
475
|
+
Ok(_) => false,
|
|
476
|
+
Err(error) => exception_message(error).is_ok_and(|message| message.contains("'flay_rs_undefined_method'")),
|
|
477
|
+
}
|
|
478
|
+
}
|
|
479
|
+
|
|
480
|
+
/// How `Encoding::CompatibilityError` messages name ASCII-8BIT:
|
|
481
|
+
/// `ASCII-8BIT` before Ruby 3.4, `BINARY (ASCII-8BIT)` since (the name
|
|
482
|
+
/// `Encoding#inspect` shows). flay-core writes `ASCII-8BIT`.
|
|
483
|
+
fn binary_encoding_name(ruby: &Ruby) -> Result<String, Error> {
|
|
484
|
+
let inspect: String = ruby.eval("Encoding::ASCII_8BIT.inspect")?;
|
|
485
|
+
Ok(inspect.trim_start_matches("#<Encoding:").trim_end_matches('>').to_string())
|
|
486
|
+
}
|
|
487
|
+
|
|
488
|
+
/// A flay-core String as a Ruby String in its encoding.
|
|
489
|
+
fn ruby_string(ruby: &Ruby, string: &RubyString) -> Result<magnus::RString, Error> {
|
|
490
|
+
let rstring = ruby.str_from_slice(&string.bytes);
|
|
491
|
+
rstring.funcall::<_, _, Value>("force_encoding", (string.encoding,))?;
|
|
492
|
+
Ok(rstring)
|
|
493
|
+
}
|
|
494
|
+
|
|
495
|
+
/// Defines a Struct class with the members and the aliases given.
|
|
496
|
+
fn define_struct(ruby: &Ruby, members: &[&str], aliases: &[(&str, &str)]) -> Result<RClass, Error> {
|
|
497
|
+
let symbols: Vec<Symbol> = members.iter().map(|member| ruby.to_symbol(member)).collect();
|
|
498
|
+
let class: RClass = ruby.class_struct().funcall("new", symbols.as_slice())?;
|
|
499
|
+
for (alias, original) in aliases {
|
|
500
|
+
class.define_alias(*alias, *original)?;
|
|
501
|
+
}
|
|
502
|
+
Ok(class)
|
|
503
|
+
}
|
|
504
|
+
|
|
505
|
+
#[magnus::init]
|
|
506
|
+
fn init(ruby: &Ruby) -> Result<(), Error> {
|
|
507
|
+
let flay_rs = ruby.define_module("FlayRs")?;
|
|
508
|
+
let native = flay_rs.define_module("Native")?;
|
|
509
|
+
native.const_set("FLAY_COMPAT", flay_core::FLAY_COMPAT)?;
|
|
510
|
+
|
|
511
|
+
// A node in `Flay#hashes`: what Flay's results read from a Sexp
|
|
512
|
+
// (`first` is its type; `modified?` is true for nodes `fuzzy` made).
|
|
513
|
+
let node = define_struct(
|
|
514
|
+
ruby,
|
|
515
|
+
&["sexp_type", "file", "line", "mass", "structural_hash", "modified"],
|
|
516
|
+
&[("first", "sexp_type"), ("modified?", "modified")],
|
|
517
|
+
)?;
|
|
518
|
+
flay_rs.const_set("Node", node)?;
|
|
519
|
+
|
|
520
|
+
let class = flay_rs.define_class("Flay", ruby.class_object())?;
|
|
521
|
+
class.define_alloc_func::<NativeFlay>();
|
|
522
|
+
class.const_set("DEFAULT_IGNORE", DEFAULT_IGNORE)?;
|
|
523
|
+
class.const_set(
|
|
524
|
+
"Item",
|
|
525
|
+
define_struct(ruby, &["structural_hash", "name", "bonus", "mass", "locations"], &[("identical?", "bonus")])?,
|
|
526
|
+
)?;
|
|
527
|
+
class.const_set("Location", define_struct(ruby, &["file", "line", "fuzzy"], &[("fuzzy?", "fuzzy")])?)?;
|
|
528
|
+
class.define_singleton_method("default_options", function!(default_options, 0))?;
|
|
529
|
+
class.define_singleton_method("load_plugins", function!(load_plugins, 0))?;
|
|
530
|
+
class.define_attr("mass_threshold", Attr::ReadWrite)?;
|
|
531
|
+
class.define_attr("option", Attr::Read)?;
|
|
532
|
+
class.define_method("initialize", method!(initialize, -1))?;
|
|
533
|
+
class.define_method("process", method!(process, -1))?;
|
|
534
|
+
class.define_method("analyze", method!(analyze, -1))?;
|
|
535
|
+
class.define_method("prune", method!(prune, 0))?;
|
|
536
|
+
class.define_method("update_masses", method!(update_masses, 0))?;
|
|
537
|
+
class.define_method("hashes", method!(hashes, 0))?;
|
|
538
|
+
class.define_method("identical", method!(identical, 0))?;
|
|
539
|
+
class.define_method("masses", method!(masses, 0))?;
|
|
540
|
+
class.define_method("total", method!(total, 0))?;
|
|
541
|
+
class.define_method("summary", method!(summary, 0))?;
|
|
542
|
+
class.define_method("report", method!(report, -1))?;
|
|
543
|
+
Ok(())
|
|
544
|
+
}
|
data/lib/flay_rs.rb
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require_relative "flay_rs/version"
|
|
4
|
+
|
|
5
|
+
# Precompiled gems ship one library per Ruby minor version.
|
|
6
|
+
begin
|
|
7
|
+
require_relative "flay_rs/#{RUBY_VERSION[/\d+\.\d+/]}/flay_rs"
|
|
8
|
+
rescue LoadError
|
|
9
|
+
require_relative "flay_rs/flay_rs"
|
|
10
|
+
end
|
|
11
|
+
|
|
12
|
+
# Flay 2.14.5's duplication analysis, computed in Rust from Prism's syntax
|
|
13
|
+
# tree.
|
|
14
|
+
#
|
|
15
|
+
# The extension defines FlayRs::Flay, which has the public API of ::Flay that
|
|
16
|
+
# tools such as RubyCritic use, and the FlayRs::Node, FlayRs::Flay::Item and
|
|
17
|
+
# FlayRs::Flay::Location structs its results are made of (see
|
|
18
|
+
# ext/flay_rs/src/lib.rs).
|
metadata
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
--- !ruby/object:Gem::Specification
|
|
2
|
+
name: flay-rs
|
|
3
|
+
version: !ruby/object:Gem::Version
|
|
4
|
+
version: 0.1.0
|
|
5
|
+
platform: ruby
|
|
6
|
+
authors:
|
|
7
|
+
- Eric Burns
|
|
8
|
+
bindir: bin
|
|
9
|
+
cert_chain: []
|
|
10
|
+
date: 1980-01-02 00:00:00.000000000 Z
|
|
11
|
+
dependencies:
|
|
12
|
+
- !ruby/object:Gem::Dependency
|
|
13
|
+
name: rb_sys
|
|
14
|
+
requirement: !ruby/object:Gem::Requirement
|
|
15
|
+
requirements:
|
|
16
|
+
-
|
|
17
|
+
- ~>
|
|
18
|
+
- !ruby/object:Gem::Version
|
|
19
|
+
version: 0.9.130
|
|
20
|
+
type: :runtime
|
|
21
|
+
prerelease: false
|
|
22
|
+
version_requirements: !ruby/object:Gem::Requirement
|
|
23
|
+
requirements:
|
|
24
|
+
-
|
|
25
|
+
- ~>
|
|
26
|
+
- !ruby/object:Gem::Version
|
|
27
|
+
version: 0.9.130
|
|
28
|
+
description: |
|
|
29
|
+
FlayRs reproduces Flay 2.14.5's structural hashes, masses, identical
|
|
30
|
+
checks and node locations by building the same sexp tree in Rust.
|
|
31
|
+
executables: []
|
|
32
|
+
extensions:
|
|
33
|
+
- ext/flay_rs/extconf.rb
|
|
34
|
+
extra_rdoc_files: []
|
|
35
|
+
files:
|
|
36
|
+
- Cargo.lock
|
|
37
|
+
- Cargo.toml
|
|
38
|
+
- DIVERGENCES.md
|
|
39
|
+
- LICENSE
|
|
40
|
+
- README.md
|
|
41
|
+
- THIRD_PARTY_NOTICES.md
|
|
42
|
+
- crates/flay-cli/Cargo.toml
|
|
43
|
+
- crates/flay-cli/src/bin/flay-matcher-parity.rs
|
|
44
|
+
- crates/flay-cli/src/main.rs
|
|
45
|
+
- crates/flay-core/Cargo.toml
|
|
46
|
+
- crates/flay-core/src/attach_comments.rs
|
|
47
|
+
- crates/flay-core/src/erb.rs
|
|
48
|
+
- crates/flay-core/src/lib.rs
|
|
49
|
+
- crates/flay-core/src/matcher.rs
|
|
50
|
+
- crates/flay-core/src/matcher/parser.rs
|
|
51
|
+
- crates/flay-core/src/matcher/regexp.rs
|
|
52
|
+
- crates/flay-core/src/matcher/ruby_text.rs
|
|
53
|
+
- crates/flay-core/src/matcher/serialized.rs
|
|
54
|
+
- crates/flay-core/src/process.rs
|
|
55
|
+
- crates/flay-core/src/report.rs
|
|
56
|
+
- crates/flay-core/src/ruby2ruby.rs
|
|
57
|
+
- crates/flay-core/src/ruby_format.rs
|
|
58
|
+
- crates/flay-core/src/ruby_sort.rs
|
|
59
|
+
- crates/flay-core/src/sexp.rs
|
|
60
|
+
- crates/flay-core/src/translate.rs
|
|
61
|
+
- crates/flay-core/tests/ruby2ruby_parity.rs
|
|
62
|
+
- ext/flay_rs/Cargo.toml
|
|
63
|
+
- ext/flay_rs/extconf.rb
|
|
64
|
+
- ext/flay_rs/src/filters.rs
|
|
65
|
+
- ext/flay_rs/src/lib.rs
|
|
66
|
+
- lib/flay_rs.rb
|
|
67
|
+
- lib/flay_rs/version.rb
|
|
68
|
+
homepage: "https://gloom.fm"
|
|
69
|
+
licenses:
|
|
70
|
+
- MIT
|
|
71
|
+
metadata:
|
|
72
|
+
source_code_uri: "https://github.com/gloom-fm/flay-rs"
|
|
73
|
+
bug_tracker_uri: "https://github.com/gloom-fm/flay-rs/issues"
|
|
74
|
+
rubygems_mfa_required: "true"
|
|
75
|
+
rdoc_options: []
|
|
76
|
+
require_paths:
|
|
77
|
+
- lib
|
|
78
|
+
required_ruby_version: !ruby/object:Gem::Requirement
|
|
79
|
+
requirements:
|
|
80
|
+
-
|
|
81
|
+
- ">="
|
|
82
|
+
- !ruby/object:Gem::Version
|
|
83
|
+
version: "3.3"
|
|
84
|
+
required_rubygems_version: !ruby/object:Gem::Requirement
|
|
85
|
+
requirements:
|
|
86
|
+
-
|
|
87
|
+
- ">="
|
|
88
|
+
- !ruby/object:Gem::Version
|
|
89
|
+
version: "0"
|
|
90
|
+
requirements: []
|
|
91
|
+
rubygems_version: 4.1.1
|
|
92
|
+
specification_version: 4
|
|
93
|
+
summary: "Flay 2.14.5 duplication analysis, computed in Rust from Prism's syntax tree"
|
|
94
|
+
test_files: []
|