Skip to main content

dictator_ruby/
lib.rs

1//! Ruby hygiene rules implemented as a Dictator decree.
2
3use dictator_decree_abi::{BoxDecree, Decree, Diagnostic, Diagnostics, Span};
4use dictator_supreme::SupremeConfig;
5use memchr::memchr_iter;
6
7mod heredoc;
8
9/// Configuration for ruby decree
10#[derive(Debug, Clone)]
11pub struct RubyConfig {
12    pub max_lines: usize,
13    pub ignore_comments: bool,
14    /// Exempt heredoc bodies from `line-too-long` (RuboCop's `AllowHeredoc`).
15    pub ignore_heredocs: bool,
16    pub comment_spacing: bool,
17}
18
19impl Default for RubyConfig {
20    fn default() -> Self {
21        Self {
22            max_lines: 300,
23            ignore_comments: false,
24            ignore_heredocs: false,
25            comment_spacing: true,
26        }
27    }
28}
29
30/// Lint a Ruby source file and emit diagnostics for common hygiene issues.
31#[must_use]
32pub fn lint_source(source: &str) -> Diagnostics {
33    lint_source_with_configs(source, &RubyConfig::default(), &SupremeConfig::default())
34}
35
36/// Lint with custom configuration
37#[must_use]
38pub fn lint_source_with_config(source: &str, config: &RubyConfig) -> Diagnostics {
39    let mut diags = Diagnostics::new();
40
41    diags.extend(dictator_supreme::lint_source_with_owner(
42        source,
43        &SupremeConfig::default(),
44        "ruby",
45    ));
46
47    // Ruby-specific rules
48    diags.extend(lint_ruby_specific(
49        source,
50        config,
51        &heredoc::heredoc_lines(source),
52    ));
53
54    diags
55}
56
57#[must_use]
58pub fn lint_source_with_configs(
59    source: &str,
60    ruby_config: &RubyConfig,
61    supreme_config: &SupremeConfig,
62) -> Diagnostics {
63    let mut diags = Diagnostics::new();
64    let heredoc = heredoc::heredoc_lines(source);
65
66    let supreme_diags = dictator_supreme::lint_source_with_owner(source, supreme_config, "ruby");
67    let lines: Vec<&str> = source.split('\n').collect();
68    diags.extend(supreme_diags.into_iter().filter(|d| {
69        if d.rule != "ruby/line-too-long" {
70            return true;
71        }
72        let line_idx = source[..d.span.start].matches('\n').count();
73        if heredoc[line_idx] {
74            !ruby_config.ignore_heredocs
75        } else {
76            !(ruby_config.ignore_comments && lines[line_idx].trim_start().starts_with('#'))
77        }
78    }));
79
80    // Ruby-specific rules
81    diags.extend(lint_ruby_specific(source, ruby_config, &heredoc));
82
83    diags
84}
85
86fn lint_ruby_specific(source: &str, config: &RubyConfig, heredoc: &[bool]) -> Diagnostics {
87    let mut diags = Diagnostics::new();
88
89    // Check file line count
90    check_file_line_count(source, config.max_lines, heredoc, &mut diags);
91
92    let bytes = source.as_bytes();
93    let mut line_start: usize = 0;
94    let mut line_idx: usize = 0;
95
96    for nl in memchr_iter(b'\n', bytes) {
97        process_line(
98            source,
99            line_start,
100            nl,
101            config.comment_spacing && !heredoc[line_idx],
102            &mut diags,
103        );
104        line_start = nl + 1;
105        line_idx += 1;
106    }
107
108    if line_start < bytes.len() {
109        // Final line without trailing newline.
110        process_line(
111            source,
112            line_start,
113            bytes.len(),
114            config.comment_spacing && !heredoc[line_idx],
115            &mut diags,
116        );
117    }
118
119    diags
120}
121
122/// Insert the missing space after `#` on every line `ruby/comment-space` flags.
123#[must_use]
124pub fn fix_comment_spacing(source: &str) -> String {
125    let heredoc = heredoc::heredoc_lines(source);
126    source
127        .split('\n')
128        .enumerate()
129        .map(|(idx, line)| match unspaced_comment_hash(line) {
130            Some(hash) if !heredoc[idx] => format!("{}# {}", &line[..hash], &line[hash + 1..]),
131            _ => line.to_string(),
132        })
133        .collect::<Vec<_>>()
134        .join("\n")
135}
136
137/// Check file line count (excluding comments and blank lines)
138fn check_file_line_count(
139    source: &str,
140    max_lines: usize,
141    heredoc: &[bool],
142    diags: &mut Diagnostics,
143) {
144    if max_lines == 0 {
145        return; // max_lines = 0 disables the check
146    }
147    // A heredoc line starting with `#{` is string content, not a comment.
148    let code_lines = source
149        .split('\n')
150        .zip(heredoc)
151        .filter(|(line, in_heredoc)| {
152            let trimmed = line.trim();
153            !trimmed.is_empty() && (**in_heredoc || !trimmed.starts_with('#'))
154        })
155        .count();
156
157    if code_lines > max_lines {
158        diags.push(Diagnostic {
159            rule: "ruby/file-too-long".to_string(),
160            message: format!("{code_lines} code lines (max {max_lines})"),
161            enforced: false,
162            span: Span::new(0, source.len().min(100)),
163        });
164    }
165}
166
167#[derive(Default)]
168pub struct RubyHygiene {
169    config: RubyConfig,
170    supreme: SupremeConfig,
171}
172
173impl RubyHygiene {
174    #[must_use]
175    pub const fn new(config: RubyConfig, supreme: SupremeConfig) -> Self {
176        Self { config, supreme }
177    }
178}
179
180impl Decree for RubyHygiene {
181    fn name(&self) -> &'static str {
182        "ruby"
183    }
184
185    fn lint(&self, _path: &str, source: &str) -> Diagnostics {
186        lint_source_with_configs(source, &self.config, &self.supreme)
187    }
188
189    fn metadata(&self) -> dictator_decree_abi::DecreeMetadata {
190        dictator_decree_abi::DecreeMetadata {
191            abi_version: dictator_decree_abi::ABI_VERSION.to_string(),
192            decree_version: env!("CARGO_PKG_VERSION").to_string(),
193            description: "Ruby code structure and hygiene".to_string(),
194            persona: "Matz".to_string(),
195            dectauthors: Some(env!("CARGO_PKG_AUTHORS").to_string()),
196            supported_extensions: vec!["rb".to_string(), "rake".to_string(), "gemspec".to_string()],
197            supported_filenames: vec![
198                "Gemfile".to_string(),
199                "Rakefile".to_string(),
200                "Guardfile".to_string(),
201                "Capfile".to_string(),
202                "Brewfile".to_string(),
203                "Dangerfile".to_string(),
204                "Podfile".to_string(),
205                "Fastfile".to_string(),
206                "Appfile".to_string(),
207                "Matchfile".to_string(),
208                "Berksfile".to_string(),
209                "Thorfile".to_string(),
210                "Vagrantfile".to_string(),
211                ".pryrc".to_string(),
212                ".irbrc".to_string(),
213            ],
214            skip_filenames: vec!["Gemfile.lock".to_string(), "Podfile.lock".to_string()],
215            file_scope_rules: dictator_supreme::file_scope_rules(&["file-too-long"]),
216            capabilities: vec![dictator_decree_abi::Capability::Lint],
217        }
218    }
219}
220
221/// Factory used by host (native or WASM-exported).
222#[must_use]
223pub fn init_decree() -> BoxDecree {
224    Box::new(RubyHygiene::default())
225}
226
227/// Create plugin with custom config
228#[must_use]
229pub fn init_decree_with_config(config: RubyConfig) -> BoxDecree {
230    Box::new(RubyHygiene::new(config, SupremeConfig::default()))
231}
232
233/// Create plugin with custom config + supreme config (merged from decree.supreme + decree.ruby)
234#[must_use]
235pub fn init_decree_with_configs(config: RubyConfig, supreme: SupremeConfig) -> BoxDecree {
236    Box::new(RubyHygiene::new(config, supreme))
237}
238
239/// Convert `DecreeSettings` to `RubyConfig`
240#[must_use]
241pub fn config_from_decree_settings(settings: &dictator_core::DecreeSettings) -> RubyConfig {
242    RubyConfig {
243        max_lines: settings.max_lines.unwrap_or(300),
244        ignore_comments: settings.ignore_comments.unwrap_or(false),
245        ignore_heredocs: settings.ignore_heredocs.unwrap_or(false),
246        comment_spacing: settings.comment_spacing.unwrap_or(true),
247    }
248}
249
250fn process_line(
251    source: &str,
252    start: usize,
253    end: usize,
254    comment_spacing: bool,
255    diags: &mut Diagnostics,
256) {
257    if !comment_spacing {
258        return;
259    }
260
261    // Comment hygiene: ensure space after '#', except for known directives.
262    if let Some(hash) = unspaced_comment_hash(&source[start..end]) {
263        // Span of the leading '#'
264        let hash_offset = start + hash;
265        diags.push(Diagnostic {
266            rule: "ruby/comment-space".to_string(),
267            message: "Comments should start with '# '".to_string(),
268            enforced: true,
269            span: Span::new(hash_offset, hash_offset + 1),
270        });
271    }
272}
273
274/// Byte offset of the `#` opening a comment that lacks the following space.
275fn unspaced_comment_hash(line: &str) -> Option<usize> {
276    let line = line.strip_suffix('\r').unwrap_or(line);
277    let trimmed = line.trim_start_matches(' ');
278    let rest = trimmed.strip_prefix('#')?;
279    let unspaced = !rest.is_empty()
280        && !rest.starts_with(' ')
281        // `#{...}` opening a line of a multi-line string, not a comment
282        && !rest.starts_with('{')
283        && !is_comment_directive(rest);
284    unspaced.then_some(line.len() - trimmed.len())
285}
286
287fn is_comment_directive(rest: &str) -> bool {
288    let rest = rest.trim_start();
289
290    rest.starts_with('!') // shebang
291        || rest.starts_with("--") // RDoc: stop documenting
292        || rest.starts_with("++") // RDoc: resume documenting
293        || rest.starts_with("encoding")
294        || rest.starts_with("frozen_string_literal")
295        || rest.starts_with("rubocop")
296        || rest.starts_with("typed")
297}
298
299#[cfg(test)]
300mod tests;