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_lint::{EarlyContext, LateContext};
11use rustc_middle::ty::TyCtxt;
12use rustc_session::Session;
13use rustc_span::source_map::{SourceMap, original_sp};
14use rustc_span::{
15 BytePos, DUMMY_SP, FileNameDisplayPreference, Pos, SourceFile, SourceFileAndLine, Span, SpanData, SyntaxContext,
16 hygiene,
17};
18use std::borrow::Cow;
19use std::fmt;
20use std::ops::{Deref, Index, Range};
21
22pub trait HasSession {
23 fn sess(&self) -> &Session;
24}
25impl HasSession for Session {
26 fn sess(&self) -> &Session {
27 self
28 }
29}
30impl HasSession for TyCtxt<'_> {
31 fn sess(&self) -> &Session {
32 self.sess
33 }
34}
35impl HasSession for EarlyContext<'_> {
36 fn sess(&self) -> &Session {
37 ::rustc_lint::LintContext::sess(self)
38 }
39}
40impl HasSession for LateContext<'_> {
41 fn sess(&self) -> &Session {
42 self.tcx.sess()
43 }
44}
45
46pub trait SpanRange: Sized {
48 fn into_range(self) -> Range<BytePos>;
49}
50impl SpanRange for Span {
51 fn into_range(self) -> Range<BytePos> {
52 let data = self.data();
53 data.lo..data.hi
54 }
55}
56impl SpanRange for SpanData {
57 fn into_range(self) -> Range<BytePos> {
58 self.lo..self.hi
59 }
60}
61impl SpanRange for Range<BytePos> {
62 fn into_range(self) -> Range<BytePos> {
63 self
64 }
65}
66
67pub trait IntoSpan: Sized {
69 fn into_span(self) -> Span;
70 fn with_ctxt(self, ctxt: SyntaxContext) -> Span;
71}
72impl IntoSpan for Span {
73 fn into_span(self) -> Span {
74 self
75 }
76 fn with_ctxt(self, ctxt: SyntaxContext) -> Span {
77 self.with_ctxt(ctxt)
78 }
79}
80impl IntoSpan for SpanData {
81 fn into_span(self) -> Span {
82 self.span()
83 }
84 fn with_ctxt(self, ctxt: SyntaxContext) -> Span {
85 Span::new(self.lo, self.hi, ctxt, self.parent)
86 }
87}
88impl IntoSpan for Range<BytePos> {
89 fn into_span(self) -> Span {
90 Span::with_root_ctxt(self.start, self.end)
91 }
92 fn with_ctxt(self, ctxt: SyntaxContext) -> Span {
93 Span::new(self.start, self.end, ctxt, None)
94 }
95}
96
97pub trait SpanRangeExt: SpanRange {
98 fn get_source_text(self, cx: &impl HasSession) -> Option<SourceText> {
101 get_source_range(cx.sess().source_map(), self.into_range()).and_then(SourceText::new)
102 }
103
104 fn get_source_range(self, cx: &impl HasSession) -> Option<SourceFileRange> {
107 get_source_range(cx.sess().source_map(), self.into_range())
108 }
109
110 fn with_source_text<T>(self, cx: &impl HasSession, f: impl for<'a> FnOnce(&'a str) -> T) -> Option<T> {
113 with_source_text(cx.sess().source_map(), self.into_range(), f)
114 }
115
116 fn check_source_text(self, cx: &impl HasSession, pred: impl for<'a> FnOnce(&'a str) -> bool) -> bool {
119 self.with_source_text(cx, pred).unwrap_or(false)
120 }
121
122 fn with_source_text_and_range<T>(
125 self,
126 cx: &impl HasSession,
127 f: impl for<'a> FnOnce(&'a str, Range<usize>) -> T,
128 ) -> Option<T> {
129 with_source_text_and_range(cx.sess().source_map(), self.into_range(), f)
130 }
131
132 fn map_range(
138 self,
139 cx: &impl HasSession,
140 f: impl for<'a> FnOnce(&'a str, Range<usize>) -> Option<Range<usize>>,
141 ) -> Option<Range<BytePos>> {
142 map_range(cx.sess().source_map(), self.into_range(), f)
143 }
144
145 fn with_leading_whitespace(self, cx: &impl HasSession) -> Range<BytePos> {
147 with_leading_whitespace(cx.sess().source_map(), self.into_range())
148 }
149
150 fn trim_start(self, cx: &impl HasSession) -> Range<BytePos> {
152 trim_start(cx.sess().source_map(), self.into_range())
153 }
154}
155impl<T: SpanRange> SpanRangeExt for T {}
156
157pub struct SourceText(SourceFileRange);
159impl SourceText {
160 pub fn new(text: SourceFileRange) -> Option<Self> {
162 if text.as_str().is_some() {
163 Some(Self(text))
164 } else {
165 None
166 }
167 }
168
169 pub fn as_str(&self) -> &str {
171 self.0.as_str().unwrap()
172 }
173
174 pub fn to_owned(&self) -> String {
176 self.as_str().to_owned()
177 }
178}
179impl Deref for SourceText {
180 type Target = str;
181 fn deref(&self) -> &Self::Target {
182 self.as_str()
183 }
184}
185impl AsRef<str> for SourceText {
186 fn as_ref(&self) -> &str {
187 self.as_str()
188 }
189}
190impl<T> Index<T> for SourceText
191where
192 str: Index<T>,
193{
194 type Output = <str as Index<T>>::Output;
195 fn index(&self, idx: T) -> &Self::Output {
196 &self.as_str()[idx]
197 }
198}
199impl fmt::Display for SourceText {
200 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
201 self.as_str().fmt(f)
202 }
203}
204
205fn get_source_range(sm: &SourceMap, sp: Range<BytePos>) -> Option<SourceFileRange> {
206 let start = sm.lookup_byte_offset(sp.start);
207 let end = sm.lookup_byte_offset(sp.end);
208 if !Arc::ptr_eq(&start.sf, &end.sf) || start.pos > end.pos {
209 return None;
210 }
211 sm.ensure_source_file_source_present(&start.sf);
212 let range = start.pos.to_usize()..end.pos.to_usize();
213 Some(SourceFileRange { sf: start.sf, range })
214}
215
216fn with_source_text<T>(sm: &SourceMap, sp: Range<BytePos>, f: impl for<'a> FnOnce(&'a str) -> T) -> Option<T> {
217 if let Some(src) = get_source_range(sm, sp)
218 && let Some(src) = src.as_str()
219 {
220 Some(f(src))
221 } else {
222 None
223 }
224}
225
226fn with_source_text_and_range<T>(
227 sm: &SourceMap,
228 sp: Range<BytePos>,
229 f: impl for<'a> FnOnce(&'a str, Range<usize>) -> T,
230) -> Option<T> {
231 if let Some(src) = get_source_range(sm, sp)
232 && let Some(text) = &src.sf.src
233 {
234 Some(f(text, src.range))
235 } else {
236 None
237 }
238}
239
240#[expect(clippy::cast_possible_truncation)]
241fn map_range(
242 sm: &SourceMap,
243 sp: Range<BytePos>,
244 f: impl for<'a> FnOnce(&'a str, Range<usize>) -> Option<Range<usize>>,
245) -> Option<Range<BytePos>> {
246 if let Some(src) = get_source_range(sm, sp.clone())
247 && let Some(text) = &src.sf.src
248 && let Some(range) = f(text, src.range.clone())
249 {
250 debug_assert!(
251 range.start <= text.len() && range.end <= text.len(),
252 "Range `{range:?}` is outside the source file (file `{}`, length `{}`)",
253 src.sf.name.display(FileNameDisplayPreference::Local),
254 text.len(),
255 );
256 debug_assert!(range.start <= range.end, "Range `{range:?}` has overlapping bounds");
257 let dstart = (range.start as u32).wrapping_sub(src.range.start as u32);
258 let dend = (range.end as u32).wrapping_sub(src.range.start as u32);
259 Some(BytePos(sp.start.0.wrapping_add(dstart))..BytePos(sp.start.0.wrapping_add(dend)))
260 } else {
261 None
262 }
263}
264
265fn with_leading_whitespace(sm: &SourceMap, sp: Range<BytePos>) -> Range<BytePos> {
266 map_range(sm, sp.clone(), |src, range| {
267 Some(src.get(..range.start)?.trim_end().len()..range.end)
268 })
269 .unwrap_or(sp)
270}
271
272fn trim_start(sm: &SourceMap, sp: Range<BytePos>) -> Range<BytePos> {
273 map_range(sm, sp.clone(), |src, range| {
274 let src = src.get(range.clone())?;
275 Some(range.start + (src.len() - src.trim_start().len())..range.end)
276 })
277 .unwrap_or(sp)
278}
279
280pub struct SourceFileRange {
281 pub sf: Arc<SourceFile>,
282 pub range: Range<usize>,
283}
284impl SourceFileRange {
285 pub fn as_str(&self) -> Option<&str> {
288 self.sf
289 .src
290 .as_ref()
291 .map(|src| src.as_str())
292 .or_else(|| self.sf.external_src.get().and_then(|src| src.get_source()))
293 .and_then(|x| x.get(self.range.clone()))
294 }
295}
296
297pub fn expr_block(
299 sess: &impl HasSession,
300 expr: &Expr<'_>,
301 outer: SyntaxContext,
302 default: &str,
303 indent_relative_to: Option<Span>,
304 app: &mut Applicability,
305) -> String {
306 let (code, from_macro) = snippet_block_with_context(sess, expr.span, outer, default, indent_relative_to, app);
307 if !from_macro
308 && let ExprKind::Block(block, None) = expr.kind
309 && block.rules != BlockCheckMode::UnsafeBlock(UnsafeSource::UserProvided)
310 {
311 code
312 } else {
313 format!("{{ {code} }}")
318 }
319}
320
321pub fn first_line_of_span(sess: &impl HasSession, span: Span) -> Span {
332 first_char_in_first_line(sess, span).map_or(span, |first_char_pos| span.with_lo(first_char_pos))
333}
334
335fn first_char_in_first_line(sess: &impl HasSession, span: Span) -> Option<BytePos> {
336 let line_span = line_span(sess, span);
337 snippet_opt(sess, line_span).and_then(|snip| {
338 snip.find(|c: char| !c.is_whitespace())
339 .map(|pos| line_span.lo() + BytePos::from_usize(pos))
340 })
341}
342
343fn line_span(sess: &impl HasSession, span: Span) -> Span {
353 let span = original_sp(span, DUMMY_SP);
354 let SourceFileAndLine { sf, line } = sess.sess().source_map().lookup_line(span.lo()).unwrap();
355 let line_start = sf.lines()[line];
356 let line_start = sf.absolute_position(line_start);
357 span.with_lo(line_start)
358}
359
360pub fn indent_of(sess: &impl HasSession, span: Span) -> Option<usize> {
369 snippet_opt(sess, line_span(sess, span)).and_then(|snip| snip.find(|c: char| !c.is_whitespace()))
370}
371
372pub fn snippet_indent(sess: &impl HasSession, span: Span) -> Option<String> {
374 snippet_opt(sess, line_span(sess, span)).map(|mut s| {
375 let len = s.len() - s.trim_start().len();
376 s.truncate(len);
377 s
378 })
379}
380
381pub fn is_present_in_source(sess: &impl HasSession, span: Span) -> bool {
387 if let Some(snippet) = snippet_opt(sess, span) {
388 if snippet.is_empty() {
389 return false;
390 }
391 }
392 true
393}
394
395pub fn position_before_rarrow(s: &str) -> Option<usize> {
407 s.rfind("->").map(|rpos| {
408 let mut rpos = rpos;
409 let chars: Vec<char> = s.chars().collect();
410 while rpos > 1 {
411 if let Some(c) = chars.get(rpos - 1) {
412 if c.is_whitespace() {
413 rpos -= 1;
414 continue;
415 }
416 }
417 break;
418 }
419 rpos
420 })
421}
422
423pub fn reindent_multiline(s: &str, ignore_first: bool, indent: Option<usize>) -> String {
425 let s_space = reindent_multiline_inner(s, ignore_first, indent, ' ');
426 let s_tab = reindent_multiline_inner(&s_space, ignore_first, indent, '\t');
427 reindent_multiline_inner(&s_tab, ignore_first, indent, ' ')
428}
429
430fn reindent_multiline_inner(s: &str, ignore_first: bool, indent: Option<usize>, ch: char) -> String {
431 let x = s
432 .lines()
433 .skip(usize::from(ignore_first))
434 .filter_map(|l| {
435 if l.is_empty() {
436 None
437 } else {
438 Some(l.char_indices().find(|&(_, x)| x != ch).unwrap_or((l.len(), ch)).0)
440 }
441 })
442 .min()
443 .unwrap_or(0);
444 let indent = indent.unwrap_or(0);
445 s.lines()
446 .enumerate()
447 .map(|(i, l)| {
448 if (ignore_first && i == 0) || l.is_empty() {
449 l.to_owned()
450 } else if x > indent {
451 l.split_at(x - indent).1.to_owned()
452 } else {
453 " ".repeat(indent - x) + l
454 }
455 })
456 .collect::<Vec<String>>()
457 .join("\n")
458}
459
460pub fn snippet<'a>(sess: &impl HasSession, span: Span, default: &'a str) -> Cow<'a, str> {
478 snippet_opt(sess, span).map_or_else(|| Cow::Borrowed(default), From::from)
479}
480
481pub fn snippet_with_applicability<'a>(
488 sess: &impl HasSession,
489 span: Span,
490 default: &'a str,
491 applicability: &mut Applicability,
492) -> Cow<'a, str> {
493 snippet_with_applicability_sess(sess.sess(), span, default, applicability)
494}
495
496fn snippet_with_applicability_sess<'a>(
497 sess: &Session,
498 span: Span,
499 default: &'a str,
500 applicability: &mut Applicability,
501) -> Cow<'a, str> {
502 if *applicability != Applicability::Unspecified && span.from_expansion() {
503 *applicability = Applicability::MaybeIncorrect;
504 }
505 snippet_opt(sess, span).map_or_else(
506 || {
507 if *applicability == Applicability::MachineApplicable {
508 *applicability = Applicability::HasPlaceholders;
509 }
510 Cow::Borrowed(default)
511 },
512 From::from,
513 )
514}
515
516pub fn snippet_opt(sess: &impl HasSession, span: Span) -> Option<String> {
518 sess.sess().source_map().span_to_snippet(span).ok()
519}
520
521pub fn snippet_block(sess: &impl HasSession, span: Span, default: &str, indent_relative_to: Option<Span>) -> String {
556 let snip = snippet(sess, span, default);
557 let indent = indent_relative_to.and_then(|s| indent_of(sess, s));
558 reindent_multiline(&snip, true, indent)
559}
560
561pub fn snippet_block_with_applicability(
564 sess: &impl HasSession,
565 span: Span,
566 default: &str,
567 indent_relative_to: Option<Span>,
568 applicability: &mut Applicability,
569) -> String {
570 let snip = snippet_with_applicability(sess, span, default, applicability);
571 let indent = indent_relative_to.and_then(|s| indent_of(sess, s));
572 reindent_multiline(&snip, true, indent)
573}
574
575pub fn snippet_block_with_context(
576 sess: &impl HasSession,
577 span: Span,
578 outer: SyntaxContext,
579 default: &str,
580 indent_relative_to: Option<Span>,
581 app: &mut Applicability,
582) -> (String, bool) {
583 let (snip, from_macro) = snippet_with_context(sess, span, outer, default, app);
584 let indent = indent_relative_to.and_then(|s| indent_of(sess, s));
585 (reindent_multiline(&snip, true, indent), from_macro)
586}
587
588pub fn snippet_with_context<'a>(
599 sess: &impl HasSession,
600 span: Span,
601 outer: SyntaxContext,
602 default: &'a str,
603 applicability: &mut Applicability,
604) -> (Cow<'a, str>, bool) {
605 snippet_with_context_sess(sess.sess(), span, outer, default, applicability)
606}
607
608fn snippet_with_context_sess<'a>(
609 sess: &Session,
610 span: Span,
611 outer: SyntaxContext,
612 default: &'a str,
613 applicability: &mut Applicability,
614) -> (Cow<'a, str>, bool) {
615 let (span, is_macro_call) = walk_span_to_context(span, outer).map_or_else(
616 || {
617 if *applicability != Applicability::Unspecified {
619 *applicability = Applicability::MaybeIncorrect;
620 }
621 (span, false)
623 },
624 |outer_span| (outer_span, span.ctxt() != outer),
625 );
626
627 (
628 snippet_with_applicability_sess(sess, span, default, applicability),
629 is_macro_call,
630 )
631}
632
633pub fn walk_span_to_context(span: Span, outer: SyntaxContext) -> Option<Span> {
661 let outer_span = hygiene::walk_chain(span, outer);
662 (outer_span.ctxt() == outer).then_some(outer_span)
663}
664
665pub fn trim_span(sm: &SourceMap, span: Span) -> Span {
667 let data = span.data();
668 let sf: &_ = &sm.lookup_source_file(data.lo);
669 let Some(src) = sf.src.as_deref() else {
670 return span;
671 };
672 let Some(snip) = &src.get((data.lo - sf.start_pos).to_usize()..(data.hi - sf.start_pos).to_usize()) else {
673 return span;
674 };
675 let trim_start = snip.len() - snip.trim_start().len();
676 let trim_end = snip.len() - snip.trim_end().len();
677 SpanData {
678 lo: data.lo + BytePos::from_usize(trim_start),
679 hi: data.hi - BytePos::from_usize(trim_end),
680 ctxt: data.ctxt,
681 parent: data.parent,
682 }
683 .span()
684}
685
686pub fn expand_past_previous_comma(sess: &impl HasSession, span: Span) -> Span {
692 let extended = sess.sess().source_map().span_extend_to_prev_char(span, ',', true);
693 extended.with_lo(extended.lo() - BytePos(1))
694}
695
696pub fn str_literal_to_char_literal(
699 sess: &impl HasSession,
700 expr: &Expr<'_>,
701 applicability: &mut Applicability,
702 ascii_only: bool,
703) -> Option<String> {
704 if let ExprKind::Lit(lit) = &expr.kind
705 && let LitKind::Str(r, style) = lit.node
706 && let string = r.as_str()
707 && let len = if ascii_only {
708 string.len()
709 } else {
710 string.chars().count()
711 }
712 && len == 1
713 {
714 let snip = snippet_with_applicability(sess, expr.span, string, applicability);
715 let ch = if let StrStyle::Raw(nhash) = style {
716 let nhash = nhash as usize;
717 &snip[(nhash + 2)..(snip.len() - 1 - nhash)]
719 } else {
720 &snip[1..(snip.len() - 1)]
722 };
723
724 let hint = format!(
725 "'{}'",
726 match ch {
727 "'" => "\\'",
728 r"\" => "\\\\",
729 "\\\"" => "\"", _ => ch,
731 }
732 );
733
734 Some(hint)
735 } else {
736 None
737 }
738}
739
740#[cfg(test)]
741mod test {
742 use super::reindent_multiline;
743
744 #[test]
745 fn test_reindent_multiline_single_line() {
746 assert_eq!("", reindent_multiline("", false, None));
747 assert_eq!("...", reindent_multiline("...", false, None));
748 assert_eq!("...", reindent_multiline(" ...", false, None));
749 assert_eq!("...", reindent_multiline("\t...", false, None));
750 assert_eq!("...", reindent_multiline("\t\t...", false, None));
751 }
752
753 #[test]
754 #[rustfmt::skip]
755 fn test_reindent_multiline_block() {
756 assert_eq!("\
757 if x {
758 y
759 } else {
760 z
761 }", reindent_multiline(" if x {
762 y
763 } else {
764 z
765 }", false, None));
766 assert_eq!("\
767 if x {
768 \ty
769 } else {
770 \tz
771 }", reindent_multiline(" if x {
772 \ty
773 } else {
774 \tz
775 }", false, None));
776 }
777
778 #[test]
779 #[rustfmt::skip]
780 fn test_reindent_multiline_empty_line() {
781 assert_eq!("\
782 if x {
783 y
784
785 } else {
786 z
787 }", reindent_multiline(" if x {
788 y
789
790 } else {
791 z
792 }", false, None));
793 }
794
795 #[test]
796 #[rustfmt::skip]
797 fn test_reindent_multiline_lines_deeper() {
798 assert_eq!("\
799 if x {
800 y
801 } else {
802 z
803 }", reindent_multiline("\
804 if x {
805 y
806 } else {
807 z
808 }", true, Some(8)));
809 }
810}