flog-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 +486 -0
- data/Cargo.toml +22 -0
- data/DIVERGENCES.md +14 -0
- data/LICENSE +22 -0
- data/README.md +100 -0
- data/THIRD_PARTY_NOTICES.md +45 -0
- data/crates/flog-cli/Cargo.toml +23 -0
- data/crates/flog-cli/src/main.rs +224 -0
- data/crates/flog-core/Cargo.toml +18 -0
- data/crates/flog-core/src/attach_comments.rs +271 -0
- data/crates/flog-core/src/lib.rs +307 -0
- data/crates/flog-core/src/literal.rs +217 -0
- data/crates/flog-core/src/ruby_format.rs +131 -0
- data/crates/flog-core/src/ruby_sort.rs +192 -0
- data/crates/flog-core/src/scorer.rs +1851 -0
- data/crates/flog-core/src/scores.rs +96 -0
- data/crates/flog-core/src/syntax_error.rs +145 -0
- data/crates/flog-core/src/translation.rs +487 -0
- data/ext/flog_rs/Cargo.toml +18 -0
- data/ext/flog_rs/extconf.rb +6 -0
- data/ext/flog_rs/src/flog.rs +493 -0
- data/ext/flog_rs/src/lib.rs +39 -0
- data/lib/flog_rs/version.rb +8 -0
- data/lib/flog_rs.rb +16 -0
- metadata +86 -0
|
@@ -0,0 +1,493 @@
|
|
|
1
|
+
//! `FlogRs::Flog`: the public API of `::Flog` 4.10.0 that tools such as
|
|
2
|
+
//! RubyCritic use. flog-core scores each file; this module merges each
|
|
3
|
+
//! file's additions into the instance's results and computes totals, ports
|
|
4
|
+
//! of the `Flog` methods of the same names.
|
|
5
|
+
//!
|
|
6
|
+
//! The results live in the same instance variables Flog uses (`@calls`,
|
|
7
|
+
//! `@totals`, `@total_score`, ...), as Ruby Hashes with Flog's defaults, so
|
|
8
|
+
//! they are the objects Flog's readers return: `calls` creates a tally for a
|
|
9
|
+
//! new label, `totals` answers 0 for a missing one, and `total_score` and
|
|
10
|
+
//! `average` are the Integer 0 when nothing was scored.
|
|
11
|
+
|
|
12
|
+
use flog_core::ruby_sort::sort_by_numeric_keys;
|
|
13
|
+
use flog_core::{score_file, score_source, FileOutcome, FileResult, FlogException, SyntaxErrorException};
|
|
14
|
+
use magnus::{
|
|
15
|
+
prelude::*, r_regexp::Opts, scan_args::scan_args, value::ReprValue, Error, Float, RArray, RClass, RHash,
|
|
16
|
+
RObject, RString, Ruby, Symbol, TryConvert, Value,
|
|
17
|
+
};
|
|
18
|
+
use rayon::prelude::*;
|
|
19
|
+
|
|
20
|
+
/// `Flog::DEFAULT_THRESHOLD`.
|
|
21
|
+
pub const DEFAULT_THRESHOLD: f64 = 0.60;
|
|
22
|
+
|
|
23
|
+
/// `Flog#initialize(option = {})`.
|
|
24
|
+
pub fn initialize(ruby: &Ruby, rb_self: RObject, args: &[Value]) -> Result<(), Error> {
|
|
25
|
+
let args = scan_args::<(), (Option<Value>,), (), (), (), ()>(args)?;
|
|
26
|
+
let option: Value = match args.optional.0 {
|
|
27
|
+
Some(option) => option.funcall("dup", ())?,
|
|
28
|
+
None => ruby.hash_new().as_value(),
|
|
29
|
+
};
|
|
30
|
+
rb_self.ivar_set("@option", option)?;
|
|
31
|
+
rb_self.ivar_set("@mass", ruby.hash_new())?;
|
|
32
|
+
rb_self.ivar_set("@method_locations", ruby.hash_new())?;
|
|
33
|
+
let threshold: Value = option.funcall("[]", (ruby.to_symbol("threshold"),))?;
|
|
34
|
+
let threshold = if threshold.to_bool() { threshold } else { ruby.float_from_f64(DEFAULT_THRESHOLD).as_value() };
|
|
35
|
+
rb_self.ivar_set("@threshold", threshold)?;
|
|
36
|
+
reset(ruby, rb_self)
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/// `Flog#reset`: clears every result.
|
|
40
|
+
pub fn reset(ruby: &Ruby, rb_self: RObject) -> Result<(), Error> {
|
|
41
|
+
rb_self.ivar_set("@totals", ruby.qnil())?;
|
|
42
|
+
rb_self.ivar_set("@total_score", ruby.qnil())?;
|
|
43
|
+
rb_self.ivar_set("@multiplier", 1.0)?;
|
|
44
|
+
rb_self.ivar_set("@calls", hash_with_default_proc(ruby, new_tally)?)?;
|
|
45
|
+
rb_self.ivar_set("@method_scores", hash_with_default_proc(ruby, new_method_score_list)?)?;
|
|
46
|
+
rb_self.ivar_set("@scores", hash_with_zero_default(ruby)?)?;
|
|
47
|
+
let method_locations: Value = rb_self.ivar_get("@method_locations")?;
|
|
48
|
+
method_locations.funcall::<_, _, Value>("clear", ())?;
|
|
49
|
+
Ok(())
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/// `Hash.new { |h, k| h[k] = ... }` with `default` making the new value.
|
|
53
|
+
fn hash_with_default_proc(ruby: &Ruby, default: fn(&Ruby) -> Result<Value, Error>) -> Result<RHash, Error> {
|
|
54
|
+
let block = ruby.proc_from_fn(move |ruby, args, _block| -> Result<Value, Error> {
|
|
55
|
+
let (hash, key) = (RHash::from_value(args[0]).expect("Hash default proc receives the hash"), args[1]);
|
|
56
|
+
let value = default(ruby)?;
|
|
57
|
+
hash.aset(key, value)?;
|
|
58
|
+
Ok(value)
|
|
59
|
+
});
|
|
60
|
+
ruby.class_hash().funcall_with_block("new", (), block)
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/// A tally for a new label in `calls`: `Hash.new 0`.
|
|
64
|
+
fn new_tally(ruby: &Ruby) -> Result<Value, Error> {
|
|
65
|
+
Ok(hash_with_zero_default(ruby)?.as_value())
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/// A list for a new class in `method_scores`: `[]`.
|
|
69
|
+
fn new_method_score_list(ruby: &Ruby) -> Result<Value, Error> {
|
|
70
|
+
Ok(ruby.ary_new().as_value())
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/// `Hash.new 0`.
|
|
74
|
+
fn hash_with_zero_default(ruby: &Ruby) -> Result<RHash, Error> {
|
|
75
|
+
let hash = ruby.hash_new();
|
|
76
|
+
hash.funcall::<_, _, Value>("default=", (0,))?;
|
|
77
|
+
Ok(hash)
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/// `Flog#flog(*files)`: scores each readable file (or standard input for
|
|
81
|
+
/// `"-"`), then calculates totals.
|
|
82
|
+
pub fn flog(ruby: &Ruby, rb_self: RObject, files: &[Value]) -> Result<(), Error> {
|
|
83
|
+
let file_class: RClass = ruby.class_object().const_get("File")?;
|
|
84
|
+
let timeout: Value = option(ruby, rb_self, "timeout")?;
|
|
85
|
+
for &file in files {
|
|
86
|
+
let is_stdin = is_stdin_name(file);
|
|
87
|
+
if !is_stdin && !file_class.funcall::<_, _, bool>("readable?", (file,))? {
|
|
88
|
+
continue;
|
|
89
|
+
}
|
|
90
|
+
let source: RString = if is_stdin {
|
|
91
|
+
ruby.eval::<Value>("$stdin")?.funcall("read", ())?
|
|
92
|
+
} else {
|
|
93
|
+
file_class.funcall("binread", (file,))?
|
|
94
|
+
};
|
|
95
|
+
flog_ruby(ruby, rb_self, &[source.as_value(), file, timeout])?;
|
|
96
|
+
}
|
|
97
|
+
calculate_total_scores(ruby, rb_self)
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/// `file == "-"`.
|
|
101
|
+
fn is_stdin_name(file: Value) -> bool {
|
|
102
|
+
// SAFETY: the bytes are compared before any Ruby code runs.
|
|
103
|
+
RString::from_value(file).is_some_and(|name| unsafe { name.as_slice() } == b"-")
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/// `option[name]`.
|
|
107
|
+
fn option(ruby: &Ruby, rb_self: RObject, name: &str) -> Result<Value, Error> {
|
|
108
|
+
let option: Value = rb_self.ivar_get("@option")?;
|
|
109
|
+
option.funcall("[]", (ruby.to_symbol(name),))
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/// `Flog#flog_ruby(ruby, file = "-", timeout = 10)`: scores source and
|
|
113
|
+
/// handles a syntax error as Flog does (see [`handle_syntax_error`]).
|
|
114
|
+
pub fn flog_ruby(ruby: &Ruby, rb_self: RObject, args: &[Value]) -> Result<(), Error> {
|
|
115
|
+
let (source, file) = source_and_file(ruby, args)?;
|
|
116
|
+
let result = score(ruby, rb_self, source, file)?;
|
|
117
|
+
if let FileOutcome::SyntaxError { message, .. } = &result.outcome {
|
|
118
|
+
let erb_in_source = || ruby.reg_new("<%|%>", Opts::new()).and_then(|erb| erb.reg_match(source));
|
|
119
|
+
return handle_syntax_error(ruby, rb_self, message, file, |exception_mentions_erb| {
|
|
120
|
+
Ok(exception_mentions_erb || erb_in_source()?.is_some())
|
|
121
|
+
});
|
|
122
|
+
}
|
|
123
|
+
add_file_result(ruby, rb_self, &result)
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/// `Flog#flog_ruby!(ruby, file = "-", timeout = 10)`: scores source without
|
|
127
|
+
/// handling syntax errors. The timeout is accepted and ignored.
|
|
128
|
+
pub fn flog_ruby_bang(ruby: &Ruby, rb_self: RObject, args: &[Value]) -> Result<(), Error> {
|
|
129
|
+
let (source, file) = source_and_file(ruby, args)?;
|
|
130
|
+
let result = score(ruby, rb_self, source, file)?;
|
|
131
|
+
if let FileOutcome::SyntaxError { message, .. } = &result.outcome {
|
|
132
|
+
return Err(syntax_error(ruby, message)?.into());
|
|
133
|
+
}
|
|
134
|
+
add_file_result(ruby, rb_self, &result)
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/// The `ruby` and `file` arguments of `flog_ruby` and `flog_ruby!`.
|
|
138
|
+
fn source_and_file(ruby: &Ruby, args: &[Value]) -> Result<(RString, Value), Error> {
|
|
139
|
+
let args = scan_args::<(RString,), (Option<Value>, Option<Value>), (), (), (), ()>(args)?;
|
|
140
|
+
let file = args.optional.0.unwrap_or_else(|| ruby.str_new("-").as_value());
|
|
141
|
+
Ok((args.required.0, file))
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/// Warns `** flogging FILE` when `verbose` is set, then scores the source
|
|
145
|
+
/// with flog-core.
|
|
146
|
+
fn score(ruby: &Ruby, rb_self: RObject, source: RString, file: Value) -> Result<FileResult, Error> {
|
|
147
|
+
if option(ruby, rb_self, "verbose")?.to_bool() {
|
|
148
|
+
warn(rb_self, format!("** flogging {}", file.to_r_string()?.to_string()?))?;
|
|
149
|
+
}
|
|
150
|
+
let path = file.to_r_string()?.to_string()?;
|
|
151
|
+
let methods_only = option(ruby, rb_self, "methods")?.to_bool();
|
|
152
|
+
// SAFETY: the bytes are copied before any Ruby code runs.
|
|
153
|
+
let bytes = unsafe { source.as_slice() }.to_vec();
|
|
154
|
+
Ok(score_source(&bytes, &path, methods_only, &ruby_version(ruby)?))
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/// `RUBY_VERSION`, which decides the syntax Prism parses.
|
|
158
|
+
fn ruby_version(ruby: &Ruby) -> Result<String, Error> {
|
|
159
|
+
ruby.class_object().const_get("RUBY_VERSION")
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/// `Kernel#warn`, so the message goes to `$stderr` as Flog's do.
|
|
163
|
+
fn warn(rb_self: RObject, message: impl AsRef<str>) -> Result<(), Error> {
|
|
164
|
+
rb_self.funcall::<_, _, Value>("warn", (message.as_ref(),))?;
|
|
165
|
+
Ok(())
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/// A `FlogRs::SyntaxError` with the message Flog's parser raises, with the
|
|
169
|
+
/// caller's backtrace (Flog prints it).
|
|
170
|
+
fn syntax_error(ruby: &Ruby, message: &str) -> Result<magnus::Exception, Error> {
|
|
171
|
+
let class: magnus::ExceptionClass = flog_rs_module(ruby)?.const_get("SyntaxError")?;
|
|
172
|
+
let exception = class.new_instance((message,))?;
|
|
173
|
+
let backtrace: Value = ruby.module_kernel().funcall("caller", ())?;
|
|
174
|
+
exception.funcall::<_, _, Value>("set_backtrace", (backtrace,))?;
|
|
175
|
+
Ok(exception)
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
fn flog_rs_module(ruby: &Ruby) -> Result<magnus::RModule, Error> {
|
|
179
|
+
ruby.class_object().const_get("FlogRs")
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/// The `rescue RubyParser::SyntaxError` clause of `Flog#flog_ruby` (see
|
|
183
|
+
/// [`flog_core::handle_syntax_error`]): issues its warnings, then raises
|
|
184
|
+
/// when Flog re-raises. `looks_like_erb` gets whether the exception's
|
|
185
|
+
/// `inspect` mentions `<%` or `%>` and adds the check on the source, as
|
|
186
|
+
/// `e.inspect =~ /<\%|%\>/ or ruby =~ /<\%|%\>/` does.
|
|
187
|
+
fn handle_syntax_error(
|
|
188
|
+
ruby: &Ruby,
|
|
189
|
+
rb_self: RObject,
|
|
190
|
+
message: &str,
|
|
191
|
+
file: Value,
|
|
192
|
+
looks_like_erb: impl FnOnce(bool) -> Result<bool, Error>,
|
|
193
|
+
) -> Result<(), Error> {
|
|
194
|
+
let exception = syntax_error(ruby, message)?;
|
|
195
|
+
let inspect: String = exception.funcall("inspect", ())?;
|
|
196
|
+
let looks_like_erb = looks_like_erb(inspect.contains("<%") || inspect.contains("%>"))?;
|
|
197
|
+
let path = file.to_r_string()?.to_string()?;
|
|
198
|
+
let class_name: String = exception.class().funcall("to_s", ())?;
|
|
199
|
+
let backtrace: Vec<String> = exception.funcall("backtrace", ())?;
|
|
200
|
+
let handling = flog_core::handle_syntax_error(
|
|
201
|
+
&SyntaxErrorException { path: &path, message, class_name: &class_name, inspect: &inspect, backtrace: &backtrace },
|
|
202
|
+
looks_like_erb,
|
|
203
|
+
option(ruby, rb_self, "quiet")?.to_bool(),
|
|
204
|
+
option(ruby, rb_self, "continue")?.to_bool(),
|
|
205
|
+
);
|
|
206
|
+
for warning in &handling.warnings {
|
|
207
|
+
warn(rb_self, warning)?;
|
|
208
|
+
}
|
|
209
|
+
if handling.raises {
|
|
210
|
+
return Err(exception.into());
|
|
211
|
+
}
|
|
212
|
+
Ok(())
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
/// Merges one file's result into `calls` and `method_locations`, replaying
|
|
216
|
+
/// each addition as Flog's `@calls[signature][name] += score * @multiplier`
|
|
217
|
+
/// does, then raises the exception Flog raised while scoring, if any (Flog
|
|
218
|
+
/// keeps the points it added before).
|
|
219
|
+
fn add_file_result(ruby: &Ruby, rb_self: RObject, result: &FileResult) -> Result<(), Error> {
|
|
220
|
+
let calls: RHash = rb_self.ivar_get("@calls")?;
|
|
221
|
+
for (label, tally) in result.additions() {
|
|
222
|
+
let merged: Value = calls.aref(label.as_str())?;
|
|
223
|
+
for (name, additions) in tally {
|
|
224
|
+
let key = ruby.to_symbol(name);
|
|
225
|
+
for addition in additions {
|
|
226
|
+
let sum = add(merged.funcall("[]", (key,))?, *addition)?;
|
|
227
|
+
merged.funcall::<_, _, Value>("[]=", (key, sum))?;
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
let method_locations: RHash = rb_self.ivar_get("@method_locations")?;
|
|
232
|
+
for (label, location) in result.method_locations() {
|
|
233
|
+
method_locations.aset(label.as_str(), location.as_str())?;
|
|
234
|
+
}
|
|
235
|
+
match &result.outcome {
|
|
236
|
+
FileOutcome::Raised(exception) => Err(flog_exception(ruby, exception)?),
|
|
237
|
+
_ => Ok(()),
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
/// `sum + addition` for a tally entry, which is a Float or Flog's default 0.
|
|
242
|
+
fn add(sum: Value, addition: f64) -> Result<f64, Error> {
|
|
243
|
+
Ok(f64::try_convert(sum)? + addition)
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
/// The Ruby exception Flog raised while scoring.
|
|
247
|
+
fn flog_exception(ruby: &Ruby, exception: &FlogException) -> Result<Error, Error> {
|
|
248
|
+
let class: magnus::ExceptionClass = ruby.class_object().const_get(exception.class)?;
|
|
249
|
+
Ok(Error::new(class, exception.message.clone()))
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
/// `Flog#calculate_total_scores`: each method's score, and their sum. Does
|
|
253
|
+
/// nothing once totals exist, until `reset`.
|
|
254
|
+
pub fn calculate_total_scores(ruby: &Ruby, rb_self: RObject) -> Result<(), Error> {
|
|
255
|
+
if rb_self.ivar_get::<_, Value>("@totals")?.to_bool() {
|
|
256
|
+
return Ok(());
|
|
257
|
+
}
|
|
258
|
+
let totals = hash_with_zero_default(ruby)?;
|
|
259
|
+
let mut total_score: Option<f64> = None;
|
|
260
|
+
let calls: RHash = rb_self.ivar_get("@calls")?;
|
|
261
|
+
calls.foreach(|label: Value, tally: Value| {
|
|
262
|
+
let score = score_method(ruby, rb_self, tally)?;
|
|
263
|
+
totals.aset(label, score)?;
|
|
264
|
+
total_score = Some(total_score.unwrap_or(0.0) + score);
|
|
265
|
+
Ok(magnus::r_hash::ForEach::Continue)
|
|
266
|
+
})?;
|
|
267
|
+
rb_self.ivar_set("@totals", totals)?;
|
|
268
|
+
// `@total_score = 0` stays the Integer 0 when there are no methods.
|
|
269
|
+
match total_score {
|
|
270
|
+
Some(score) => rb_self.ivar_set("@total_score", score),
|
|
271
|
+
None => rb_self.ivar_set("@total_score", 0),
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
/// `Flog#score_method(tally)`: the distance formula, with `:assignment` in
|
|
276
|
+
/// A, `:branch` and `:block_call` in B, and every other name in C.
|
|
277
|
+
pub fn score_method(ruby: &Ruby, _rb_self: RObject, tally: Value) -> Result<f64, Error> {
|
|
278
|
+
let (mut a, mut b, mut c) = (0.0_f64, 0.0_f64, 0.0_f64);
|
|
279
|
+
let assignment = ruby.to_symbol("assignment");
|
|
280
|
+
let branches = [ruby.to_symbol("branch"), ruby.to_symbol("block_call")];
|
|
281
|
+
let pairs: RArray = tally.funcall("to_a", ())?;
|
|
282
|
+
for pair in pairs {
|
|
283
|
+
let (name, score): (Value, f64) = TryConvert::try_convert(pair)?;
|
|
284
|
+
let name = Symbol::from_value(name);
|
|
285
|
+
if name == Some(assignment) {
|
|
286
|
+
a += score;
|
|
287
|
+
} else if name.is_some_and(|name| branches.contains(&name)) {
|
|
288
|
+
b += score;
|
|
289
|
+
} else {
|
|
290
|
+
c += score;
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
Ok((a * a + b * b + c * c).sqrt())
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
/// `Flog#average`: `total_score / calls.size`, or the Integer 0 when no
|
|
297
|
+
/// method was scored.
|
|
298
|
+
pub fn average(ruby: &Ruby, rb_self: RObject) -> Result<Value, Error> {
|
|
299
|
+
let calls: RHash = rb_self.ivar_get("@calls")?;
|
|
300
|
+
if calls.is_empty() {
|
|
301
|
+
return Ok(ruby.integer_from_i64(0).as_value());
|
|
302
|
+
}
|
|
303
|
+
let total_score: Value = rb_self.ivar_get("@total_score")?;
|
|
304
|
+
match Float::from_value(total_score) {
|
|
305
|
+
Some(total_score) => Ok(ruby.float_from_f64(total_score.to_f64() / calls.len() as f64).as_value()),
|
|
306
|
+
// Integer 0 (totals calculated before these methods) or nil (never
|
|
307
|
+
// calculated): Ruby's own `/` gives Flog's result or error.
|
|
308
|
+
None => total_score.funcall("/", (calls.len(),)),
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
/// `Flog#each_by_score(max = nil)`: yields each method's label, score and
|
|
313
|
+
/// tally from the highest score down (see [`each_by_score_with`]). Returns
|
|
314
|
+
/// the sorted `[label, tally]` pairs, or nil when it stopped early.
|
|
315
|
+
pub fn each_by_score(ruby: &Ruby, rb_self: RObject, args: &[Value]) -> Result<Value, Error> {
|
|
316
|
+
let args = scan_args::<(), (Option<Value>,), (), (), (), ()>(args)?;
|
|
317
|
+
let max = args.optional.0.unwrap_or_else(|| ruby.qnil().as_value());
|
|
318
|
+
each_by_score_with(ruby, rb_self, max, |label, score, tally| {
|
|
319
|
+
if !ruby.block_given() {
|
|
320
|
+
return Err(Error::new(ruby.exception_local_jump_error(), "no block given (yield)"));
|
|
321
|
+
}
|
|
322
|
+
ruby.yield_values::<_, Value>((label, score, tally))?;
|
|
323
|
+
Ok(())
|
|
324
|
+
})
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
/// The body of `Flog#each_by_score`, calling `visit` where Flog yields:
|
|
328
|
+
/// methods sorted by `-totals[label]` (equal scores in the order Ruby's
|
|
329
|
+
/// `sort_by` leaves them), stopping once the scores visited add up to `max`
|
|
330
|
+
/// (when `max` is not nil).
|
|
331
|
+
fn each_by_score_with(
|
|
332
|
+
ruby: &Ruby,
|
|
333
|
+
rb_self: RObject,
|
|
334
|
+
max: Value,
|
|
335
|
+
mut visit: impl FnMut(Value, Value, Value) -> Result<(), Error>,
|
|
336
|
+
) -> Result<Value, Error> {
|
|
337
|
+
let max = if max.to_bool() { Some(f64::try_convert(max)?) } else { None };
|
|
338
|
+
let calls: RHash = rb_self.ivar_get("@calls")?;
|
|
339
|
+
let totals: Value = rb_self.ivar_get("@totals")?;
|
|
340
|
+
|
|
341
|
+
let mut entries = Vec::with_capacity(calls.len());
|
|
342
|
+
let mut keys = Vec::with_capacity(calls.len());
|
|
343
|
+
calls.foreach(|label: Value, tally: Value| {
|
|
344
|
+
let score: Value = totals.funcall("[]", (label,))?;
|
|
345
|
+
keys.push(-f64::try_convert(score)?);
|
|
346
|
+
entries.push((label, tally));
|
|
347
|
+
Ok(magnus::r_hash::ForEach::Continue)
|
|
348
|
+
})?;
|
|
349
|
+
let order = sort_by_numeric_keys(&keys);
|
|
350
|
+
|
|
351
|
+
let sorted = ruby.ary_new_capa(order.len());
|
|
352
|
+
for &index in &order {
|
|
353
|
+
let (label, tally) = entries[index];
|
|
354
|
+
sorted.push(ruby.ary_new_from_values(&[label, tally]))?;
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
let mut current = 0.0;
|
|
358
|
+
for &index in &order {
|
|
359
|
+
let (label, tally) = entries[index];
|
|
360
|
+
let score: Value = totals.funcall("[]", (label,))?;
|
|
361
|
+
visit(label, score, tally)?;
|
|
362
|
+
current += f64::try_convert(score)?;
|
|
363
|
+
if max.is_some_and(|max| current >= max) {
|
|
364
|
+
return Ok(ruby.qnil().as_value());
|
|
365
|
+
}
|
|
366
|
+
}
|
|
367
|
+
Ok(sorted.as_value())
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
/// `Flog#threshold`: nil with `all`, otherwise `total_score` times the
|
|
371
|
+
/// threshold fraction.
|
|
372
|
+
pub fn threshold(ruby: &Ruby, rb_self: RObject) -> Result<Value, Error> {
|
|
373
|
+
if option(ruby, rb_self, "all")?.to_bool() {
|
|
374
|
+
return Ok(ruby.qnil().as_value());
|
|
375
|
+
}
|
|
376
|
+
let total_score: Value = rb_self.ivar_get("@total_score")?;
|
|
377
|
+
let fraction: Value = rb_self.ivar_get("@threshold")?;
|
|
378
|
+
match (Float::from_value(total_score), Float::from_value(fraction)) {
|
|
379
|
+
(Some(total_score), Some(fraction)) => Ok(ruby.float_from_f64(total_score.to_f64() * fraction.to_f64()).as_value()),
|
|
380
|
+
// The Integer 0 or nil: Ruby's own `*` gives Flog's result or error.
|
|
381
|
+
_ => total_score.funcall("*", (fraction,)),
|
|
382
|
+
}
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
/// `Flog#calculate`: the score of each class, and its methods' scores, from
|
|
386
|
+
/// the methods `each_by_score(threshold)` yields.
|
|
387
|
+
pub fn calculate(ruby: &Ruby, rb_self: RObject) -> Result<(), Error> {
|
|
388
|
+
let threshold = threshold(ruby, rb_self)?;
|
|
389
|
+
let method_scores: RHash = rb_self.ivar_get("@method_scores")?;
|
|
390
|
+
let scores: RHash = rb_self.ivar_get("@scores")?;
|
|
391
|
+
each_by_score_with(ruby, rb_self, threshold, |label, score, _tally| {
|
|
392
|
+
let class_name = class_name(&String::try_convert(label)?).map(|name| ruby.str_new(name));
|
|
393
|
+
let class_key = class_name.map_or_else(|| ruby.qnil().as_value(), |name| name.as_value());
|
|
394
|
+
let list: RArray = method_scores.aref(class_key)?;
|
|
395
|
+
list.push(ruby.ary_new_from_values(&[label, score]))?;
|
|
396
|
+
let sum: Value = scores.aref(class_key)?;
|
|
397
|
+
let sum: Value = match (Float::from_value(sum), Float::from_value(score)) {
|
|
398
|
+
(Some(sum), Some(score)) => ruby.float_from_f64(sum.to_f64() + score.to_f64()).as_value(),
|
|
399
|
+
// Integer scores: Ruby's own `+`.
|
|
400
|
+
_ => sum.funcall("+", (score,))?,
|
|
401
|
+
};
|
|
402
|
+
scores.aset(class_key, sum)
|
|
403
|
+
})?;
|
|
404
|
+
Ok(())
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
/// `class_method.scan(/.+(?=#|::)/).first`: the label up to its last `#`
|
|
408
|
+
/// or `::`, within the first line that has one after its first character.
|
|
409
|
+
fn class_name(label: &str) -> Option<&str> {
|
|
410
|
+
let mut line_start = 0;
|
|
411
|
+
for line in label.split('\n') {
|
|
412
|
+
let end = (1..line.len()).rev().find(|&end| {
|
|
413
|
+
let rest = &line.as_bytes()[end..];
|
|
414
|
+
rest.starts_with(b"#") || rest.starts_with(b"::")
|
|
415
|
+
});
|
|
416
|
+
if let Some(end) = end {
|
|
417
|
+
return Some(&label[line_start..line_start + end]);
|
|
418
|
+
}
|
|
419
|
+
line_start += line.len() + 1;
|
|
420
|
+
}
|
|
421
|
+
None
|
|
422
|
+
}
|
|
423
|
+
|
|
424
|
+
/// `Flog#max_method`: the first `[label, score]` with the highest score.
|
|
425
|
+
pub fn max_method(ruby: &Ruby, rb_self: RObject) -> Result<Value, Error> {
|
|
426
|
+
let totals: Value = rb_self.ivar_get("@totals")?;
|
|
427
|
+
let Some(totals) = RHash::from_value(totals) else {
|
|
428
|
+
// nil before totals are calculated: Ruby's NoMethodError.
|
|
429
|
+
return totals.funcall("max_by", ());
|
|
430
|
+
};
|
|
431
|
+
let mut max: Option<(Value, Value, f64)> = None;
|
|
432
|
+
totals.foreach(|label: Value, score: Value| {
|
|
433
|
+
let value = f64::try_convert(score)?;
|
|
434
|
+
if max.is_none_or(|(_, _, max)| value > max) {
|
|
435
|
+
max = Some((label, score, value));
|
|
436
|
+
}
|
|
437
|
+
Ok(magnus::r_hash::ForEach::Continue)
|
|
438
|
+
})?;
|
|
439
|
+
Ok(match max {
|
|
440
|
+
Some((label, score, _)) => ruby.ary_new_from_values(&[label, score]).as_value(),
|
|
441
|
+
None => ruby.qnil().as_value(),
|
|
442
|
+
})
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
/// `Flog#max_score`: `max_method.last`.
|
|
446
|
+
pub fn max_score(ruby: &Ruby, rb_self: RObject) -> Result<Value, Error> {
|
|
447
|
+
max_method(ruby, rb_self)?.funcall("last", ())
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
/// `FlogRs.flog_many(paths, options = {})`: scores the files in parallel,
|
|
451
|
+
/// each on its own as `reset` then `flog(path)` would, and returns
|
|
452
|
+
/// `{ path => FlogRs::Flog }` in input order with totals calculated.
|
|
453
|
+
pub fn flog_many(ruby: &Ruby, args: &[Value]) -> Result<RHash, Error> {
|
|
454
|
+
let args = scan_args::<(Vec<String>,), (Option<Value>,), (), (), (), ()>(args)?;
|
|
455
|
+
let (paths, options) = (args.required.0, args.optional.0.unwrap_or_else(|| ruby.hash_new().as_value()));
|
|
456
|
+
let methods_only = options.funcall::<_, _, Value>("[]", (ruby.to_symbol("methods"),))?.to_bool();
|
|
457
|
+
let version = ruby_version(ruby)?;
|
|
458
|
+
let results: Vec<FileResult> = paths.par_iter().map(|path| score_file(path, methods_only, &version)).collect();
|
|
459
|
+
|
|
460
|
+
let flog_class: RClass = flog_rs_module(ruby)?.const_get("Flog")?;
|
|
461
|
+
let many = ruby.hash_new();
|
|
462
|
+
for result in &results {
|
|
463
|
+
let flog = RObject::try_convert(flog_class.new_instance((options,))?)?;
|
|
464
|
+
match &result.outcome {
|
|
465
|
+
FileOutcome::Unreadable => {}
|
|
466
|
+
FileOutcome::SyntaxError { message, looks_like_erb } => {
|
|
467
|
+
let path = ruby.str_new(&result.path).as_value();
|
|
468
|
+
handle_syntax_error(ruby, flog, message, path, |_| Ok(*looks_like_erb))?;
|
|
469
|
+
}
|
|
470
|
+
FileOutcome::Scored | FileOutcome::Raised(_) => add_file_result(ruby, flog, result)?,
|
|
471
|
+
}
|
|
472
|
+
calculate_total_scores(ruby, flog)?;
|
|
473
|
+
many.aset(result.path.as_str(), flog)?;
|
|
474
|
+
}
|
|
475
|
+
Ok(many)
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
#[cfg(test)]
|
|
479
|
+
mod tests {
|
|
480
|
+
use super::class_name;
|
|
481
|
+
|
|
482
|
+
#[test]
|
|
483
|
+
fn class_name_is_the_label_up_to_its_last_separator() {
|
|
484
|
+
assert_eq!(class_name("Foo::Bar#baz"), Some("Foo::Bar"));
|
|
485
|
+
assert_eq!(class_name("Foo::bar"), Some("Foo"));
|
|
486
|
+
assert_eq!(class_name("A::B::c"), Some("A::B"));
|
|
487
|
+
assert_eq!(class_name("main#none"), Some("main"));
|
|
488
|
+
assert_eq!(class_name("Foo#==#x"), Some("Foo#=="));
|
|
489
|
+
assert_eq!(class_name("none"), None);
|
|
490
|
+
assert_eq!(class_name("#x"), None);
|
|
491
|
+
assert_eq!(class_name("a\nB#c"), Some("B"));
|
|
492
|
+
}
|
|
493
|
+
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
//! Ruby binding for flog-core: defines `FlogRs::Flog`, `FlogRs::SyntaxError`
|
|
2
|
+
//! and `FlogRs.flog_many` (see `flog.rs`).
|
|
3
|
+
|
|
4
|
+
mod flog;
|
|
5
|
+
|
|
6
|
+
use magnus::{function, method, prelude::*, Attr, Error, Ruby};
|
|
7
|
+
|
|
8
|
+
#[magnus::init]
|
|
9
|
+
fn init(ruby: &Ruby) -> Result<(), Error> {
|
|
10
|
+
let flog_rs = ruby.define_module("FlogRs")?;
|
|
11
|
+
let native = flog_rs.define_module("Native")?;
|
|
12
|
+
native.const_set("FLOG_COMPAT", flog_core::FLOG_COMPAT)?;
|
|
13
|
+
|
|
14
|
+
// Raised for a parse error, as Flog raises RubyParser::SyntaxError.
|
|
15
|
+
flog_rs.define_error("SyntaxError", ruby.exception_runtime_error())?;
|
|
16
|
+
flog_rs.define_module_function("flog_many", function!(flog::flog_many, -1))?;
|
|
17
|
+
|
|
18
|
+
let class = flog_rs.define_class("Flog", ruby.class_object())?;
|
|
19
|
+
class.const_set("DEFAULT_THRESHOLD", flog::DEFAULT_THRESHOLD)?;
|
|
20
|
+
class.define_attr("multiplier", Attr::ReadWrite)?;
|
|
21
|
+
for reader in ["calls", "option", "mass", "method_scores", "scores", "total_score", "totals", "method_locations"] {
|
|
22
|
+
class.define_attr(reader, Attr::Read)?;
|
|
23
|
+
}
|
|
24
|
+
class.define_attr("threshold", Attr::Write)?;
|
|
25
|
+
class.define_method("initialize", method!(flog::initialize, -1))?;
|
|
26
|
+
class.define_method("reset", method!(flog::reset, 0))?;
|
|
27
|
+
class.define_method("flog", method!(flog::flog, -1))?;
|
|
28
|
+
class.define_method("flog_ruby", method!(flog::flog_ruby, -1))?;
|
|
29
|
+
class.define_method("flog_ruby!", method!(flog::flog_ruby_bang, -1))?;
|
|
30
|
+
class.define_method("average", method!(flog::average, 0))?;
|
|
31
|
+
class.define_method("calculate", method!(flog::calculate, 0))?;
|
|
32
|
+
class.define_method("each_by_score", method!(flog::each_by_score, -1))?;
|
|
33
|
+
class.define_method("max_method", method!(flog::max_method, 0))?;
|
|
34
|
+
class.define_method("max_score", method!(flog::max_score, 0))?;
|
|
35
|
+
class.define_method("threshold", method!(flog::threshold, 0))?;
|
|
36
|
+
class.define_method("score_method", method!(flog::score_method, 1))?;
|
|
37
|
+
class.define_method("calculate_total_scores", method!(flog::calculate_total_scores, 0))?;
|
|
38
|
+
Ok(())
|
|
39
|
+
}
|
data/lib/flog_rs.rb
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require_relative "flog_rs/version"
|
|
4
|
+
|
|
5
|
+
# Precompiled gems ship one library per Ruby minor version.
|
|
6
|
+
begin
|
|
7
|
+
require_relative "flog_rs/#{RUBY_VERSION[/\d+\.\d+/]}/flog_rs"
|
|
8
|
+
rescue LoadError
|
|
9
|
+
require_relative "flog_rs/flog_rs"
|
|
10
|
+
end
|
|
11
|
+
|
|
12
|
+
# Flog 4.10.0's scores, computed in Rust from Prism's syntax tree.
|
|
13
|
+
#
|
|
14
|
+
# The extension defines FlogRs::Flog, which has the public API of ::Flog that
|
|
15
|
+
# tools such as RubyCritic use, FlogRs::SyntaxError and FlogRs.flog_many
|
|
16
|
+
# (see ext/flog_rs/src/flog.rs).
|
metadata
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
--- !ruby/object:Gem::Specification
|
|
2
|
+
name: flog-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
|
+
FlogRs reproduces Flog 4.10.0's method labels, scores, totals and
|
|
30
|
+
method locations exactly, without translating Prism's tree to ruby_parser's.
|
|
31
|
+
executables: []
|
|
32
|
+
extensions:
|
|
33
|
+
- ext/flog_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/flog-cli/Cargo.toml
|
|
43
|
+
- crates/flog-cli/src/main.rs
|
|
44
|
+
- crates/flog-core/Cargo.toml
|
|
45
|
+
- crates/flog-core/src/attach_comments.rs
|
|
46
|
+
- crates/flog-core/src/lib.rs
|
|
47
|
+
- crates/flog-core/src/literal.rs
|
|
48
|
+
- crates/flog-core/src/ruby_format.rs
|
|
49
|
+
- crates/flog-core/src/ruby_sort.rs
|
|
50
|
+
- crates/flog-core/src/scorer.rs
|
|
51
|
+
- crates/flog-core/src/scores.rs
|
|
52
|
+
- crates/flog-core/src/syntax_error.rs
|
|
53
|
+
- crates/flog-core/src/translation.rs
|
|
54
|
+
- ext/flog_rs/Cargo.toml
|
|
55
|
+
- ext/flog_rs/extconf.rb
|
|
56
|
+
- ext/flog_rs/src/flog.rs
|
|
57
|
+
- ext/flog_rs/src/lib.rs
|
|
58
|
+
- lib/flog_rs.rb
|
|
59
|
+
- lib/flog_rs/version.rb
|
|
60
|
+
homepage: "https://gloom.fm"
|
|
61
|
+
licenses:
|
|
62
|
+
- MIT
|
|
63
|
+
metadata:
|
|
64
|
+
source_code_uri: "https://github.com/gloom-fm/flog-rs"
|
|
65
|
+
bug_tracker_uri: "https://github.com/gloom-fm/flog-rs/issues"
|
|
66
|
+
rubygems_mfa_required: "true"
|
|
67
|
+
rdoc_options: []
|
|
68
|
+
require_paths:
|
|
69
|
+
- lib
|
|
70
|
+
required_ruby_version: !ruby/object:Gem::Requirement
|
|
71
|
+
requirements:
|
|
72
|
+
-
|
|
73
|
+
- ">="
|
|
74
|
+
- !ruby/object:Gem::Version
|
|
75
|
+
version: "3.3"
|
|
76
|
+
required_rubygems_version: !ruby/object:Gem::Requirement
|
|
77
|
+
requirements:
|
|
78
|
+
-
|
|
79
|
+
- ">="
|
|
80
|
+
- !ruby/object:Gem::Version
|
|
81
|
+
version: "0"
|
|
82
|
+
requirements: []
|
|
83
|
+
rubygems_version: 4.1.1
|
|
84
|
+
specification_version: 4
|
|
85
|
+
summary: "Flog 4.10.0 complexity scores, computed in Rust from Prism's syntax tree"
|
|
86
|
+
test_files: []
|