Skip to content

Commit 000dbd2

Browse files
authored
Rollup merge of #86165 - m-ou-se:proc-macro-span-shrink, r=dtolnay
Add proc_macro::Span::{before, after}. This adds `proc_macro::Span::before()` and `proc_macro::Span::after()` to get a zero width span at the start or end of the span. These are equivalent to rustc's `Span::shrink_to_lo()` and `Span::shrink_to_hi()` but with a less cryptic name. They are useful when generating diagnostlics like "missing \<thing\> after \<thing\>". E.g. ```rust syn::Error::new(ident.span().after(), "missing `:` after field name").into_compile_error() ```
2 parents acfe7c4 + f9be6cd commit 000dbd2

File tree

3 files changed

+20
-0
lines changed

3 files changed

+20
-0
lines changed

compiler/rustc_expand/src/proc_macro_server.rs

+6
Original file line numberDiff line numberDiff line change
@@ -758,6 +758,12 @@ impl server::Span for Rustc<'_> {
758758
let loc = self.sess.source_map().lookup_char_pos(span.hi());
759759
LineColumn { line: loc.line, column: loc.col.to_usize() }
760760
}
761+
fn before(&mut self, span: Self::Span) -> Self::Span {
762+
span.shrink_to_lo()
763+
}
764+
fn after(&mut self, span: Self::Span) -> Self::Span {
765+
span.shrink_to_hi()
766+
}
761767
fn join(&mut self, first: Self::Span, second: Self::Span) -> Option<Self::Span> {
762768
let self_loc = self.sess.source_map().lookup_char_pos(first.lo());
763769
let other_loc = self.sess.source_map().lookup_char_pos(second.lo());

library/proc_macro/src/bridge/mod.rs

+2
Original file line numberDiff line numberDiff line change
@@ -162,6 +162,8 @@ macro_rules! with_api {
162162
fn source($self: $S::Span) -> $S::Span;
163163
fn start($self: $S::Span) -> LineColumn;
164164
fn end($self: $S::Span) -> LineColumn;
165+
fn before($self: $S::Span) -> $S::Span;
166+
fn after($self: $S::Span) -> $S::Span;
165167
fn join($self: $S::Span, other: $S::Span) -> Option<$S::Span>;
166168
fn resolved_at($self: $S::Span, at: $S::Span) -> $S::Span;
167169
fn source_text($self: $S::Span) -> Option<String>;

library/proc_macro/src/lib.rs

+12
Original file line numberDiff line numberDiff line change
@@ -357,6 +357,18 @@ impl Span {
357357
self.0.end().add_1_to_column()
358358
}
359359

360+
/// Creates an empty span pointing to directly before this span.
361+
#[unstable(feature = "proc_macro_span_shrink", issue = "87552")]
362+
pub fn before(&self) -> Span {
363+
Span(self.0.before())
364+
}
365+
366+
/// Creates an empty span pointing to directly after this span.
367+
#[unstable(feature = "proc_macro_span_shrink", issue = "87552")]
368+
pub fn after(&self) -> Span {
369+
Span(self.0.after())
370+
}
371+
360372
/// Creates a new span encompassing `self` and `other`.
361373
///
362374
/// Returns `None` if `self` and `other` are from different files.

0 commit comments

Comments
 (0)