clippy_utils/
source.rs

1//! Utils for extracting, inspecting or transforming source code
2
3#![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
47/// Conversion of a value into the range portion of a `Span`.
48pub 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
68/// Conversion of a value into a `Span`
69pub 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    /// Attempts to get a handle to the source text. Returns `None` if either the span is malformed,
100    /// or the source text is not accessible.
101    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    /// Gets the source file, and range in the file, of the given span. Returns `None` if the span
106    /// extends through multiple files, or is malformed.
107    fn get_source_range(self, cx: &impl HasSession) -> Option<SourceFileRange> {
108        get_source_range(cx.sess().source_map(), self.into_range())
109    }
110
111    /// Calls the given function with the source text referenced and returns the value. Returns
112    /// `None` if the source text cannot be retrieved.
113    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    /// Checks if the referenced source text satisfies the given predicate. Returns `false` if the
118    /// source text cannot be retrieved.
119    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    /// Calls the given function with the both the text of the source file and the referenced range,
124    /// and returns the value. Returns `None` if the source text cannot be retrieved.
125    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    /// Calls the given function with the both the text of the source file and the referenced range,
134    /// and creates a new span with the returned range. Returns `None` if the source text cannot be
135    /// retrieved, or no result is returned.
136    ///
137    /// The new range must reside within the same source file.
138    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    /// Extends the range to include all preceding whitespace characters.
148    ///
149    /// The range will not be expanded if it would cross a line boundary, the line the range would
150    /// be extended to ends with a line comment and the text after the range contains a
151    /// non-whitespace character on the same line. e.g.
152    ///
153    /// ```ignore
154    /// ( // Some comment
155    /// foo)
156    /// ```
157    ///
158    /// When the range points to `foo`, suggesting to remove the range after it's been extended will
159    /// cause the `)` to be placed inside the line comment as `( // Some comment)`.
160    fn with_leading_whitespace(self, cx: &impl HasSession) -> Range<BytePos> {
161        with_leading_whitespace(cx.sess().source_map(), self.into_range())
162    }
163
164    /// Trims the leading whitespace from the range.
165    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
171/// Handle to a range of text in a source file.
172pub struct SourceText(SourceFileRange);
173impl SourceText {
174    /// Takes ownership of the source file handle if the source text is accessible.
175    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    /// Gets the source text.
184    pub fn as_str(&self) -> &str {
185        self.0.as_str().unwrap()
186    }
187
188    /// Converts this into an owned string.
189    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        // Will give the wrong result on text like `" // "` where the first quote ends a string
285        // started earlier. The only workaround is to lex the whole file which we don't really want
286        // to do.
287        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    /// Attempts to get the text from the source file. This can fail if the source text isn't
343    /// loaded.
344    pub fn as_str(&self) -> Option<&str> {
345        (self.sf.src.as_ref().map(|src| src.as_str()))
346            .or_else(|| self.sf.external_src.get()?.get_source())
347            .and_then(|x| x.get(self.range.clone()))
348    }
349}
350
351/// Like `snippet_block`, but add braces if the expr is not an `ExprKind::Block` with no label.
352pub fn expr_block(
353    sess: &impl HasSession,
354    expr: &Expr<'_>,
355    outer: SyntaxContext,
356    default: &str,
357    indent_relative_to: Option<Span>,
358    app: &mut Applicability,
359) -> String {
360    let (code, from_macro) = snippet_block_with_context(sess, expr.span, outer, default, indent_relative_to, app);
361    if !from_macro
362        && let ExprKind::Block(block, None) = expr.kind
363        && block.rules != BlockCheckMode::UnsafeBlock(UnsafeSource::UserProvided)
364    {
365        code
366    } else {
367        // FIXME: add extra indent for the unsafe blocks:
368        //     original code:   unsafe { ... }
369        //     result code:     { unsafe { ... } }
370        //     desired code:    {\n  unsafe { ... }\n}
371        format!("{{ {code} }}")
372    }
373}
374
375/// Returns a new Span that extends the original Span to the first non-whitespace char of the first
376/// line.
377///
378/// ```rust,ignore
379///     let x = ();
380/// //          ^^
381/// // will be converted to
382///     let x = ();
383/// //  ^^^^^^^^^^
384/// ```
385pub fn first_line_of_span(sess: &impl HasSession, span: Span) -> Span {
386    first_char_in_first_line(sess, span).map_or(span, |first_char_pos| span.with_lo(first_char_pos))
387}
388
389fn first_char_in_first_line(sess: &impl HasSession, span: Span) -> Option<BytePos> {
390    let line_span = line_span(sess, span);
391    snippet_opt(sess, line_span).and_then(|snip| {
392        snip.find(|c: char| !c.is_whitespace())
393            .map(|pos| line_span.lo() + BytePos::from_usize(pos))
394    })
395}
396
397/// Extends the span to the beginning of the spans line, incl. whitespaces.
398///
399/// ```no_run
400///        let x = ();
401/// //             ^^
402/// // will be converted to
403///        let x = ();
404/// // ^^^^^^^^^^^^^^
405/// ```
406fn line_span(sess: &impl HasSession, span: Span) -> Span {
407    let span = original_sp(span, DUMMY_SP);
408    let SourceFileAndLine { sf, line } = sess.sess().source_map().lookup_line(span.lo()).unwrap();
409    let line_start = sf.lines()[line];
410    let line_start = sf.absolute_position(line_start);
411    span.with_lo(line_start)
412}
413
414/// Returns the indentation of the line of a span
415///
416/// ```rust,ignore
417/// let x = ();
418/// //      ^^ -- will return 0
419///     let x = ();
420/// //          ^^ -- will return 4
421/// ```
422pub fn indent_of(sess: &impl HasSession, span: Span) -> Option<usize> {
423    snippet_opt(sess, line_span(sess, span)).and_then(|snip| snip.find(|c: char| !c.is_whitespace()))
424}
425
426/// Gets a snippet of the indentation of the line of a span
427pub fn snippet_indent(sess: &impl HasSession, span: Span) -> Option<String> {
428    snippet_opt(sess, line_span(sess, span)).map(|mut s| {
429        let len = s.len() - s.trim_start().len();
430        s.truncate(len);
431        s
432    })
433}
434
435// If the snippet is empty, it's an attribute that was inserted during macro
436// expansion and we want to ignore those, because they could come from external
437// sources that the user has no control over.
438// For some reason these attributes don't have any expansion info on them, so
439// we have to check it this way until there is a better way.
440pub fn is_present_in_source(sess: &impl HasSession, span: Span) -> bool {
441    if let Some(snippet) = snippet_opt(sess, span)
442        && snippet.is_empty()
443    {
444        return false;
445    }
446    true
447}
448
449/// Returns the position just before rarrow
450///
451/// ```rust,ignore
452/// fn into(self) -> () {}
453///              ^
454/// // in case of unformatted code
455/// fn into2(self)-> () {}
456///               ^
457/// fn into3(self)   -> () {}
458///               ^
459/// ```
460pub fn position_before_rarrow(s: &str) -> Option<usize> {
461    s.rfind("->").map(|rpos| {
462        let mut rpos = rpos;
463        let chars: Vec<char> = s.chars().collect();
464        while rpos > 1 {
465            if let Some(c) = chars.get(rpos - 1)
466                && c.is_whitespace()
467            {
468                rpos -= 1;
469                continue;
470            }
471            break;
472        }
473        rpos
474    })
475}
476
477/// Reindent a multiline string with possibility of ignoring the first line.
478pub fn reindent_multiline(s: &str, ignore_first: bool, indent: Option<usize>) -> String {
479    let s_space = reindent_multiline_inner(s, ignore_first, indent, ' ');
480    let s_tab = reindent_multiline_inner(&s_space, ignore_first, indent, '\t');
481    reindent_multiline_inner(&s_tab, ignore_first, indent, ' ')
482}
483
484fn reindent_multiline_inner(s: &str, ignore_first: bool, indent: Option<usize>, ch: char) -> String {
485    let x = s
486        .lines()
487        .skip(usize::from(ignore_first))
488        .filter_map(|l| {
489            if l.is_empty() {
490                None
491            } else {
492                // ignore empty lines
493                Some(l.char_indices().find(|&(_, x)| x != ch).unwrap_or((l.len(), ch)).0)
494            }
495        })
496        .min()
497        .unwrap_or(0);
498    let indent = indent.unwrap_or(0);
499    s.lines()
500        .enumerate()
501        .map(|(i, l)| {
502            if (ignore_first && i == 0) || l.is_empty() {
503                l.to_owned()
504            } else if x > indent {
505                l.split_at(x - indent).1.to_owned()
506            } else {
507                " ".repeat(indent - x) + l
508            }
509        })
510        .collect::<Vec<String>>()
511        .join("\n")
512}
513
514/// Converts a span to a code snippet if available, otherwise returns the default.
515///
516/// This is useful if you want to provide suggestions for your lint or more generally, if you want
517/// to convert a given `Span` to a `str`. To create suggestions consider using
518/// [`snippet_with_applicability`] to ensure that the applicability stays correct.
519///
520/// # Example
521/// ```rust,ignore
522/// // Given two spans one for `value` and one for the `init` expression.
523/// let value = Vec::new();
524/// //  ^^^^^   ^^^^^^^^^^
525/// //  span1   span2
526///
527/// // The snipped call would return the corresponding code snippet
528/// snippet(cx, span1, "..") // -> "value"
529/// snippet(cx, span2, "..") // -> "Vec::new()"
530/// ```
531pub fn snippet<'a>(sess: &impl HasSession, span: Span, default: &'a str) -> Cow<'a, str> {
532    snippet_opt(sess, span).map_or_else(|| Cow::Borrowed(default), From::from)
533}
534
535/// Same as [`snippet`], but it adapts the applicability level by following rules:
536///
537/// - Applicability level `Unspecified` will never be changed.
538/// - If the span is inside a macro, change the applicability level to `MaybeIncorrect`.
539/// - If the default value is used and the applicability level is `MachineApplicable`, change it to
540///   `HasPlaceholders`
541pub fn snippet_with_applicability<'a>(
542    sess: &impl HasSession,
543    span: Span,
544    default: &'a str,
545    applicability: &mut Applicability,
546) -> Cow<'a, str> {
547    snippet_with_applicability_sess(sess.sess(), span, default, applicability)
548}
549
550fn snippet_with_applicability_sess<'a>(
551    sess: &Session,
552    span: Span,
553    default: &'a str,
554    applicability: &mut Applicability,
555) -> Cow<'a, str> {
556    if *applicability != Applicability::Unspecified && span.from_expansion() {
557        *applicability = Applicability::MaybeIncorrect;
558    }
559    snippet_opt(sess, span).map_or_else(
560        || {
561            if *applicability == Applicability::MachineApplicable {
562                *applicability = Applicability::HasPlaceholders;
563            }
564            Cow::Borrowed(default)
565        },
566        From::from,
567    )
568}
569
570/// Converts a span to a code snippet. Returns `None` if not available.
571pub fn snippet_opt(sess: &impl HasSession, span: Span) -> Option<String> {
572    sess.sess().source_map().span_to_snippet(span).ok()
573}
574
575/// Converts a span (from a block) to a code snippet if available, otherwise use default.
576///
577/// This trims the code of indentation, except for the first line. Use it for blocks or block-like
578/// things which need to be printed as such.
579///
580/// The `indent_relative_to` arg can be used, to provide a span, where the indentation of the
581/// resulting snippet of the given span.
582///
583/// # Example
584///
585/// ```rust,ignore
586/// snippet_block(cx, block.span, "..", None)
587/// // where, `block` is the block of the if expr
588///     if x {
589///         y;
590///     }
591/// // will return the snippet
592/// {
593///     y;
594/// }
595/// ```
596///
597/// ```rust,ignore
598/// snippet_block(cx, block.span, "..", Some(if_expr.span))
599/// // where, `block` is the block of the if expr
600///     if x {
601///         y;
602///     }
603/// // will return the snippet
604/// {
605///         y;
606///     } // aligned with `if`
607/// ```
608/// Note that the first line of the snippet always has 0 indentation.
609pub fn snippet_block(sess: &impl HasSession, span: Span, default: &str, indent_relative_to: Option<Span>) -> String {
610    let snip = snippet(sess, span, default);
611    let indent = indent_relative_to.and_then(|s| indent_of(sess, s));
612    reindent_multiline(&snip, true, indent)
613}
614
615/// Same as `snippet_block`, but adapts the applicability level by the rules of
616/// `snippet_with_applicability`.
617pub fn snippet_block_with_applicability(
618    sess: &impl HasSession,
619    span: Span,
620    default: &str,
621    indent_relative_to: Option<Span>,
622    applicability: &mut Applicability,
623) -> String {
624    let snip = snippet_with_applicability(sess, span, default, applicability);
625    let indent = indent_relative_to.and_then(|s| indent_of(sess, s));
626    reindent_multiline(&snip, true, indent)
627}
628
629pub fn snippet_block_with_context(
630    sess: &impl HasSession,
631    span: Span,
632    outer: SyntaxContext,
633    default: &str,
634    indent_relative_to: Option<Span>,
635    app: &mut Applicability,
636) -> (String, bool) {
637    let (snip, from_macro) = snippet_with_context(sess, span, outer, default, app);
638    let indent = indent_relative_to.and_then(|s| indent_of(sess, s));
639    (reindent_multiline(&snip, true, indent), from_macro)
640}
641
642/// Same as `snippet_with_applicability`, but first walks the span up to the given context.
643///
644/// This will result in the macro call, rather than the expansion, if the span is from a child
645/// context. If the span is not from a child context, it will be used directly instead.
646///
647/// e.g. Given the expression `&vec![]`, getting a snippet from the span for `vec![]` as a HIR node
648/// would result in `box []`. If given the context of the address of expression, this function will
649/// correctly get a snippet of `vec![]`.
650///
651/// This will also return whether or not the snippet is a macro call.
652pub fn snippet_with_context<'a>(
653    sess: &impl HasSession,
654    span: Span,
655    outer: SyntaxContext,
656    default: &'a str,
657    applicability: &mut Applicability,
658) -> (Cow<'a, str>, bool) {
659    snippet_with_context_sess(sess.sess(), span, outer, default, applicability)
660}
661
662fn snippet_with_context_sess<'a>(
663    sess: &Session,
664    span: Span,
665    outer: SyntaxContext,
666    default: &'a str,
667    applicability: &mut Applicability,
668) -> (Cow<'a, str>, bool) {
669    let (span, is_macro_call) = walk_span_to_context(span, outer).map_or_else(
670        || {
671            // The span is from a macro argument, and the outer context is the macro using the argument
672            if *applicability != Applicability::Unspecified {
673                *applicability = Applicability::MaybeIncorrect;
674            }
675            // TODO: get the argument span.
676            (span, false)
677        },
678        |outer_span| (outer_span, span.ctxt() != outer),
679    );
680
681    (
682        snippet_with_applicability_sess(sess, span, default, applicability),
683        is_macro_call,
684    )
685}
686
687/// Walks the span up to the target context, thereby returning the macro call site if the span is
688/// inside a macro expansion, or the original span if it is not.
689///
690/// Note this will return `None` in the case of the span being in a macro expansion, but the target
691/// context is from expanding a macro argument.
692///
693/// Given the following
694///
695/// ```rust,ignore
696/// macro_rules! m { ($e:expr) => { f($e) }; }
697/// g(m!(0))
698/// ```
699///
700/// If called with a span of the call to `f` and a context of the call to `g` this will return a
701/// span containing `m!(0)`. However, if called with a span of the literal `0` this will give a span
702/// containing `0` as the context is the same as the outer context.
703///
704/// This will traverse through multiple macro calls. Given the following:
705///
706/// ```rust,ignore
707/// macro_rules! m { ($e:expr) => { n!($e, 0) }; }
708/// macro_rules! n { ($e:expr, $f:expr) => { f($e, $f) }; }
709/// g(m!(0))
710/// ```
711///
712/// If called with a span of the call to `f` and a context of the call to `g` this will return a
713/// span containing `m!(0)`.
714pub fn walk_span_to_context(span: Span, outer: SyntaxContext) -> Option<Span> {
715    let outer_span = hygiene::walk_chain(span, outer);
716    (outer_span.ctxt() == outer).then_some(outer_span)
717}
718
719/// Trims the whitespace from the start and the end of the span.
720pub fn trim_span(sm: &SourceMap, span: Span) -> Span {
721    let data = span.data();
722    let sf: &_ = &sm.lookup_source_file(data.lo);
723    let Some(src) = sf.src.as_deref() else {
724        return span;
725    };
726    let Some(snip) = &src.get((data.lo - sf.start_pos).to_usize()..(data.hi - sf.start_pos).to_usize()) else {
727        return span;
728    };
729    let trim_start = snip.len() - snip.trim_start().len();
730    let trim_end = snip.len() - snip.trim_end().len();
731    SpanData {
732        lo: data.lo + BytePos::from_usize(trim_start),
733        hi: data.hi - BytePos::from_usize(trim_end),
734        ctxt: data.ctxt,
735        parent: data.parent,
736    }
737    .span()
738}
739
740/// Expand a span to include a preceding comma
741/// ```rust,ignore
742/// writeln!(o, "")   ->   writeln!(o, "")
743///             ^^                   ^^^^
744/// ```
745pub fn expand_past_previous_comma(sess: &impl HasSession, span: Span) -> Span {
746    let extended = sess.sess().source_map().span_extend_to_prev_char(span, ',', true);
747    extended.with_lo(extended.lo() - BytePos(1))
748}
749
750/// Converts `expr` to a `char` literal if it's a `str` literal containing a single
751/// character (or a single byte with `ascii_only`)
752pub fn str_literal_to_char_literal(
753    sess: &impl HasSession,
754    expr: &Expr<'_>,
755    applicability: &mut Applicability,
756    ascii_only: bool,
757) -> Option<String> {
758    if let ExprKind::Lit(lit) = &expr.kind
759        && let LitKind::Str(r, style) = lit.node
760        && let string = r.as_str()
761        && let len = if ascii_only {
762            string.len()
763        } else {
764            string.chars().count()
765        }
766        && len == 1
767    {
768        let snip = snippet_with_applicability(sess, expr.span, string, applicability);
769        let ch = if let StrStyle::Raw(nhash) = style {
770            let nhash = nhash as usize;
771            // for raw string: r##"a"##
772            &snip[(nhash + 2)..(snip.len() - 1 - nhash)]
773        } else {
774            // for regular string: "a"
775            &snip[1..(snip.len() - 1)]
776        };
777
778        let hint = format!(
779            "'{}'",
780            match ch {
781                "'" => "\\'",
782                r"\" => "\\\\",
783                "\\\"" => "\"", // no need to escape `"` in `'"'`
784                _ => ch,
785            }
786        );
787
788        Some(hint)
789    } else {
790        None
791    }
792}
793
794#[cfg(test)]
795mod test {
796    use super::reindent_multiline;
797
798    #[test]
799    fn test_reindent_multiline_single_line() {
800        assert_eq!("", reindent_multiline("", false, None));
801        assert_eq!("...", reindent_multiline("...", false, None));
802        assert_eq!("...", reindent_multiline("    ...", false, None));
803        assert_eq!("...", reindent_multiline("\t...", false, None));
804        assert_eq!("...", reindent_multiline("\t\t...", false, None));
805    }
806
807    #[test]
808    #[rustfmt::skip]
809    fn test_reindent_multiline_block() {
810        assert_eq!("\
811    if x {
812        y
813    } else {
814        z
815    }", reindent_multiline("    if x {
816            y
817        } else {
818            z
819        }", false, None));
820        assert_eq!("\
821    if x {
822    \ty
823    } else {
824    \tz
825    }", reindent_multiline("    if x {
826        \ty
827        } else {
828        \tz
829        }", false, None));
830    }
831
832    #[test]
833    #[rustfmt::skip]
834    fn test_reindent_multiline_empty_line() {
835        assert_eq!("\
836    if x {
837        y
838
839    } else {
840        z
841    }", reindent_multiline("    if x {
842            y
843
844        } else {
845            z
846        }", false, None));
847    }
848
849    #[test]
850    #[rustfmt::skip]
851    fn test_reindent_multiline_lines_deeper() {
852        assert_eq!("\
853        if x {
854            y
855        } else {
856            z
857        }", reindent_multiline("\
858    if x {
859        y
860    } else {
861        z
862    }", true, Some(8)));
863    }
864}