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