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_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
46/// Conversion of a value into the range portion of a `Span`.
47pub 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
67/// Conversion of a value into a `Span`
68pub 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    /// Attempts to get a handle to the source text. Returns `None` if either the span is malformed,
99    /// or the source text is not accessible.
100    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    /// Gets the source file, and range in the file, of the given span. Returns `None` if the span
105    /// extends through multiple files, or is malformed.
106    fn get_source_range(self, cx: &impl HasSession) -> Option<SourceFileRange> {
107        get_source_range(cx.sess().source_map(), self.into_range())
108    }
109
110    /// Calls the given function with the source text referenced and returns the value. Returns
111    /// `None` if the source text cannot be retrieved.
112    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    /// Checks if the referenced source text satisfies the given predicate. Returns `false` if the
117    /// source text cannot be retrieved.
118    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    /// Calls the given function with the both the text of the source file and the referenced range,
123    /// and returns the value. Returns `None` if the source text cannot be retrieved.
124    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    /// Calls the given function with the both the text of the source file and the referenced range,
133    /// and creates a new span with the returned range. Returns `None` if the source text cannot be
134    /// retrieved, or no result is returned.
135    ///
136    /// The new range must reside within the same source file.
137    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    /// Extends the range to include all preceding whitespace characters.
146    fn with_leading_whitespace(self, cx: &impl HasSession) -> Range<BytePos> {
147        with_leading_whitespace(cx.sess().source_map(), self.into_range())
148    }
149
150    /// Trims the leading whitespace from the range.
151    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
157/// Handle to a range of text in a source file.
158pub struct SourceText(SourceFileRange);
159impl SourceText {
160    /// Takes ownership of the source file handle if the source text is accessible.
161    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    /// Gets the source text.
170    pub fn as_str(&self) -> &str {
171        self.0.as_str().unwrap()
172    }
173
174    /// Converts this into an owned string.
175    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    /// Attempts to get the text from the source file. This can fail if the source text isn't
286    /// loaded.
287    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
297/// Like `snippet_block`, but add braces if the expr is not an `ExprKind::Block` with no label.
298pub 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        // FIXME: add extra indent for the unsafe blocks:
314        //     original code:   unsafe { ... }
315        //     result code:     { unsafe { ... } }
316        //     desired code:    {\n  unsafe { ... }\n}
317        format!("{{ {code} }}")
318    }
319}
320
321/// Returns a new Span that extends the original Span to the first non-whitespace char of the first
322/// line.
323///
324/// ```rust,ignore
325///     let x = ();
326/// //          ^^
327/// // will be converted to
328///     let x = ();
329/// //  ^^^^^^^^^^
330/// ```
331pub 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
343/// Extends the span to the beginning of the spans line, incl. whitespaces.
344///
345/// ```no_run
346///        let x = ();
347/// //             ^^
348/// // will be converted to
349///        let x = ();
350/// // ^^^^^^^^^^^^^^
351/// ```
352fn 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
360/// Returns the indentation of the line of a span
361///
362/// ```rust,ignore
363/// let x = ();
364/// //      ^^ -- will return 0
365///     let x = ();
366/// //          ^^ -- will return 4
367/// ```
368pub 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
372/// Gets a snippet of the indentation of the line of a span
373pub 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
381// If the snippet is empty, it's an attribute that was inserted during macro
382// expansion and we want to ignore those, because they could come from external
383// sources that the user has no control over.
384// For some reason these attributes don't have any expansion info on them, so
385// we have to check it this way until there is a better way.
386pub 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
395/// Returns the position just before rarrow
396///
397/// ```rust,ignore
398/// fn into(self) -> () {}
399///              ^
400/// // in case of unformatted code
401/// fn into2(self)-> () {}
402///               ^
403/// fn into3(self)   -> () {}
404///               ^
405/// ```
406pub 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
423/// Reindent a multiline string with possibility of ignoring the first line.
424pub 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                // ignore empty lines
439                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
460/// Converts a span to a code snippet if available, otherwise returns the default.
461///
462/// This is useful if you want to provide suggestions for your lint or more generally, if you want
463/// to convert a given `Span` to a `str`. To create suggestions consider using
464/// [`snippet_with_applicability`] to ensure that the applicability stays correct.
465///
466/// # Example
467/// ```rust,ignore
468/// // Given two spans one for `value` and one for the `init` expression.
469/// let value = Vec::new();
470/// //  ^^^^^   ^^^^^^^^^^
471/// //  span1   span2
472///
473/// // The snipped call would return the corresponding code snippet
474/// snippet(cx, span1, "..") // -> "value"
475/// snippet(cx, span2, "..") // -> "Vec::new()"
476/// ```
477pub 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
481/// Same as [`snippet`], but it adapts the applicability level by following rules:
482///
483/// - Applicability level `Unspecified` will never be changed.
484/// - If the span is inside a macro, change the applicability level to `MaybeIncorrect`.
485/// - If the default value is used and the applicability level is `MachineApplicable`, change it to
486///   `HasPlaceholders`
487pub 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
516/// Converts a span to a code snippet. Returns `None` if not available.
517pub fn snippet_opt(sess: &impl HasSession, span: Span) -> Option<String> {
518    sess.sess().source_map().span_to_snippet(span).ok()
519}
520
521/// Converts a span (from a block) to a code snippet if available, otherwise use default.
522///
523/// This trims the code of indentation, except for the first line. Use it for blocks or block-like
524/// things which need to be printed as such.
525///
526/// The `indent_relative_to` arg can be used, to provide a span, where the indentation of the
527/// resulting snippet of the given span.
528///
529/// # Example
530///
531/// ```rust,ignore
532/// snippet_block(cx, block.span, "..", None)
533/// // where, `block` is the block of the if expr
534///     if x {
535///         y;
536///     }
537/// // will return the snippet
538/// {
539///     y;
540/// }
541/// ```
542///
543/// ```rust,ignore
544/// snippet_block(cx, block.span, "..", Some(if_expr.span))
545/// // where, `block` is the block of the if expr
546///     if x {
547///         y;
548///     }
549/// // will return the snippet
550/// {
551///         y;
552///     } // aligned with `if`
553/// ```
554/// Note that the first line of the snippet always has 0 indentation.
555pub 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
561/// Same as `snippet_block`, but adapts the applicability level by the rules of
562/// `snippet_with_applicability`.
563pub 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
588/// Same as `snippet_with_applicability`, but first walks the span up to the given context.
589///
590/// This will result in the macro call, rather than the expansion, if the span is from a child
591/// context. If the span is not from a child context, it will be used directly instead.
592///
593/// e.g. Given the expression `&vec![]`, getting a snippet from the span for `vec![]` as a HIR node
594/// would result in `box []`. If given the context of the address of expression, this function will
595/// correctly get a snippet of `vec![]`.
596///
597/// This will also return whether or not the snippet is a macro call.
598pub 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            // The span is from a macro argument, and the outer context is the macro using the argument
618            if *applicability != Applicability::Unspecified {
619                *applicability = Applicability::MaybeIncorrect;
620            }
621            // TODO: get the argument span.
622            (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
633/// Walks the span up to the target context, thereby returning the macro call site if the span is
634/// inside a macro expansion, or the original span if it is not.
635///
636/// Note this will return `None` in the case of the span being in a macro expansion, but the target
637/// context is from expanding a macro argument.
638///
639/// Given the following
640///
641/// ```rust,ignore
642/// macro_rules! m { ($e:expr) => { f($e) }; }
643/// g(m!(0))
644/// ```
645///
646/// If called with a span of the call to `f` and a context of the call to `g` this will return a
647/// span containing `m!(0)`. However, if called with a span of the literal `0` this will give a span
648/// containing `0` as the context is the same as the outer context.
649///
650/// This will traverse through multiple macro calls. Given the following:
651///
652/// ```rust,ignore
653/// macro_rules! m { ($e:expr) => { n!($e, 0) }; }
654/// macro_rules! n { ($e:expr, $f:expr) => { f($e, $f) }; }
655/// g(m!(0))
656/// ```
657///
658/// If called with a span of the call to `f` and a context of the call to `g` this will return a
659/// span containing `m!(0)`.
660pub 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
665/// Trims the whitespace from the start and the end of the span.
666pub 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
686/// Expand a span to include a preceding comma
687/// ```rust,ignore
688/// writeln!(o, "")   ->   writeln!(o, "")
689///             ^^                   ^^^^
690/// ```
691pub 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
696/// Converts `expr` to a `char` literal if it's a `str` literal containing a single
697/// character (or a single byte with `ascii_only`)
698pub 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            // for raw string: r##"a"##
718            &snip[(nhash + 2)..(snip.len() - 1 - nhash)]
719        } else {
720            // for regular string: "a"
721            &snip[1..(snip.len() - 1)]
722        };
723
724        let hint = format!(
725            "'{}'",
726            match ch {
727                "'" => "\\'",
728                r"\" => "\\\\",
729                "\\\"" => "\"", // no need to escape `"` in `'"'`
730                _ => 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}