Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Rule: multiple-statements-per-line #246

Draft
wants to merge 4 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions fortitude/src/rules/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ pub(crate) mod precision;
pub(crate) mod readability;
pub(crate) mod style;
pub(crate) mod testing;
pub mod text;
pub(crate) mod typing;
use crate::registry::{AsRule, Category};

Expand Down Expand Up @@ -84,6 +85,8 @@ pub fn code_to_rule(category: Category, code: &str) -> Option<(RuleGroup, Rule)>
(Style, "051") => (RuleGroup::Stable, Ast, style::relational_operators::DeprecatedRelationalOperator),
(Style, "061") => (RuleGroup::Stable, Ast, style::end_statements::UnnamedEndStatement),
(Style, "071") => (RuleGroup::Stable, Ast, style::double_colon_in_decl::MissingDoubleColon),
(Style, "081") => (RuleGroup::Preview, Text, style::semicolons::SuperfluousSemicolon),
(Style, "082") => (RuleGroup::Preview, Text, style::semicolons::MultipleStatementsPerLine),
(Style, "101") => (RuleGroup::Stable, Text, style::whitespace::TrailingWhitespace),
(Style, "102") => (RuleGroup::Stable, Ast, style::whitespace::IncorrectSpaceBeforeComment),

Expand Down
1 change: 1 addition & 0 deletions fortitude/src/rules/style/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ pub mod exit_labels;
pub mod line_length;
pub mod old_style_array_literal;
pub mod relational_operators;
pub mod semicolons;
pub mod whitespace;

#[cfg(test)]
Expand Down
156 changes: 156 additions & 0 deletions fortitude/src/rules/style/semicolons.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,156 @@
use lazy_regex::bytes_regex_is_match;
use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Edit, Fix};
use ruff_macros::{derive_message_formats, violation};
use ruff_source_file::{OneIndexed, SourceFile};
use ruff_text_size::{TextRange, TextSize};

use crate::rules::text::blank_comments_and_strings;
use crate::settings::Settings;
use crate::TextRule;

fn semicolon_is_superfluous<S: AsRef<str>>(line: S, position: usize) -> bool {
let line = line.as_ref();
// A semicolons is superfluous if:
// - It is at the beginning of a line, possibly containing a line continuation or
// other semicolons.
// - It is at the end of the last statement on a line, even if followed by a line
// continuation character.
// - It is followed by other semicolons (with any amount of whitespace in between)
line.as_bytes()[..position]
.iter()
.all(|b| b.is_ascii_whitespace() || *b == b'&' || *b == b';')
|| bytes_regex_is_match!(r"^;[\s!&]*$", &line.as_bytes()[position..])
|| bytes_regex_is_match!(r"^;\s*;", &line.as_bytes()[position..])
}

/// ## What does it do?
/// Catches a semicolon at the end of a line of code.
///
/// ## Why is this bad?
/// Many languages use semicolons to denote the end of a statement, but in Fortran each
/// line of code is considered its own statement (unless it ends with a line
/// continuation character, `'&'`). Semicolons may be used to separate multiple
/// statements written on the same line, but a semicolon at the end of a line has no
/// effect.
///
/// A semicolon at the beginning of a statement similarly has no effect, nor do
/// multiple semicolons in sequence.
#[violation]
pub struct SuperfluousSemicolon {}

impl AlwaysFixableViolation for SuperfluousSemicolon {
#[derive_message_formats]
fn message(&self) -> String {
format!("unnecessary semicolon")
}

fn fix_title(&self) -> String {
format!("Remove this character")
}
}

impl TextRule for SuperfluousSemicolon {
fn check(_settings: &Settings, source_file: &SourceFile) -> Vec<Diagnostic> {
let source = source_file.to_source_code();
let text = blank_comments_and_strings(source.text());
text.lines()
.enumerate()
.flat_map(|(line_idx, line)| {
let line_start_byte = source.line_start(OneIndexed::from_zero_indexed(line_idx));
line.bytes()
.enumerate()
.filter_map(move |(col_idx, b)| {
if b == b';' && semicolon_is_superfluous(line, col_idx) {
Some(col_idx)
} else {
None
}
})
.map(move |col_idx| {
let leading_whitespace = line.as_bytes()[..col_idx]
.iter()
.rev()
.take_while(|&&b| b == b' ' || b == b'\t')
.count();
let trailing_whitespace = line.as_bytes()[col_idx + 1..]
.iter()
.take_while(|&&b| b == b' ' || b == b'\t')
.count();
let edit_start =
line_start_byte + TextSize::from((col_idx - leading_whitespace) as u32);
let edit_end = line_start_byte
+ TextSize::from((col_idx + 1 + trailing_whitespace) as u32);
let edit = Edit::deletion(edit_start, edit_end);
let report_start = line_start_byte + TextSize::from(col_idx as u32);
let report_end = line_start_byte + TextSize::from((col_idx + 1) as u32);
let range = TextRange::new(report_start, report_end);
Diagnostic::new(Self {}, range).with_fix(Fix::safe_edit(edit))
})
})
.collect()
}
}

