Skip to content

Commit

Permalink
Add SourceMap::indentation_before.
Browse files Browse the repository at this point in the history
  • Loading branch information
m-ou-se committed Nov 16, 2021
1 parent d914f17 commit 483cff7
Showing 1 changed file with 12 additions and 7 deletions.
19 changes: 12 additions & 7 deletions compiler/rustc_span/src/source_map.rs
Expand Up @@ -593,14 +593,19 @@ impl SourceMap {
}

pub fn span_to_margin(&self, sp: Span) -> Option<usize> {
match self.span_to_prev_source(sp) {
Err(_) => None,
Ok(source) => {
let last_line = source.rsplit_once('\n').unwrap_or(("", &source)).1;
Some(self.indentation_before(sp)?.len())
}

Some(last_line.len() - last_line.trim_start().len())
}
}
pub fn indentation_before(&self, sp: Span) -> Option<String> {
self.span_to_source(sp, |src, start_index, _| {
let before = &src[..start_index];
let last_line = before.rsplit_once('\n').map_or(before, |(_, last)| last);
Ok(last_line
.split_once(|c: char| !c.is_whitespace())
.map_or(last_line, |(indent, _)| indent)
.to_string())
})
.ok()
}

/// Returns the source snippet as `String` before the given `Span`.
Expand Down

0 comments on commit 483cff7

Please sign in to comment.