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.
@@ -0,0 +1,23 @@
1
+ [package]
2
+ name = "flog-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 = "flog-rs: Flog 4.10.0's complexity scores for Ruby files, as JSON"
11
+ readme = "README.md"
12
+ keywords = ["ruby", "flog", "complexity", "static-analysis", "cli"]
13
+ categories = ["development-tools", "command-line-utilities"]
14
+
15
+ [dependencies]
16
+ flog-core = { version = "0.1.0", path = "../flog-core" }
17
+ indexmap.workspace = true
18
+ rayon.workspace = true
19
+ serde_json = { version = "1.0.154", features = ["preserve_order"] }
20
+
21
+ [[bin]]
22
+ name = "flog-rs"
23
+ path = "src/main.rs"
@@ -0,0 +1,224 @@
1
+ //! `flog-rs`: Flog 4.10.0 scores as JSON.
2
+ //!
3
+ //! flog-rs [--all] [--methods] [--continue] [--threshold=N] [--ruby-version=V] PATHS...
4
+ //! flog-rs --per-file [--methods=both|true|false] [--ruby-version=V] PATHS...
5
+ //!
6
+ //! `--ruby-version` is the `RUBY_VERSION` whose syntax Flog would parse with
7
+ //! (default: latest). Under Ruby 3.3, for example, `it` in a block is a call.
8
+ //!
9
+ //! The default mode merges all files into one report, as one `Flog` instance
10
+ //! would. `--per-file` scores each file on its own with `all` and `continue`
11
+ //! on and writes one JSON line per file and `methods` setting, in the format
12
+ //! `parity/oracle.rb` writes, so the two can be compared as text.
13
+ //!
14
+ //! Directories are expanded to the `.rb` files under them, sorted.
15
+ //! Files are scored in parallel and merged in input order.
16
+
17
+ use std::path::Path;
18
+ use std::process::ExitCode;
19
+
20
+ use flog_core::ruby_format::float_to_s;
21
+ use flog_core::{score_file, FileOutcome, FileResult, Flog, DEFAULT_THRESHOLD};
22
+ use rayon::prelude::*;
23
+ use serde_json::{json, Map, Value};
24
+
25
+ struct Arguments {
26
+ all: bool,
27
+ methods: bool,
28
+ continue_on_error: bool,
29
+ threshold: f64,
30
+ per_file: bool,
31
+ per_file_methods: Vec<bool>,
32
+ ruby_version: String,
33
+ paths: Vec<String>,
34
+ }
35
+
36
+ fn parse_arguments() -> Result<Arguments, String> {
37
+ let mut arguments = Arguments {
38
+ all: false,
39
+ methods: false,
40
+ continue_on_error: false,
41
+ threshold: DEFAULT_THRESHOLD,
42
+ per_file: false,
43
+ per_file_methods: vec![true, false],
44
+ ruby_version: "latest".to_string(),
45
+ paths: Vec::new(),
46
+ };
47
+ for argument in std::env::args().skip(1) {
48
+ match argument.as_str() {
49
+ "--all" | "-a" => arguments.all = true,
50
+ "--methods" | "--methods-only" | "-m" => arguments.methods = true,
51
+ "--continue" | "-c" => arguments.continue_on_error = true,
52
+ "--per-file" => arguments.per_file = true,
53
+ "--json" => {}
54
+ "--methods=both" => arguments.per_file_methods = vec![true, false],
55
+ "--methods=true" => arguments.per_file_methods = vec![true],
56
+ "--methods=false" => arguments.per_file_methods = vec![false],
57
+ other if other.starts_with("--ruby-version=") => {
58
+ arguments.ruby_version = other["--ruby-version=".len()..].to_string();
59
+ }
60
+ other if other.starts_with("--threshold=") => {
61
+ let value = &other["--threshold=".len()..];
62
+ let percent: f64 = value.parse().map_err(|_| format!("bad threshold: {value}"))?;
63
+ arguments.threshold = percent / 100.0;
64
+ }
65
+ other if other.starts_with('-') && other != "-" => {
66
+ return Err(format!("unknown option: {other}"))
67
+ }
68
+ path => arguments.paths.push(path.to_string()),
69
+ }
70
+ }
71
+ Ok(arguments)
72
+ }
73
+
74
+ fn expand_paths(paths: &[String]) -> Vec<String> {
75
+ let mut files = Vec::new();
76
+ for path in paths {
77
+ if Path::new(path).is_dir() {
78
+ let mut found = Vec::new();
79
+ collect_ruby_files(Path::new(path), &mut found);
80
+ found.sort();
81
+ files.extend(found);
82
+ } else {
83
+ files.push(path.clone());
84
+ }
85
+ }
86
+ files
87
+ }
88
+
89
+ fn collect_ruby_files(directory: &Path, found: &mut Vec<String>) {
90
+ let Ok(entries) = std::fs::read_dir(directory) else { return };
91
+ for entry in entries.flatten() {
92
+ let path = entry.path();
93
+ if path.is_dir() {
94
+ collect_ruby_files(&path, found);
95
+ } else if path.extension().is_some_and(|extension| extension == "rb") {
96
+ found.push(path.to_string_lossy().into_owned());
97
+ }
98
+ }
99
+ }
100
+
101
+ fn main() -> ExitCode {
102
+ let arguments = match parse_arguments() {
103
+ Ok(arguments) => arguments,
104
+ Err(message) => {
105
+ eprintln!("flog-rs: {message}");
106
+ return ExitCode::from(2);
107
+ }
108
+ };
109
+ let files = expand_paths(&arguments.paths);
110
+
111
+ if arguments.per_file {
112
+ print_per_file_records(&files, &arguments.per_file_methods, &arguments.ruby_version);
113
+ return ExitCode::SUCCESS;
114
+ }
115
+
116
+ let results: Vec<FileResult> =
117
+ files.par_iter().map(|file| score_file(file, arguments.methods, &arguments.ruby_version)).collect();
118
+ let mut flog = Flog::new();
119
+ for result in &results {
120
+ match &result.outcome {
121
+ FileOutcome::SyntaxError { message, looks_like_erb } => {
122
+ if !arguments.continue_on_error && !looks_like_erb {
123
+ eprintln!("ERROR: parsing ruby file {}", result.path);
124
+ eprintln!("ERROR! Aborting. You may want to run with --continue.");
125
+ eprintln!("{message}");
126
+ return ExitCode::FAILURE;
127
+ }
128
+ eprintln!("ERROR: parsing ruby file {}: {message}", result.path);
129
+ }
130
+ FileOutcome::Raised(exception) => {
131
+ flog.merge(result);
132
+ eprintln!("{}: {} ({})", exception.class, exception.message, result.path);
133
+ return ExitCode::FAILURE;
134
+ }
135
+ FileOutcome::Scored | FileOutcome::Unreadable => {}
136
+ }
137
+ flog.merge(result);
138
+ }
139
+ flog.calculate_total_scores();
140
+ println!("{}", merged_report(&flog, &arguments));
141
+ ExitCode::SUCCESS
142
+ }
143
+
144
+ /// One JSON line per file and `methods` setting, matching `parity/oracle.rb`.
145
+ fn print_per_file_records(files: &[String], modes: &[bool], ruby_version: &str) {
146
+ let records: Vec<Vec<String>> = files
147
+ .par_iter()
148
+ .map(|file| {
149
+ modes
150
+ .iter()
151
+ .map(|methods| {
152
+ per_file_record(&score_file(file, *methods, ruby_version), *methods).to_string()
153
+ })
154
+ .collect()
155
+ })
156
+ .collect();
157
+ for lines in records {
158
+ for line in lines {
159
+ println!("{line}");
160
+ }
161
+ }
162
+ }
163
+
164
+ fn per_file_record(result: &FileResult, methods: bool) -> Value {
165
+ if let FileOutcome::Raised(exception) = &result.outcome {
166
+ return json!({
167
+ "path": result.path,
168
+ "methods": methods,
169
+ "error": format!("{}: {}", exception.class, exception.message),
170
+ });
171
+ }
172
+ let mut flog = Flog::new();
173
+ flog.merge(result);
174
+ flog.calculate_total_scores();
175
+ let mut record = report_body(&flog);
176
+ let object = record.as_object_mut().unwrap();
177
+ let mut ordered = Map::new();
178
+ ordered.insert("path".into(), json!(result.path));
179
+ ordered.insert("methods".into(), json!(methods));
180
+ ordered.insert(
181
+ "skipped".into(),
182
+ json!(matches!(result.outcome, FileOutcome::SyntaxError { .. })),
183
+ );
184
+ ordered.append(object);
185
+ Value::Object(ordered)
186
+ }
187
+
188
+ /// `total_score`, then each method in Flog's `calls` order, then every
189
+ /// recorded method location.
190
+ fn report_body(flog: &Flog) -> Value {
191
+ let totals = flog.totals().expect("totals calculated");
192
+ let methods: Vec<Value> = flog
193
+ .calls()
194
+ .iter()
195
+ .map(|(label, tally)| {
196
+ let tally: Vec<Value> =
197
+ tally.iter().map(|(name, score)| json!([name, float_to_s(*score)])).collect();
198
+ json!({
199
+ "label": label,
200
+ "location": flog.method_locations().get(label),
201
+ "score": float_to_s(totals[label]),
202
+ "tally": tally,
203
+ })
204
+ })
205
+ .collect();
206
+ let locations: Vec<Value> =
207
+ flog.method_locations().iter().map(|(label, location)| json!([label, location])).collect();
208
+ let mut body = Map::new();
209
+ body.insert("total_score".into(), json!(float_to_s(flog.total_score())));
210
+ body.insert("methods_list".into(), Value::Array(methods));
211
+ body.insert("method_locations".into(), Value::Array(locations));
212
+ Value::Object(body)
213
+ }
214
+
215
+ fn merged_report(flog: &Flog, arguments: &Arguments) -> Value {
216
+ let mut body = report_body(flog);
217
+ let count = flog.calls().len();
218
+ let average = if count == 0 { 0.0 } else { flog.total_score() / count as f64 };
219
+ let object = body.as_object_mut().unwrap();
220
+ object.insert("average".into(), json!(float_to_s(average)));
221
+ let threshold = if arguments.all { None } else { Some(flog.total_score() * arguments.threshold) };
222
+ object.insert("threshold".into(), json!(threshold.map(float_to_s)));
223
+ body
224
+ }
@@ -0,0 +1,18 @@
1
+ [package]
2
+ name = "flog-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 = "Flog 4.10.0's complexity scores for Ruby, computed from Prism's syntax tree"
11
+ readme = "README.md"
12
+ keywords = ["ruby", "flog", "complexity", "static-analysis", "prism"]
13
+ categories = ["development-tools"]
14
+
15
+ [dependencies]
16
+ indexmap.workspace = true
17
+ ruby-prism.workspace = true
18
+ ruby-prism-sys.workspace = true
@@ -0,0 +1,271 @@
1
+ //! The exceptions `Prism::Translation::RubyParser`'s `attach_comments` raises.
2
+ //!
3
+ //! For every `class`, `module` and `def`, the translator (prism 2.1.0,
4
+ //! `translation/ruby_parser.rb`) collects the comments before the keyword:
5
+ //!
6
+ //! ```ruby
7
+ //! leading.reverse_each do |comment|
8
+ //! gap = source_string[comment.location.end_offset...boundary]
9
+ //! break if gap.match?(/\S/)
10
+ //! result.unshift(comment)
11
+ //! boundary = comment.location.start_offset
12
+ //! end
13
+ //! sexp.comments = source_string[result.first.location.start_offset...node_start].gsub(...)
14
+ //! ```
15
+ //!
16
+ //! The offsets are byte offsets but `String#[]` counts characters, so in a
17
+ //! source with multibyte characters a comment can end past the string's
18
+ //! character length. The slice is then `nil` and `match?` raises
19
+ //! `NoMethodError`. A slice holding an invalid byte sequence makes `match?`
20
+ //! or `gsub` raise `ArgumentError`. Translation runs before Flog scores
21
+ //! anything, so the file then scores no points at all.
22
+ //!
23
+ //! `source_string` is `Prism.parse(source).source.source`: the bytes in the
24
+ //! encoding Prism detected from a magic comment (UTF-8 without one), except
25
+ //! that a binary source that is valid UTF-8 becomes UTF-8.
26
+
27
+ use std::ffi::{c_char, CStr};
28
+
29
+ use ruby_prism::{ParseResult, Visit};
30
+ use ruby_prism_sys::{pm_arena_free, pm_arena_new, pm_parse, pm_parser_free, pm_parser_new, pm_parser_t};
31
+
32
+ use crate::scorer::FlogException;
33
+
34
+ extern "C" {
35
+ // Exported by prism (include/prism/parser.h) but not bound by ruby-prism-sys.
36
+ fn pm_parser_encoding_name(parser: *const pm_parser_t) -> *const c_char;
37
+ fn pm_parser_encoding_char_width(parser: *const pm_parser_t, start: *const u8, remaining: isize) -> usize;
38
+ }
39
+
40
+ /// The exception the translator raises while attaching comments to `source`,
41
+ /// if any. Sources of ASCII characters only never raise.
42
+ pub fn attach_comments_exception(source: &[u8], parse_result: &ParseResult<'_>) -> Option<FlogException> {
43
+ if source.is_ascii() {
44
+ return None;
45
+ }
46
+ let source_string = SourceString::new(source);
47
+ let comments: Vec<(usize, usize)> = parse_result
48
+ .comments()
49
+ .map(|comment| {
50
+ let location = comment.location();
51
+ (location.start() as usize, location.end() as usize)
52
+ })
53
+ .collect();
54
+ let mut visitor = CommentAttacher { source, source_string: &source_string, comments: &comments, exception: None };
55
+ visitor.visit(&parse_result.node());
56
+ visitor.exception
57
+ }
58
+
59
+ /// `source_string` as Ruby sees it: where each character starts, and which
60
+ /// characters are invalid byte sequences in its encoding.
61
+ struct SourceString {
62
+ encoding_name: String,
63
+ /// Byte offset of each character, then the source length.
64
+ char_starts: Vec<usize>,
65
+ /// For each character index, how many invalid characters come before it.
66
+ invalid_before: Vec<usize>,
67
+ }
68
+
69
+ impl SourceString {
70
+ fn new(source: &[u8]) -> Self {
71
+ let detected = DetectedEncoding::new(source);
72
+ let detected_name = detected.name();
73
+ let valid_utf8 = std::str::from_utf8(source).is_ok();
74
+ let encoding_name = if detected_name == "ASCII-8BIT" && valid_utf8 { "UTF-8".to_string() } else { detected_name };
75
+
76
+ let mut char_starts = Vec::with_capacity(source.len() + 1);
77
+ let mut invalid_before = Vec::with_capacity(source.len() + 1);
78
+ let mut invalid = 0;
79
+ let mut offset = 0;
80
+ while offset < source.len() {
81
+ let width = if encoding_name == "UTF-8" {
82
+ utf8_char_width(&source[offset..])
83
+ } else {
84
+ detected.char_width(&source[offset..])
85
+ };
86
+ char_starts.push(offset);
87
+ invalid_before.push(invalid);
88
+ // Ruby counts each byte of an invalid sequence as one character.
89
+ if width == 0 {
90
+ invalid += 1;
91
+ offset += 1;
92
+ } else {
93
+ offset += width;
94
+ }
95
+ }
96
+ char_starts.push(source.len());
97
+ invalid_before.push(invalid);
98
+ SourceString { encoding_name, char_starts, invalid_before }
99
+ }
100
+
101
+ fn char_length(&self) -> usize {
102
+ self.char_starts.len() - 1
103
+ }
104
+
105
+ /// `source_string[start...finish]` with character indexes: `None` when
106
+ /// `start` is past the end (Ruby's `nil`), otherwise the byte range.
107
+ fn slice(&self, start: usize, finish: usize) -> Option<(usize, usize)> {
108
+ if start > self.char_length() {
109
+ return None;
110
+ }
111
+ let finish = finish.clamp(start, self.char_length());
112
+ Some((start, finish))
113
+ }
114
+
115
+ fn has_invalid_byte_sequence(&self, (start, finish): (usize, usize)) -> bool {
116
+ self.invalid_before[finish] > self.invalid_before[start]
117
+ }
118
+
119
+ /// `/\S/` in Ruby matches anything but space, tab, newline, vertical tab,
120
+ /// form feed and carriage return.
121
+ fn has_non_whitespace(&self, source: &[u8], (start, finish): (usize, usize)) -> bool {
122
+ source[self.char_starts[start]..self.char_starts[finish]]
123
+ .iter()
124
+ .any(|byte| !matches!(byte, b' ' | b'\t' | b'\n' | 0x0b | 0x0c | b'\r'))
125
+ }
126
+
127
+ fn invalid_byte_sequence(&self) -> FlogException {
128
+ FlogException { class: "ArgumentError", message: format!("invalid byte sequence in {}", self.encoding_name) }
129
+ }
130
+ }
131
+
132
+ /// The width of the UTF-8 character at the start of `bytes`, or 0 when it is
133
+ /// an invalid byte sequence.
134
+ fn utf8_char_width(bytes: &[u8]) -> usize {
135
+ let width = match bytes[0] {
136
+ 0x00..=0x7f => return 1,
137
+ 0xc2..=0xdf => 2,
138
+ 0xe0..=0xef => 3,
139
+ 0xf0..=0xf4 => 4,
140
+ _ => return 0,
141
+ };
142
+ match bytes.get(..width) {
143
+ Some(candidate) if std::str::from_utf8(candidate).is_ok() => width,
144
+ _ => 0,
145
+ }
146
+ }
147
+
148
+ /// The encoding Prism detects for a source. A magic comment only counts on
149
+ /// the first line, or on the second after a shebang, so parsing those two
150
+ /// lines is enough.
151
+ struct DetectedEncoding {
152
+ arena: *mut ruby_prism_sys::pm_arena_t,
153
+ parser: *mut pm_parser_t,
154
+ _prefix: Vec<u8>,
155
+ }
156
+
157
+ impl DetectedEncoding {
158
+ fn new(source: &[u8]) -> Self {
159
+ let prefix_length = source
160
+ .iter()
161
+ .enumerate()
162
+ .filter(|(_, byte)| **byte == b'\n')
163
+ .nth(1)
164
+ .map_or(source.len(), |(index, _)| index + 1);
165
+ let prefix = source[..prefix_length].to_vec();
166
+ // SAFETY: the parser reads `prefix`, which lives as long as the
167
+ // parser; both are freed in `drop`.
168
+ unsafe {
169
+ let arena = pm_arena_new();
170
+ let parser = pm_parser_new(arena, prefix.as_ptr(), prefix.len(), std::ptr::null());
171
+ pm_parse(parser);
172
+ DetectedEncoding { arena, parser, _prefix: prefix }
173
+ }
174
+ }
175
+
176
+ fn name(&self) -> String {
177
+ // SAFETY: prism returns a static, NUL-terminated encoding name.
178
+ unsafe { CStr::from_ptr(pm_parser_encoding_name(self.parser)).to_string_lossy().into_owned() }
179
+ }
180
+
181
+ /// The width of the character at the start of `bytes`, or 0 when it is
182
+ /// an invalid byte sequence.
183
+ fn char_width(&self, bytes: &[u8]) -> usize {
184
+ // SAFETY: prism reads at most `bytes.len()` bytes from `bytes`.
185
+ unsafe { pm_parser_encoding_char_width(self.parser, bytes.as_ptr(), bytes.len() as isize) }
186
+ }
187
+ }
188
+
189
+ impl Drop for DetectedEncoding {
190
+ fn drop(&mut self) {
191
+ // SAFETY: created in `new` and freed only here.
192
+ unsafe {
193
+ pm_parser_free(self.parser);
194
+ pm_arena_free(self.arena);
195
+ }
196
+ }
197
+ }
198
+
199
+ /// Walks the tree in the translator's order: a `def` attaches its comments
200
+ /// after its receiver and before its parameters and body; a `class` or
201
+ /// `module` after its name, superclass and body.
202
+ struct CommentAttacher<'a> {
203
+ source: &'a [u8],
204
+ source_string: &'a SourceString,
205
+ comments: &'a [(usize, usize)],
206
+ exception: Option<FlogException>,
207
+ }
208
+
209
+ impl CommentAttacher<'_> {
210
+ fn attach_comments(&mut self, node_start: u32) {
211
+ let node_start = node_start as usize;
212
+ if self.exception.is_some() {
213
+ return;
214
+ }
215
+ let source_string = self.source_string;
216
+ let mut first_attached = None;
217
+ let mut boundary = node_start;
218
+ for &(start, end) in self.comments.iter().filter(|(start, _)| *start < node_start).rev() {
219
+ let Some(gap) = source_string.slice(end, boundary) else {
220
+ self.exception = Some(FlogException {
221
+ class: "NoMethodError",
222
+ message: "undefined method `match?' for nil".to_string(),
223
+ });
224
+ return;
225
+ };
226
+ if source_string.has_invalid_byte_sequence(gap) {
227
+ self.exception = Some(source_string.invalid_byte_sequence());
228
+ return;
229
+ }
230
+ if source_string.has_non_whitespace(self.source, gap) {
231
+ break;
232
+ }
233
+ first_attached = Some(start);
234
+ boundary = start;
235
+ }
236
+ // The comment text `gsub` reads; it is never nil, because the first
237
+ // attached comment ends within the string.
238
+ if let Some(start) = first_attached {
239
+ if let Some(text) = source_string.slice(start, node_start) {
240
+ if source_string.has_invalid_byte_sequence(text) {
241
+ self.exception = Some(source_string.invalid_byte_sequence());
242
+ }
243
+ }
244
+ }
245
+ }
246
+ }
247
+
248
+ impl<'pr> Visit<'pr> for CommentAttacher<'_> {
249
+ fn visit_class_node(&mut self, node: &ruby_prism::ClassNode<'pr>) {
250
+ ruby_prism::visit_class_node(self, node);
251
+ self.attach_comments(node.location().start());
252
+ }
253
+
254
+ fn visit_module_node(&mut self, node: &ruby_prism::ModuleNode<'pr>) {
255
+ ruby_prism::visit_module_node(self, node);
256
+ self.attach_comments(node.location().start());
257
+ }
258
+
259
+ fn visit_def_node(&mut self, node: &ruby_prism::DefNode<'pr>) {
260
+ if let Some(receiver) = node.receiver() {
261
+ self.visit(&receiver);
262
+ }
263
+ self.attach_comments(node.location().start());
264
+ if let Some(parameters) = node.parameters() {
265
+ self.visit_parameters_node(&parameters);
266
+ }
267
+ if let Some(body) = node.body() {
268
+ self.visit(&body);
269
+ }
270
+ }
271
+ }