/// ## What does it do?
/// Catches multiple statements on the same line separated by a semicolon.
///
/// ## Why is this bad?
/// This can have a detrimental effect on code readability.
#[violation]
pub struct MultipleStatementsPerLine {}

impl AlwaysFixableViolation for MultipleStatementsPerLine {
#[derive_message_formats]
fn message(&self) -> String {
format!("multiple statements per line")
}

fn fix_title(&self) -> String {
format!("Separate over two lines")
}
}

impl TextRule for MultipleStatementsPerLine {
fn check(_settings: &Settings, source_file: &SourceFile) -> Vec<Diagnostic> {
let source = source_file.to_source_code();
let text = blank_comments_and_strings(source.text());
text.lines()
.enumerate()
.flat_map(|(line_idx, line)| {
let line_start_byte = source.line_start(OneIndexed::from_zero_indexed(line_idx));
line.bytes()
.enumerate()
.filter_map(move |(col_idx, b)| {
if b == b';' && !semicolon_is_superfluous(line, col_idx) {
Some(col_idx)
} else {
None
}
})
.map(move |col_idx| {
let leading_whitespace = line.as_bytes()[..col_idx]
.iter()
.rev()
.take_while(|&&b| b == b' ' || b == b'\t')
.count();
let trailing_whitespace = line.as_bytes()[col_idx + 1..]
.iter()
.take_while(|&&b| b == b' ' || b == b'\t')
.count();
let indentation: String =
line.chars().take_while(|c| c.is_whitespace()).collect();
let replacement = format!("\n{indentation}");
let edit_start =
line_start_byte + TextSize::from((col_idx - leading_whitespace) as u32);
let edit_end = line_start_byte
+ TextSize::from((col_idx + 1 + trailing_whitespace) as u32);
let edit = Edit::replacement(replacement, edit_start, edit_end);
let report_start = line_start_byte + TextSize::from(col_idx as u32);
let report_end = line_start_byte + TextSize::from((col_idx + 1) as u32);
let range = TextRange::new(report_start, report_end);
Diagnostic::new(Self {}, range).with_fix(Fix::safe_edit(edit))
})
})
.collect()
}
}
74 changes: 74 additions & 0 deletions fortitude/src/rules/text.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
use lazy_regex::regex_replace_all;

fn blank_double_quote_string(s: &str) -> String {
regex_replace_all!(r#"[^\s&"]*"#, s, |m: &str| " ".repeat(m.len())).into()
}

fn blank_single_quote_string(s: &str) -> String {
regex_replace_all!(r#"[^\s&']*"#, s, |m: &str| " ".repeat(m.len())).into()
}

fn blank_comment(s: &str) -> String {
"!".repeat(s.len())
}

/// Convert contents of strings to whitespace and comments to '!' so text rules won't match.
pub fn blank_comments_and_strings<S: AsRef<str>>(line: S) -> String {
// Need to replace with the equivalent number of _bytes_.
// (?m) at the beginning sets the multiline flag:
regex_replace_all!(
r#"(?m)("[^"]*"|'[^']*'|!.*$)"#,
line.as_ref(),
|_, m: &str| {
match m.chars().next().unwrap() {
'"' => blank_double_quote_string(m),
'\'' => blank_single_quote_string(m),
'!' => blank_comment(m),
_ => unreachable!(),
}
}
)
.into()
}

#[cfg(test)]
mod tests {
use super::*;
use pretty_assertions::assert_eq;

#[test]
fn blank_strings_and_comments() -> anyhow::Result<()> {
// accented letters are two bytes long
// the smiley is three bytes long
let test = r#"
program p
implicit none ! super important
write (*,*) "héllô &
& 'wôrld'! 😀 &

! comments càn go here!
& foo!", 'bàr', &
& "baz", &
' lorum ǐpsum &
& dolor sit &
& àmet'
"#;
let actual = blank_comments_and_strings(test);
let expected = r#"
program p
implicit none !!!!!!!!!!!!!!!!!
write (*,*) " &
& &


& ", ' ', &
& " ", &
' &
& &
& '
"#;
assert_eq!(expected, actual.as_str());

Ok(())
}
}
Loading