]> git.lizzy.rs Git - rust.git/blob - src/utils.rs
Merge pull request #3466 from topecongiro/discard-error-to-sink
[rust.git] / src / utils.rs
1 use std::borrow::Cow;
2
3 use bytecount;
4
5 use rustc_target::spec::abi;
6 use syntax::ast::{
7     self, Attribute, CrateSugar, MetaItem, MetaItemKind, NestedMetaItem, NestedMetaItemKind,
8     NodeId, Path, Visibility, VisibilityKind,
9 };
10 use syntax::ptr;
11 use syntax::source_map::{BytePos, Span, NO_EXPANSION};
12 use syntax_pos::Mark;
13 use unicode_width::UnicodeWidthStr;
14
15 use crate::comment::{filter_normal_code, CharClasses, FullCodeCharKind, LineClasses};
16 use crate::config::{Config, Version};
17 use crate::rewrite::RewriteContext;
18 use crate::shape::{Indent, Shape};
19
20 pub const DEPR_SKIP_ANNOTATION: &str = "rustfmt_skip";
21 pub const SKIP_ANNOTATION: &str = "rustfmt::skip";
22
23 pub fn rewrite_ident<'a>(context: &'a RewriteContext<'_>, ident: ast::Ident) -> &'a str {
24     context.snippet(ident.span)
25 }
26
27 // Computes the length of a string's last line, minus offset.
28 pub fn extra_offset(text: &str, shape: Shape) -> usize {
29     match text.rfind('\n') {
30         // 1 for newline character
31         Some(idx) => text.len().saturating_sub(idx + 1 + shape.used_width()),
32         None => text.len(),
33     }
34 }
35
36 pub fn is_same_visibility(a: &Visibility, b: &Visibility) -> bool {
37     match (&a.node, &b.node) {
38         (
39             VisibilityKind::Restricted { path: p, .. },
40             VisibilityKind::Restricted { path: q, .. },
41         ) => p.to_string() == q.to_string(),
42         (VisibilityKind::Public, VisibilityKind::Public)
43         | (VisibilityKind::Inherited, VisibilityKind::Inherited)
44         | (
45             VisibilityKind::Crate(CrateSugar::PubCrate),
46             VisibilityKind::Crate(CrateSugar::PubCrate),
47         )
48         | (
49             VisibilityKind::Crate(CrateSugar::JustCrate),
50             VisibilityKind::Crate(CrateSugar::JustCrate),
51         ) => true,
52         _ => false,
53     }
54 }
55
56 // Uses Cow to avoid allocating in the common cases.
57 pub fn format_visibility(context: &RewriteContext<'_>, vis: &Visibility) -> Cow<'static, str> {
58     match vis.node {
59         VisibilityKind::Public => Cow::from("pub "),
60         VisibilityKind::Inherited => Cow::from(""),
61         VisibilityKind::Crate(CrateSugar::PubCrate) => Cow::from("pub(crate) "),
62         VisibilityKind::Crate(CrateSugar::JustCrate) => Cow::from("crate "),
63         VisibilityKind::Restricted { ref path, .. } => {
64             let Path { ref segments, .. } = **path;
65             let mut segments_iter = segments.iter().map(|seg| rewrite_ident(context, seg.ident));
66             if path.is_global() {
67                 segments_iter
68                     .next()
69                     .expect("Non-global path in pub(restricted)?");
70             }
71             let is_keyword = |s: &str| s == "self" || s == "super";
72             let path = segments_iter.collect::<Vec<_>>().join("::");
73             let in_str = if is_keyword(&path) { "" } else { "in " };
74
75             Cow::from(format!("pub({}{}) ", in_str, path))
76         }
77     }
78 }
79
80 #[inline]
81 pub fn format_async(is_async: ast::IsAsync) -> &'static str {
82     match is_async {
83         ast::IsAsync::Async { .. } => "async ",
84         ast::IsAsync::NotAsync => "",
85     }
86 }
87
88 #[inline]
89 pub fn format_constness(constness: ast::Constness) -> &'static str {
90     match constness {
91         ast::Constness::Const => "const ",
92         ast::Constness::NotConst => "",
93     }
94 }
95
96 #[inline]
97 pub fn format_defaultness(defaultness: ast::Defaultness) -> &'static str {
98     match defaultness {
99         ast::Defaultness::Default => "default ",
100         ast::Defaultness::Final => "",
101     }
102 }
103
104 #[inline]
105 pub fn format_unsafety(unsafety: ast::Unsafety) -> &'static str {
106     match unsafety {
107         ast::Unsafety::Unsafe => "unsafe ",
108         ast::Unsafety::Normal => "",
109     }
110 }
111
112 #[inline]
113 pub fn format_auto(is_auto: ast::IsAuto) -> &'static str {
114     match is_auto {
115         ast::IsAuto::Yes => "auto ",
116         ast::IsAuto::No => "",
117     }
118 }
119
120 #[inline]
121 pub fn format_mutability(mutability: ast::Mutability) -> &'static str {
122     match mutability {
123         ast::Mutability::Mutable => "mut ",
124         ast::Mutability::Immutable => "",
125     }
126 }
127
128 #[inline]
129 pub fn format_abi(abi: abi::Abi, explicit_abi: bool, is_mod: bool) -> Cow<'static, str> {
130     if abi == abi::Abi::Rust && !is_mod {
131         Cow::from("")
132     } else if abi == abi::Abi::C && !explicit_abi {
133         Cow::from("extern ")
134     } else {
135         Cow::from(format!("extern {} ", abi))
136     }
137 }
138
139 #[inline]
140 // Transform `Vec<syntax::ptr::P<T>>` into `Vec<&T>`
141 pub fn ptr_vec_to_ref_vec<T>(vec: &[ptr::P<T>]) -> Vec<&T> {
142     vec.iter().map(|x| &**x).collect::<Vec<_>>()
143 }
144
145 #[inline]
146 pub fn filter_attributes(attrs: &[ast::Attribute], style: ast::AttrStyle) -> Vec<ast::Attribute> {
147     attrs
148         .iter()
149         .filter(|a| a.style == style)
150         .cloned()
151         .collect::<Vec<_>>()
152 }
153
154 #[inline]
155 pub fn inner_attributes(attrs: &[ast::Attribute]) -> Vec<ast::Attribute> {
156     filter_attributes(attrs, ast::AttrStyle::Inner)
157 }
158
159 #[inline]
160 pub fn outer_attributes(attrs: &[ast::Attribute]) -> Vec<ast::Attribute> {
161     filter_attributes(attrs, ast::AttrStyle::Outer)
162 }
163
164 #[inline]
165 pub fn is_single_line(s: &str) -> bool {
166     s.chars().find(|&c| c == '\n').is_none()
167 }
168
169 #[inline]
170 pub fn first_line_contains_single_line_comment(s: &str) -> bool {
171     s.lines().next().map_or(false, |l| l.contains("//"))
172 }
173
174 #[inline]
175 pub fn last_line_contains_single_line_comment(s: &str) -> bool {
176     s.lines().last().map_or(false, |l| l.contains("//"))
177 }
178
179 #[inline]
180 pub fn is_attributes_extendable(attrs_str: &str) -> bool {
181     !attrs_str.contains('\n') && !last_line_contains_single_line_comment(attrs_str)
182 }
183
184 // The width of the first line in s.
185 #[inline]
186 pub fn first_line_width(s: &str) -> usize {
187     unicode_str_width(s.splitn(2, '\n').next().unwrap_or(""))
188 }
189
190 // The width of the last line in s.
191 #[inline]
192 pub fn last_line_width(s: &str) -> usize {
193     unicode_str_width(s.rsplitn(2, '\n').next().unwrap_or(""))
194 }
195
196 // The total used width of the last line.
197 #[inline]
198 pub fn last_line_used_width(s: &str, offset: usize) -> usize {
199     if s.contains('\n') {
200         last_line_width(s)
201     } else {
202         offset + unicode_str_width(s)
203     }
204 }
205
206 #[inline]
207 pub fn trimmed_last_line_width(s: &str) -> usize {
208     unicode_str_width(match s.rfind('\n') {
209         Some(n) => s[(n + 1)..].trim(),
210         None => s.trim(),
211     })
212 }
213
214 #[inline]
215 pub fn last_line_extendable(s: &str) -> bool {
216     if s.ends_with("\"#") {
217         return true;
218     }
219     for c in s.chars().rev() {
220         match c {
221             '(' | ')' | ']' | '}' | '?' | '>' => continue,
222             '\n' => break,
223             _ if c.is_whitespace() => continue,
224             _ => return false,
225         }
226     }
227     true
228 }
229
230 #[inline]
231 fn is_skip(meta_item: &MetaItem) -> bool {
232     match meta_item.node {
233         MetaItemKind::Word => {
234             let path_str = meta_item.ident.to_string();
235             path_str == SKIP_ANNOTATION || path_str == DEPR_SKIP_ANNOTATION
236         }
237         MetaItemKind::List(ref l) => {
238             meta_item.name() == "cfg_attr" && l.len() == 2 && is_skip_nested(&l[1])
239         }
240         _ => false,
241     }
242 }
243
244 #[inline]
245 fn is_skip_nested(meta_item: &NestedMetaItem) -> bool {
246     match meta_item.node {
247         NestedMetaItemKind::MetaItem(ref mi) => is_skip(mi),
248         NestedMetaItemKind::Literal(_) => false,
249     }
250 }
251
252 #[inline]
253 pub fn contains_skip(attrs: &[Attribute]) -> bool {
254     attrs
255         .iter()
256         .any(|a| a.meta().map_or(false, |a| is_skip(&a)))
257 }
258
259 #[inline]
260 pub fn semicolon_for_expr(context: &RewriteContext<'_>, expr: &ast::Expr) -> bool {
261     match expr.node {
262         ast::ExprKind::Ret(..) | ast::ExprKind::Continue(..) | ast::ExprKind::Break(..) => {
263             context.config.trailing_semicolon()
264         }
265         _ => false,
266     }
267 }
268
269 #[inline]
270 pub fn semicolon_for_stmt(context: &RewriteContext<'_>, stmt: &ast::Stmt) -> bool {
271     match stmt.node {
272         ast::StmtKind::Semi(ref expr) => match expr.node {
273             ast::ExprKind::While(..)
274             | ast::ExprKind::WhileLet(..)
275             | ast::ExprKind::Loop(..)
276             | ast::ExprKind::ForLoop(..) => false,
277             ast::ExprKind::Break(..) | ast::ExprKind::Continue(..) | ast::ExprKind::Ret(..) => {
278                 context.config.trailing_semicolon()
279             }
280             _ => true,
281         },
282         ast::StmtKind::Expr(..) => false,
283         _ => true,
284     }
285 }
286
287 #[inline]
288 pub fn stmt_expr(stmt: &ast::Stmt) -> Option<&ast::Expr> {
289     match stmt.node {
290         ast::StmtKind::Expr(ref expr) => Some(expr),
291         _ => None,
292     }
293 }
294
295 #[inline]
296 pub fn count_newlines(input: &str) -> usize {
297     // Using bytes to omit UTF-8 decoding
298     bytecount::count(input.as_bytes(), b'\n')
299 }
300
301 // For format_missing and last_pos, need to use the source callsite (if applicable).
302 // Required as generated code spans aren't guaranteed to follow on from the last span.
303 macro_rules! source {
304     ($this:ident, $sp:expr) => {
305         $sp.source_callsite()
306     };
307 }
308
309 pub fn mk_sp(lo: BytePos, hi: BytePos) -> Span {
310     Span::new(lo, hi, NO_EXPANSION)
311 }
312
313 // Returns `true` if the given span does not intersect with file lines.
314 macro_rules! out_of_file_lines_range {
315     ($self:ident, $span:expr) => {
316         !$self.config.file_lines().is_all()
317             && !$self
318                 .config
319                 .file_lines()
320                 .intersects(&$self.source_map.lookup_line_range($span))
321     };
322 }
323
324 macro_rules! skip_out_of_file_lines_range {
325     ($self:ident, $span:expr) => {
326         if out_of_file_lines_range!($self, $span) {
327             return None;
328         }
329     };
330 }
331
332 macro_rules! skip_out_of_file_lines_range_visitor {
333     ($self:ident, $span:expr) => {
334         if out_of_file_lines_range!($self, $span) {
335             $self.push_rewrite($span, None);
336             return;
337         }
338     };
339 }
340
341 // Wraps String in an Option. Returns Some when the string adheres to the
342 // Rewrite constraints defined for the Rewrite trait and None otherwise.
343 pub fn wrap_str(s: String, max_width: usize, shape: Shape) -> Option<String> {
344     if is_valid_str(&filter_normal_code(&s), max_width, shape) {
345         Some(s)
346     } else {
347         None
348     }
349 }
350
351 fn is_valid_str(snippet: &str, max_width: usize, shape: Shape) -> bool {
352     if !snippet.is_empty() {
353         // First line must fits with `shape.width`.
354         if first_line_width(snippet) > shape.width {
355             return false;
356         }
357         // If the snippet does not include newline, we are done.
358         if is_single_line(snippet) {
359             return true;
360         }
361         // The other lines must fit within the maximum width.
362         if snippet
363             .lines()
364             .skip(1)
365             .any(|line| unicode_str_width(line) > max_width)
366         {
367             return false;
368         }
369         // A special check for the last line, since the caller may
370         // place trailing characters on this line.
371         if last_line_width(snippet) > shape.used_width() + shape.width {
372             return false;
373         }
374     }
375     true
376 }
377
378 #[inline]
379 pub fn colon_spaces(before: bool, after: bool) -> &'static str {
380     match (before, after) {
381         (true, true) => " : ",
382         (true, false) => " :",
383         (false, true) => ": ",
384         (false, false) => ":",
385     }
386 }
387
388 #[inline]
389 pub fn left_most_sub_expr(e: &ast::Expr) -> &ast::Expr {
390     match e.node {
391         ast::ExprKind::Call(ref e, _)
392         | ast::ExprKind::Binary(_, ref e, _)
393         | ast::ExprKind::Cast(ref e, _)
394         | ast::ExprKind::Type(ref e, _)
395         | ast::ExprKind::Assign(ref e, _)
396         | ast::ExprKind::AssignOp(_, ref e, _)
397         | ast::ExprKind::Field(ref e, _)
398         | ast::ExprKind::Index(ref e, _)
399         | ast::ExprKind::Range(Some(ref e), _, _)
400         | ast::ExprKind::Try(ref e) => left_most_sub_expr(e),
401         _ => e,
402     }
403 }
404
405 #[inline]
406 pub fn starts_with_newline(s: &str) -> bool {
407     s.starts_with('\n') || s.starts_with("\r\n")
408 }
409
410 #[inline]
411 pub fn first_line_ends_with(s: &str, c: char) -> bool {
412     s.lines().next().map_or(false, |l| l.ends_with(c))
413 }
414
415 // States whether an expression's last line exclusively consists of closing
416 // parens, braces, and brackets in its idiomatic formatting.
417 pub fn is_block_expr(context: &RewriteContext<'_>, expr: &ast::Expr, repr: &str) -> bool {
418     match expr.node {
419         ast::ExprKind::Mac(..)
420         | ast::ExprKind::Call(..)
421         | ast::ExprKind::MethodCall(..)
422         | ast::ExprKind::Array(..)
423         | ast::ExprKind::Struct(..)
424         | ast::ExprKind::While(..)
425         | ast::ExprKind::WhileLet(..)
426         | ast::ExprKind::If(..)
427         | ast::ExprKind::IfLet(..)
428         | ast::ExprKind::Block(..)
429         | ast::ExprKind::Loop(..)
430         | ast::ExprKind::ForLoop(..)
431         | ast::ExprKind::Match(..) => repr.contains('\n'),
432         ast::ExprKind::Paren(ref expr)
433         | ast::ExprKind::Binary(_, _, ref expr)
434         | ast::ExprKind::Index(_, ref expr)
435         | ast::ExprKind::Unary(_, ref expr)
436         | ast::ExprKind::Closure(_, _, _, _, ref expr, _)
437         | ast::ExprKind::Try(ref expr)
438         | ast::ExprKind::Yield(Some(ref expr)) => is_block_expr(context, expr, repr),
439         // This can only be a string lit
440         ast::ExprKind::Lit(_) => {
441             repr.contains('\n') && trimmed_last_line_width(repr) <= context.config.tab_spaces()
442         }
443         _ => false,
444     }
445 }
446
447 /// Removes trailing spaces from the specified snippet. We do not remove spaces
448 /// inside strings or comments.
449 pub fn remove_trailing_white_spaces(text: &str) -> String {
450     let mut buffer = String::with_capacity(text.len());
451     let mut space_buffer = String::with_capacity(128);
452     for (char_kind, c) in CharClasses::new(text.chars()) {
453         match c {
454             '\n' => {
455                 if char_kind == FullCodeCharKind::InString {
456                     buffer.push_str(&space_buffer);
457                 }
458                 space_buffer.clear();
459                 buffer.push('\n');
460             }
461             _ if c.is_whitespace() => {
462                 space_buffer.push(c);
463             }
464             _ => {
465                 if !space_buffer.is_empty() {
466                     buffer.push_str(&space_buffer);
467                     space_buffer.clear();
468                 }
469                 buffer.push(c);
470             }
471         }
472     }
473     buffer
474 }
475
476 /// Indent each line according to the specified `indent`.
477 /// e.g.
478 ///
479 /// ```rust,ignore
480 /// foo!{
481 /// x,
482 /// y,
483 /// foo(
484 ///     a,
485 ///     b,
486 ///     c,
487 /// ),
488 /// }
489 /// ```
490 ///
491 /// will become
492 ///
493 /// ```rust,ignore
494 /// foo!{
495 ///     x,
496 ///     y,
497 ///     foo(
498 ///         a,
499 ///         b,
500 ///         c,
501 ///     ),
502 /// }
503 /// ```
504 pub fn trim_left_preserve_layout(orig: &str, indent: Indent, config: &Config) -> Option<String> {
505     let mut lines = LineClasses::new(orig);
506     let first_line = lines.next().map(|(_, s)| s.trim_end().to_owned())?;
507     let mut trimmed_lines = Vec::with_capacity(16);
508
509     let mut veto_trim = false;
510     let min_prefix_space_width = lines
511         .filter_map(|(kind, line)| {
512             let mut trimmed = true;
513             let prefix_space_width = if is_empty_line(&line) {
514                 None
515             } else {
516                 Some(get_prefix_space_width(config, &line))
517             };
518
519             // just InString{Commented} in order to allow the start of a string to be indented
520             let new_veto_trim_value = (kind == FullCodeCharKind::InString
521                 || (config.version() == Version::Two
522                     && kind == FullCodeCharKind::InStringCommented))
523                 && !line.ends_with('\\');
524             let line = if veto_trim || new_veto_trim_value {
525                 veto_trim = new_veto_trim_value;
526                 trimmed = false;
527                 line
528             } else {
529                 line.trim().to_owned()
530             };
531             trimmed_lines.push((trimmed, line, prefix_space_width));
532
533             // Because there is a veto against trimming and indenting lines within a string,
534             // such lines should not be taken into account when computing the minimum.
535             match kind {
536                 FullCodeCharKind::InStringCommented | FullCodeCharKind::EndStringCommented
537                     if config.version() == Version::Two =>
538                 {
539                     None
540                 }
541                 FullCodeCharKind::InString | FullCodeCharKind::EndString => None,
542                 _ => prefix_space_width,
543             }
544         })
545         .min()?;
546
547     Some(
548         first_line
549             + "\n"
550             + &trimmed_lines
551                 .iter()
552                 .map(
553                     |&(trimmed, ref line, prefix_space_width)| match prefix_space_width {
554                         _ if !trimmed => line.to_owned(),
555                         Some(original_indent_width) => {
556                             let new_indent_width = indent.width()
557                                 + original_indent_width.saturating_sub(min_prefix_space_width);
558                             let new_indent = Indent::from_width(config, new_indent_width);
559                             format!("{}{}", new_indent.to_string(config), line)
560                         }
561                         None => String::new(),
562                     },
563                 )
564                 .collect::<Vec<_>>()
565                 .join("\n"),
566     )
567 }
568
569 /// Based on the given line, determine if the next line can be indented or not.
570 /// This allows to preserve the indentation of multi-line literals.
571 pub fn indent_next_line(kind: FullCodeCharKind, line: &str, config: &Config) -> bool {
572     !(kind.is_string() || (config.version() == Version::Two && kind.is_commented_string()))
573         || line.ends_with('\\')
574 }
575
576 pub fn is_empty_line(s: &str) -> bool {
577     s.is_empty() || s.chars().all(char::is_whitespace)
578 }
579
580 fn get_prefix_space_width(config: &Config, s: &str) -> usize {
581     let mut width = 0;
582     for c in s.chars() {
583         match c {
584             ' ' => width += 1,
585             '\t' => width += config.tab_spaces(),
586             _ => return width,
587         }
588     }
589     width
590 }
591
592 pub(crate) trait NodeIdExt {
593     fn root() -> Self;
594 }
595
596 impl NodeIdExt for NodeId {
597     fn root() -> NodeId {
598         NodeId::placeholder_from_mark(Mark::root())
599     }
600 }
601
602 pub(crate) fn unicode_str_width(s: &str) -> usize {
603     s.width()
604 }
605
606 pub fn get_skip_macro_names(attrs: &[ast::Attribute]) -> Vec<String> {
607     let mut skip_macro_names = vec![];
608     for attr in attrs {
609         // syntax::ast::Path is implemented partialEq
610         // but it is designed for segments.len() == 1
611         if format!("{}", attr.path) != "rustfmt::skip::macros" {
612             continue;
613         }
614
615         if let Some(list) = attr.meta_item_list() {
616             for spanned in list {
617                 if let Some(name) = spanned.name() {
618                     skip_macro_names.push(name.to_string());
619                 }
620             }
621         }
622     }
623     skip_macro_names
624 }
625
626 #[cfg(test)]
627 mod test {
628     use super::*;
629
630     #[test]
631     fn test_remove_trailing_white_spaces() {
632         let s = "    r#\"\n        test\n    \"#";
633         assert_eq!(remove_trailing_white_spaces(&s), s);
634     }
635
636     #[test]
637     fn test_trim_left_preserve_layout() {
638         let s = "aaa\n\tbbb\n    ccc";
639         let config = Config::default();
640         let indent = Indent::new(4, 0);
641         assert_eq!(
642             trim_left_preserve_layout(&s, indent, &config),
643             Some("aaa\n    bbb\n    ccc".to_string())
644         );
645     }
646 }