use crate::config::Style;
use crate::options::StyleOption;
use crate::tokens::Stream;
pub fn disabled_spans(source: &str) -> Vec<(usize, usize)> {
let mut spans = Vec::new();
let mut start: Option<usize> = None;
let mut offset = 0usize;
for line in source.split_inclusive('\n') {
let line_start = offset;
offset += line.len();
let marker = marker_of(line);
match marker {
Some(Marker::Off) if start.is_none() => start = Some(line_start),
Some(Marker::On) => {
if let Some(begin) = start.take() {
spans.push((begin, offset));
}
}
_ => {}
}
}
if let Some(begin) = start {
spans.push((begin, source.len()));
}
spans
}
pub fn is_disabled(spans: &[(usize, usize)], offset: usize) -> bool {
spans
.iter()
.any(|(begin, end)| offset >= *begin && offset < *end)
}
pub fn per_token(stream: &Stream<'_>, spans: &[(usize, usize)]) -> Vec<bool> {
let mut flags = vec![false; stream.tokens.len()];
for (index, disabled) in flags.iter_mut().enumerate() {
let gap = &stream.gaps[index];
*disabled = is_disabled(spans, gap.start.max(gap.end.saturating_sub(1)))
|| is_disabled(spans, stream.tokens[index].start);
}
flags
}
pub fn is_fully_disabled(style: &Style) -> bool {
style.flag(StyleOption::DisableFormat)
}
enum Marker {
Off,
On,
}
fn marker_of(line: &str) -> Option<Marker> {
let text = line.trim();
let body = if let Some(rest) = text.strip_prefix("//") {
rest
} else {
let rest = text.strip_prefix("/*")?;
rest.trim_end_matches("*/")
};
let body = body.trim().trim_start_matches(':').trim();
let mut words = body.split_whitespace();
if words.next()? != "clang-format" {
return None;
}
let rest: Vec<&str> = words.collect();
let off = rest.contains(&"off");
let on = rest.contains(&"on");
match (off, on) {
(true, _) => Some(Marker::Off),
(_, true) => Some(Marker::On),
_ => None,
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_span_runs_from_off_to_on_inclusive() {
let source = "int a;\n// clang-format off\nint b = 1;\n// clang-format on\nint c;\n";
let spans = disabled_spans(source);
assert_eq!(spans.len(), 1);
let (begin, end) = spans[0];
assert!(source[begin..end].starts_with("// clang-format off"));
assert!(
source[begin..end]
.trim_end()
.ends_with("// clang-format on")
);
assert!(!is_disabled(&spans, 0), "the first line is still ours");
assert!(is_disabled(&spans, begin + 1));
}
#[test]
fn an_unterminated_span_runs_to_the_end() {
let source = "int a;\n// clang-format off\nint b = 1;\n";
let spans = disabled_spans(source);
assert_eq!(spans.len(), 1);
assert_eq!(spans[0].1, source.len());
}
#[test]
fn the_block_comment_spelling_counts() {
let source = "/* clang-format off */\nint b;\n/* clang-format on */\n";
assert_eq!(disabled_spans(source).len(), 1);
}
#[test]
fn an_ordinary_comment_is_not_a_marker() {
let source = "// clang-format is a tool\nint a;\n// off we go\n";
assert!(disabled_spans(source).is_empty());
}
}