1#![allow(clippy::module_name_repetitions)]
4
5use std::sync::Arc;
6
7use rustc_ast::{LitKind, StrStyle};
8use rustc_errors::Applicability;
9use rustc_hir::{BlockCheckMode, Expr, ExprKind, UnsafeSource};
10use rustc_lexer::{FrontmatterAllowed, LiteralKind, TokenKind, tokenize};
11use rustc_lint::{EarlyContext, LateContext};
12use rustc_middle::ty::TyCtxt;
13use rustc_session::Session;
14use rustc_span::source_map::{SourceMap, original_sp};
15use rustc_span::{
16 BytePos, DUMMY_SP, FileNameDisplayPreference, Pos, RelativeBytePos, SourceFile, SourceFileAndLine, Span, SpanData,
17 SyntaxContext, hygiene,
18};
19use std::borrow::Cow;
20use std::fmt;
21use std::ops::{Deref, Index, Range};
22
23pub trait HasSession {
24 fn sess(&self) -> &Session;
25}
26impl HasSession for Session {
27 fn sess(&self) -> &Session {
28 self
29 }
30}
31impl HasSession for TyCtxt<'_> {
32 fn sess(&self) -> &Session {
33 self.sess
34 }
35}
36impl HasSession for EarlyContext<'_> {
37 fn sess(&self) -> &Session {
38 ::rustc_lint::LintContext::sess(self)
39 }
40}
41impl HasSession for LateContext<'_> {
42 fn sess(&self) -> &Session {
43 self.tcx.sess()
44 }
45}
46
47pub trait SpanRange: Sized {
49 fn into_range(self) -> Range<BytePos>;
50}
51impl SpanRange for Span {
52 fn into_range(self) -> Range<BytePos> {
53 let data = self.data();
54 data.lo..data.hi
55 }
56}
57impl SpanRange for SpanData {
58 fn into_range(self) -> Range<BytePos> {
59 self.lo..self.hi
60 }
61}
62impl SpanRange for Range<BytePos> {
63 fn into_range(self) -> Range<BytePos> {
64 self
65 }
66}
67
68pub trait IntoSpan: Sized {
70 fn into_span(self) -> Span;
71 fn with_ctxt(self, ctxt: SyntaxContext) -> Span;
72}
73impl IntoSpan for Span {
74 fn into_span(self) -> Span {
75 self
76 }
77 fn with_ctxt(self, ctxt: SyntaxContext) -> Span {
78 self.with_ctxt(ctxt)
79 }
80}
81impl IntoSpan for SpanData {
82 fn into_span(self) -> Span {
83 self.span()
84 }
85 fn with_ctxt(self, ctxt: SyntaxContext) -> Span {
86 Span::new(self.lo, self.hi, ctxt, self.parent)
87 }
88}
89impl IntoSpan for Range<BytePos> {
90 fn into_span(self) -> Span {
91 Span::with_root_ctxt(self.start, self.end)
92 }
93 fn with_ctxt(self, ctxt: SyntaxContext) -> Span {
94 Span::new(self.start, self.end, ctxt, None)
95 }
96}
97
98pub trait SpanRangeExt: SpanRange {
99 fn get_source_text(self, cx: &impl HasSession) -> Option<SourceText> {
102 get_source_range(cx.sess().source_map(), self.into_range()).and_then(SourceText::new)
103 }
104
105 fn get_source_range(self, cx: &impl HasSession) -> Option<SourceFileRange> {
108 get_source_range(cx.sess().source_map(), self.into_range())
109 }
110
111 fn with_source_text<T>(self, cx: &impl HasSession, f: impl for<'a> FnOnce(&'a str) -> T) -> Option<T> {
114 with_source_text(cx.sess().source_map(), self.into_range(), f)
115 }
116
117 fn check_source_text(self, cx: &impl HasSession, pred: impl for<'a> FnOnce(&'a str) -> bool) -> bool {
120 self.with_source_text(cx, pred).unwrap_or(false)
121 }
122
123 fn with_source_text_and_range<T>(
126 self,
127 cx: &impl HasSession,
128 f: impl for<'a> FnOnce(&'a str, Range<usize>) -> T,
129 ) -> Option<T> {
130 with_source_text_and_range(cx.sess().source_map(), self.into_range(), f)
131 }
132
133 fn map_range(
139 self,
140 cx: &impl HasSession,
141 f: impl for<'a> FnOnce(&'a SourceFile, &'a str, Range<usize>) -> Option<Range<usize>>,
142 ) -> Option<Range<BytePos>> {
143 map_range(cx.sess().source_map(), self.into_range(), f)
144 }
145
146 #[allow(rustdoc::invalid_rust_codeblocks, reason = "The codeblock is intentionally broken")]
147 fn with_leading_whitespace(self, cx: &impl HasSession) -> Range<BytePos> {
161 with_leading_whitespace(cx.sess().source_map(), self.into_range())
162 }
163
164 fn trim_start(self, cx: &impl HasSession) -> Range<BytePos> {
166 trim_start(cx.sess().source_map(), self.into_range())
167 }
168}
169impl<T: SpanRange> SpanRangeExt for T {}
170
171pub struct SourceText(SourceFileRange);
173impl SourceText {
174 pub fn new(text: SourceFileRange) -> Option<Self> {
176 if text.as_str().is_some() {
177 Some(Self(text))
178 } else {
179 None
180 }
181 }
182
183 pub fn as_str(&self) -> &str {
185 self.0.as_str().unwrap()
186 }
187
188 pub fn to_owned(&self) -> String {
190 self.as_str().to_owned()
191 }
192}
193impl Deref for SourceText {
194 type Target = str;
195 fn deref(&self) -> &Self::Target {
196 self.as_str()
197 }
198}
199impl AsRef<str> for SourceText {
200 fn as_ref(&self) -> &str {
201 self.as_str()
202 }
203}
204impl<T> Index<T> for SourceText
205where
206 str: Index<T>,
207{
208 type Output = <str as Index<T>>::Output;
209 fn index(&self, idx: T) -> &Self::Output {
210 &self.as_str()[idx]
211 }
212}
213impl fmt::Display for SourceText {
214 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
215 self.as_str().fmt(f)
216 }
217}
218
219fn get_source_range(sm: &SourceMap, sp: Range<BytePos>) -> Option<SourceFileRange> {
220 let start = sm.lookup_byte_offset(sp.start);
221 let end = sm.lookup_byte_offset(sp.end);
222 if !Arc::ptr_eq(&start.sf, &end.sf) || start.pos > end.pos {
223 return None;
224 }
225 sm.ensure_source_file_source_present(&start.sf);
226 let range = start.pos.to_usize()..end.pos.to_usize();
227 Some(SourceFileRange { sf: start.sf, range })
228}
229
230fn with_source_text<T>(sm: &SourceMap, sp: Range<BytePos>, f: impl for<'a> FnOnce(&'a str) -> T) -> Option<T> {
231 if let Some(src) = get_source_range(sm, sp)
232 && let Some(src) = src.as_str()
233 {
234 Some(f(src))
235 } else {
236 None
237 }
238}
239
240fn with_source_text_and_range<T>(
241 sm: &SourceMap,
242 sp: Range<BytePos>,
243 f: impl for<'a> FnOnce(&'a str, Range<usize>) -> T,
244) -> Option<T> {
245 if let Some(src) = get_source_range(sm, sp)
246 && let Some(text) = &src.sf.src
247 {
248 Some(f(text, src.range))
249 } else {
250 None
251 }
252}
253
254#[expect(clippy::cast_possible_truncation)]
255fn map_range(
256 sm: &SourceMap,
257 sp: Range<BytePos>,
258 f: impl for<'a> FnOnce(&'a SourceFile, &'a str, Range<usize>) -> Option<Range<usize>>,
259) -> Option<Range<BytePos>> {
260 if let Some(src) = get_source_range(sm, sp.clone())
261 && let Some(text) = &src.sf.src
262 && let Some(range) = f(&src.sf, text, src.range.clone())
263 {
264 debug_assert!(
265 range.start <= text.len() && range.end <= text.len(),
266 "Range `{range:?}` is outside the source file (file `{}`, length `{}`)",
267 src.sf.name.display(FileNameDisplayPreference::Local),
268 text.len(),
269 );
270 debug_assert!(range.start <= range.end, "Range `{range:?}` has overlapping bounds");
271 let dstart = (range.start as u32).wrapping_sub(src.range.start as u32);
272 let dend = (range.end as u32).wrapping_sub(src.range.start as u32);
273 Some(BytePos(sp.start.0.wrapping_add(dstart))..BytePos(sp.start.0.wrapping_add(dend)))
274 } else {
275 None
276 }
277}
278
279fn ends_with_line_comment_or_broken(text: &str) -> bool {
280 let Some(last) = tokenize(text, FrontmatterAllowed::No).last() else {
281 return false;
282 };
283 match last.kind {
284 TokenKind::LineComment { .. } | TokenKind::BlockComment { terminated: false, .. } => true,
288 TokenKind::Literal { kind, .. } => matches!(
289 kind,
290 LiteralKind::Byte { terminated: false }
291 | LiteralKind::ByteStr { terminated: false }
292 | LiteralKind::CStr { terminated: false }
293 | LiteralKind::Char { terminated: false }
294 | LiteralKind::RawByteStr { n_hashes: None }
295 | LiteralKind::RawCStr { n_hashes: None }
296 | LiteralKind::RawStr { n_hashes: None }
297 ),
298 _ => false,
299 }
300}
301
302fn with_leading_whitespace_inner(lines: &[RelativeBytePos], src: &str, range: Range<usize>) -> Option<usize> {
303 debug_assert!(lines.is_empty() || lines[0].to_u32() == 0);
304
305 let start = src.get(..range.start)?.trim_end();
306 let next_line = lines.partition_point(|&pos| pos.to_usize() <= start.len());
307 if let Some(line_end) = lines.get(next_line)
308 && line_end.to_usize() <= range.start
309 && let prev_start = lines.get(next_line - 1).map_or(0, |&x| x.to_usize())
310 && ends_with_line_comment_or_broken(&start[prev_start..])
311 && let next_line = lines.partition_point(|&pos| pos.to_usize() < range.end)
312 && let next_start = lines.get(next_line).map_or(src.len(), |&x| x.to_usize())
313 && tokenize(src.get(range.end..next_start)?, FrontmatterAllowed::No)
314 .any(|t| !matches!(t.kind, TokenKind::Whitespace))
315 {
316 Some(range.start)
317 } else {
318 Some(start.len())
319 }
320}
321
322fn with_leading_whitespace(sm: &SourceMap, sp: Range<BytePos>) -> Range<BytePos> {
323 map_range(sm, sp.clone(), |sf, src, range| {
324 Some(with_leading_whitespace_inner(sf.lines(), src, range.clone())?..range.end)
325 })
326 .unwrap_or(sp)
327}
328
329fn trim_start(sm: &SourceMap, sp: Range<BytePos>) -> Range<BytePos> {
330 map_range(sm, sp.clone(), |_, src, range| {
331 let src = src.get(range.clone())?;
332 Some(range.start + (src.len() - src.trim_start().len())..range.end)
333 })
334 .unwrap_or(sp)
335}
336
337pub struct SourceFileRange {
338 pub sf: Arc<SourceFile>,
339 pub range: Range<usize>,
340}
341impl SourceFileRange {
342 pub fn as_str(&self) -> Option<&str> {
345 self.sf
346 .src
347 .as_ref()
348 .map(|src| src.as_str())
349 .or_else(|| self.sf.external_src.get().and_then(|src| src.get_source()))
350 .and_then(|x| x.get(self.range.clone()))
351 }
352}
353
354pub fn expr_block(
356 sess: &impl HasSession,
357 expr: &Expr<'_>,
358 outer: SyntaxContext,
359 default: &str,
360 indent_relative_to: Option<Span>,
361 app: &mut Applicability,
362) -> String {
363 let (code, from_macro) = snippet_block_with_context(sess, expr.span, outer, default, indent_relative_to, app);
364 if !from_macro
365 && let ExprKind::Block(block, None) = expr.kind
366 && block.rules != BlockCheckMode::UnsafeBlock(UnsafeSource::UserProvided)
367 {
368 code
369 } else {
370 format!("{{ {code} }}")
375 }
376}
377
378pub fn first_line_of_span(sess: &impl HasSession, span: Span) -> Span {
389 first_char_in_first_line(sess, span).map_or(span, |first_char_pos| span.with_lo(first_char_pos))
390}
391
392fn first_char_in_first_line(sess: &impl HasSession, span: Span) -> Option<BytePos> {
393 let line_span = line_span(sess, span);
394 snippet_opt(sess, line_span).and_then(|snip| {
395 snip.find(|c: char| !c.is_whitespace())
396 .map(|pos| line_span.lo() + BytePos::from_usize(pos))
397 })
398}
399
400fn line_span(sess: &impl HasSession, span: Span) -> Span {
410 let span = original_sp(span, DUMMY_SP);
411 let SourceFileAndLine { sf, line } = sess.sess().source_map().lookup_line(span.lo()).unwrap();
412 let line_start = sf.lines()[line];
413 let line_start = sf.absolute_position(line_start);
414 span.with_lo(line_start)
415}
416
417pub fn indent_of(sess: &impl HasSession, span: Span) -> Option<usize> {
426 snippet_opt(sess, line_span(sess, span)).and_then(|snip| snip.find(|c: char| !c.is_whitespace()))
427}
428
429pub fn snippet_indent(sess: &impl HasSession, span: Span) -> Option<String> {
431 snippet_opt(sess, line_span(sess, span)).map(|mut s| {
432 let len = s.len() - s.trim_start().len();
433 s.truncate(len);
434 s
435 })
436}
437
438pub fn is_present_in_source(sess: &impl HasSession, span: Span) -> bool {
444 if let Some(snippet) = snippet_opt(sess, span)
445 && snippet.is_empty()
446 {
447 return false;
448 }
449 true
450}
451
452pub fn position_before_rarrow(s: &str) -> Option<usize> {
464 s.rfind("->").map(|rpos| {
465 let mut rpos = rpos;
466 let chars: Vec<char> = s.chars().collect();
467 while rpos > 1 {
468 if let Some(c) = chars.get(rpos - 1)
469 && c.is_whitespace()
470 {
471 rpos -= 1;
472 continue;
473 }
474 break;
475 }
476 rpos
477 })
478}
479
480pub fn reindent_multiline(s: &str, ignore_first: bool, indent: Option<usize>) -> String {
482 let s_space = reindent_multiline_inner(s, ignore_first, indent, ' ');
483 let s_tab = reindent_multiline_inner(&s_space, ignore_first, indent, '\t');
484 reindent_multiline_inner(&s_tab, ignore_first, indent, ' ')
485}
486
487fn reindent_multiline_inner(s: &str, ignore_first: bool, indent: Option<usize>, ch: char) -> String {
488 let x = s
489 .lines()
490 .skip(usize::from(ignore_first))
491 .filter_map(|l| {
492 if l.is_empty() {
493 None
494 } else {
495 Some(l.char_indices().find(|&(_, x)| x != ch).unwrap_or((l.len(), ch)).0)
497 }
498 })
499 .min()
500 .unwrap_or(0);
501 let indent = indent.unwrap_or(0);
502 s.lines()
503 .enumerate()
504 .map(|(i, l)| {
505 if (ignore_first && i == 0) || l.is_empty() {
506 l.to_owned()
507 } else if x > indent {
508 l.split_at(x - indent).1.to_owned()
509 } else {
510 " ".repeat(indent - x) + l
511 }
512 })
513 .collect::<Vec<String>>()
514 .join("\n")
515}
516
517pub fn snippet<'a>(sess: &impl HasSession, span: Span, default: &'a str) -> Cow<'a, str> {
535 snippet_opt(sess, span).map_or_else(|| Cow::Borrowed(default), From::from)
536}
537
538pub fn snippet_with_applicability<'a>(
545 sess: &impl HasSession,
546 span: Span,
547 default: &'a str,
548 applicability: &mut Applicability,
549) -> Cow<'a, str> {
550 snippet_with_applicability_sess(sess.sess(), span, default, applicability)
551}
552
553fn snippet_with_applicability_sess<'a>(
554 sess: &Session,
555 span: Span,
556 default: &'a str,
557 applicability: &mut Applicability,
558) -> Cow<'a, str> {
559 if *applicability != Applicability::Unspecified && span.from_expansion() {
560 *applicability = Applicability::MaybeIncorrect;
561 }
562 snippet_opt(sess, span).map_or_else(
563 || {
564 if *applicability == Applicability::MachineApplicable {
565 *applicability = Applicability::HasPlaceholders;
566 }
567 Cow::Borrowed(default)
568 },
569 From::from,
570 )
571}
572
573pub fn snippet_opt(sess: &impl HasSession, span: Span) -> Option<String> {
575 sess.sess().source_map().span_to_snippet(span).ok()
576}
577
578pub fn snippet_block(sess: &impl HasSession, span: Span, default: &str, indent_relative_to: Option<Span>) -> String {
613 let snip = snippet(sess, span, default);
614 let indent = indent_relative_to.and_then(|s| indent_of(sess, s));
615 reindent_multiline(&snip, true, indent)
616}
617
618pub fn snippet_block_with_applicability(
621 sess: &impl HasSession,
622 span: Span,
623 default: &str,
624 indent_relative_to: Option<Span>,
625 applicability: &mut Applicability,
626) -> String {
627 let snip = snippet_with_applicability(sess, span, default, applicability);
628 let indent = indent_relative_to.and_then(|s| indent_of(sess, s));
629 reindent_multiline(&snip, true, indent)
630}
631
632pub fn snippet_block_with_context(
633 sess: &impl HasSession,
634 span: Span,
635 outer: SyntaxContext,
636 default: &str,
637 indent_relative_to: Option<Span>,
638 app: &mut Applicability,
639) -> (String, bool) {
640 let (snip, from_macro) = snippet_with_context(sess, span, outer, default, app);
641 let indent = indent_relative_to.and_then(|s| indent_of(sess, s));
642 (reindent_multiline(&snip, true, indent), from_macro)
643}
644
645pub fn snippet_with_context<'a>(
656 sess: &impl HasSession,
657 span: Span,
658 outer: SyntaxContext,
659 default: &'a str,
660 applicability: &mut Applicability,
661) -> (Cow<'a, str>, bool) {
662 snippet_with_context_sess(sess.sess(), span, outer, default, applicability)
663}
664
665fn snippet_with_context_sess<'a>(
666 sess: &Session,
667 span: Span,
668 outer: SyntaxContext,
669 default: &'a str,
670 applicability: &mut Applicability,
671) -> (Cow<'a, str>, bool) {
672 let (span, is_macro_call) = walk_span_to_context(span, outer).map_or_else(
673 || {
674 if *applicability != Applicability::Unspecified {
676 *applicability = Applicability::MaybeIncorrect;
677 }
678 (span, false)
680 },
681 |outer_span| (outer_span, span.ctxt() != outer),
682 );
683
684 (
685 snippet_with_applicability_sess(sess, span, default, applicability),
686 is_macro_call,
687 )
688}
689
690pub fn walk_span_to_context(span: Span, outer: SyntaxContext) -> Option<Span> {
718 let outer_span = hygiene::walk_chain(span, outer);
719 (outer_span.ctxt() == outer).then_some(outer_span)
720}
721
722pub fn trim_span(sm: &SourceMap, span: Span) -> Span {
724 let data = span.data();
725 let sf: &_ = &sm.lookup_source_file(data.lo);
726 let Some(src) = sf.src.as_deref() else {
727 return span;
728 };
729 let Some(snip) = &src.get((data.lo - sf.start_pos).to_usize()..(data.hi - sf.start_pos).to_usize()) else {
730 return span;
731 };
732 let trim_start = snip.len() - snip.trim_start().len();
733 let trim_end = snip.len() - snip.trim_end().len();
734 SpanData {
735 lo: data.lo + BytePos::from_usize(trim_start),
736 hi: data.hi - BytePos::from_usize(trim_end),
737 ctxt: data.ctxt,
738 parent: data.parent,
739 }
740 .span()
741}
742
743pub fn expand_past_previous_comma(sess: &impl HasSession, span: Span) -> Span {
749 let extended = sess.sess().source_map().span_extend_to_prev_char(span, ',', true);
750 extended.with_lo(extended.lo() - BytePos(1))
751}
752
753pub fn str_literal_to_char_literal(
756 sess: &impl HasSession,
757 expr: &Expr<'_>,
758 applicability: &mut Applicability,
759 ascii_only: bool,
760) -> Option<String> {
761 if let ExprKind::Lit(lit) = &expr.kind
762 && let LitKind::Str(r, style) = lit.node
763 && let string = r.as_str()
764 && let len = if ascii_only {
765 string.len()
766 } else {
767 string.chars().count()
768 }
769 && len == 1
770 {
771 let snip = snippet_with_applicability(sess, expr.span, string, applicability);
772 let ch = if let StrStyle::Raw(nhash) = style {
773 let nhash = nhash as usize;
774 &snip[(nhash + 2)..(snip.len() - 1 - nhash)]
776 } else {
777 &snip[1..(snip.len() - 1)]
779 };
780
781 let hint = format!(
782 "'{}'",
783 match ch {
784 "'" => "\\'",
785 r"\" => "\\\\",
786 "\\\"" => "\"", _ => ch,
788 }
789 );
790
791 Some(hint)
792 } else {
793 None
794 }
795}
796
797#[cfg(test)]
798mod test {
799 use super::reindent_multiline;
800
801 #[test]
802 fn test_reindent_multiline_single_line() {
803 assert_eq!("", reindent_multiline("", false, None));
804 assert_eq!("...", reindent_multiline("...", false, None));
805 assert_eq!("...", reindent_multiline(" ...", false, None));
806 assert_eq!("...", reindent_multiline("\t...", false, None));
807 assert_eq!("...", reindent_multiline("\t\t...", false, None));
808 }
809
810 #[test]
811 #[rustfmt::skip]
812 fn test_reindent_multiline_block() {
813 assert_eq!("\
814 if x {
815 y
816 } else {
817 z
818 }", reindent_multiline(" if x {
819 y
820 } else {
821 z
822 }", false, None));
823 assert_eq!("\
824 if x {
825 \ty
826 } else {
827 \tz
828 }", reindent_multiline(" if x {
829 \ty
830 } else {
831 \tz
832 }", false, None));
833 }
834
835 #[test]
836 #[rustfmt::skip]
837 fn test_reindent_multiline_empty_line() {
838 assert_eq!("\
839 if x {
840 y
841
842 } else {
843 z
844 }", reindent_multiline(" if x {
845 y
846
847 } else {
848 z
849 }", false, None));
850 }
851
852 #[test]
853 #[rustfmt::skip]
854 fn test_reindent_multiline_lines_deeper() {
855 assert_eq!("\
856 if x {
857 y
858 } else {
859 z
860 }", reindent_multiline("\
861 if x {
862 y
863 } else {
864 z
865 }", true, Some(8)));
866 }
867}