]> git.lizzy.rs Git - rust.git/blob - src/utils.rs
discard trailing blank comments
[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 rustc_target::spec::abi;
14 use syntax::ast::{
15     self, Attribute, CrateSugar, MetaItem, MetaItemKind, NestedMetaItem, NestedMetaItemKind, Path,
16     Visibility, VisibilityKind,
17 };
18 use syntax::codemap::{BytePos, Span, NO_EXPANSION};
19 use syntax::ptr;
20
21 use comment::filter_normal_code;
22 use rewrite::RewriteContext;
23 use shape::Shape;
24
25 pub const DEPR_SKIP_ANNOTATION: &str = "rustfmt_skip";
26 pub const SKIP_ANNOTATION: &str = "rustfmt::skip";
27
28 pub fn rewrite_ident<'a>(context: &'a RewriteContext, ident: ast::Ident) -> &'a str {
29     context.snippet(ident.span)
30 }
31
32 // Computes the length of a string's last line, minus offset.
33 pub fn extra_offset(text: &str, shape: Shape) -> usize {
34     match text.rfind('\n') {
35         // 1 for newline character
36         Some(idx) => text.len().saturating_sub(idx + 1 + shape.used_width()),
37         None => text.len(),
38     }
39 }
40
41 pub fn is_same_visibility(a: &Visibility, b: &Visibility) -> bool {
42     match (&a.node, &b.node) {
43         (
44             VisibilityKind::Restricted { path: p, .. },
45             VisibilityKind::Restricted { path: q, .. },
46         ) => format!("{}", p) == format!("{}", q),
47         (VisibilityKind::Public, VisibilityKind::Public)
48         | (VisibilityKind::Inherited, VisibilityKind::Inherited)
49         | (
50             VisibilityKind::Crate(CrateSugar::PubCrate),
51             VisibilityKind::Crate(CrateSugar::PubCrate),
52         )
53         | (
54             VisibilityKind::Crate(CrateSugar::JustCrate),
55             VisibilityKind::Crate(CrateSugar::JustCrate),
56         ) => true,
57         _ => false,
58     }
59 }
60
61 // Uses Cow to avoid allocating in the common cases.
62 pub fn format_visibility(context: &RewriteContext, vis: &Visibility) -> Cow<'static, str> {
63     match vis.node {
64         VisibilityKind::Public => Cow::from("pub "),
65         VisibilityKind::Inherited => Cow::from(""),
66         VisibilityKind::Crate(CrateSugar::PubCrate) => Cow::from("pub(crate) "),
67         VisibilityKind::Crate(CrateSugar::JustCrate) => Cow::from("crate "),
68         VisibilityKind::Restricted { ref path, .. } => {
69             let Path { ref segments, .. } = **path;
70             let mut segments_iter = segments.iter().map(|seg| rewrite_ident(context, seg.ident));
71             if path.is_global() {
72                 segments_iter
73                     .next()
74                     .expect("Non-global path in pub(restricted)?");
75             }
76             let is_keyword = |s: &str| s == "self" || s == "super";
77             let path = segments_iter.collect::<Vec<_>>().join("::");
78             let in_str = if is_keyword(&path) { "" } else { "in " };
79
80             Cow::from(format!("pub({}{}) ", in_str, path))
81         }
82     }
83 }
84
85 #[inline]
86 pub fn format_async(is_async: ast::IsAsync) -> &'static str {
87     match is_async {
88         ast::IsAsync::Async { .. } => "async ",
89         ast::IsAsync::NotAsync => "",
90     }
91 }
92
93 #[inline]
94 pub fn format_constness(constness: ast::Constness) -> &'static str {
95     match constness {
96         ast::Constness::Const => "const ",
97         ast::Constness::NotConst => "",
98     }
99 }
100
101 #[inline]
102 pub fn format_defaultness(defaultness: ast::Defaultness) -> &'static str {
103     match defaultness {
104         ast::Defaultness::Default => "default ",
105         ast::Defaultness::Final => "",
106     }
107 }
108
109 #[inline]
110 pub fn format_unsafety(unsafety: ast::Unsafety) -> &'static str {
111     match unsafety {
112         ast::Unsafety::Unsafe => "unsafe ",
113         ast::Unsafety::Normal => "",
114     }
115 }
116
117 #[inline]
118 pub fn format_auto(is_auto: ast::IsAuto) -> &'static str {
119     match is_auto {
120         ast::IsAuto::Yes => "auto ",
121         ast::IsAuto::No => "",
122     }
123 }
124
125 #[inline]
126 pub fn format_mutability(mutability: ast::Mutability) -> &'static str {
127     match mutability {
128         ast::Mutability::Mutable => "mut ",
129         ast::Mutability::Immutable => "",
130     }
131 }
132
133 #[inline]
134 pub fn format_abi(abi: abi::Abi, explicit_abi: bool, is_mod: bool) -> Cow<'static, str> {
135     if abi == abi::Abi::Rust && !is_mod {
136         Cow::from("")
137     } else if abi == abi::Abi::C && !explicit_abi {
138         Cow::from("extern ")
139     } else {
140         Cow::from(format!("extern {} ", abi))
141     }
142 }
143
144 #[inline]
145 // Transform `Vec<syntax::ptr::P<T>>` into `Vec<&T>`
146 pub fn ptr_vec_to_ref_vec<T>(vec: &[ptr::P<T>]) -> Vec<&T> {
147     vec.iter().map(|x| &**x).collect::<Vec<_>>()
148 }
149
150 #[inline]
151 pub fn filter_attributes(attrs: &[ast::Attribute], style: ast::AttrStyle) -> Vec<ast::Attribute> {
152     attrs
153         .iter()
154         .filter(|a| a.style == style)
155         .cloned()
156         .collect::<Vec<_>>()
157 }
158
159 #[inline]
160 pub fn inner_attributes(attrs: &[ast::Attribute]) -> Vec<ast::Attribute> {
161     filter_attributes(attrs, ast::AttrStyle::Inner)
162 }
163
164 #[inline]
165 pub fn outer_attributes(attrs: &[ast::Attribute]) -> Vec<ast::Attribute> {
166     filter_attributes(attrs, ast::AttrStyle::Outer)
167 }
168
169 #[inline]
170 pub fn is_single_line(s: &str) -> bool {
171     s.chars().find(|&c| c == '\n').is_none()
172 }
173
174 #[inline]
175 pub fn first_line_contains_single_line_comment(s: &str) -> bool {
176     s.lines().next().map_or(false, |l| l.contains("//"))
177 }
178
179 #[inline]
180 pub fn last_line_contains_single_line_comment(s: &str) -> bool {
181     s.lines().last().map_or(false, |l| l.contains("//"))
182 }
183
184 #[inline]
185 pub fn is_attributes_extendable(attrs_str: &str) -> bool {
186     !attrs_str.contains('\n') && !last_line_contains_single_line_comment(attrs_str)
187 }
188
189 // The width of the first line in s.
190 #[inline]
191 pub fn first_line_width(s: &str) -> usize {
192     match s.find('\n') {
193         Some(n) => n,
194         None => s.len(),
195     }
196 }
197
198 // The width of the last line in s.
199 #[inline]
200 pub fn last_line_width(s: &str) -> usize {
201     match s.rfind('\n') {
202         Some(n) => s.len() - n - 1,
203         None => s.len(),
204     }
205 }
206
207 // The total used width of the last line.
208 #[inline]
209 pub fn last_line_used_width(s: &str, offset: usize) -> usize {
210     if s.contains('\n') {
211         last_line_width(s)
212     } else {
213         offset + s.len()
214     }
215 }
216
217 #[inline]
218 pub fn trimmed_last_line_width(s: &str) -> usize {
219     match s.rfind('\n') {
220         Some(n) => s[(n + 1)..].trim().len(),
221         None => s.trim().len(),
222     }
223 }
224
225 #[inline]
226 pub fn last_line_extendable(s: &str) -> bool {
227     if s.ends_with("\"#") {
228         return true;
229     }
230     for c in s.chars().rev() {
231         match c {
232             '(' | ')' | ']' | '}' | '?' | '>' => continue,
233             '\n' => break,
234             _ if c.is_whitespace() => continue,
235             _ => return false,
236         }
237     }
238     true
239 }
240
241 #[inline]
242 fn is_skip(meta_item: &MetaItem) -> bool {
243     match meta_item.node {
244         MetaItemKind::Word => {
245             let path_str = meta_item.ident.to_string();
246             path_str == SKIP_ANNOTATION || path_str == DEPR_SKIP_ANNOTATION
247         }
248         MetaItemKind::List(ref l) => {
249             meta_item.name() == "cfg_attr" && l.len() == 2 && is_skip_nested(&l[1])
250         }
251         _ => false,
252     }
253 }
254
255 #[inline]
256 fn is_skip_nested(meta_item: &NestedMetaItem) -> bool {
257     match meta_item.node {
258         NestedMetaItemKind::MetaItem(ref mi) => is_skip(mi),
259         NestedMetaItemKind::Literal(_) => false,
260     }
261 }
262
263 #[inline]
264 pub fn contains_skip(attrs: &[Attribute]) -> bool {
265     attrs
266         .iter()
267         .any(|a| a.meta().map_or(false, |a| is_skip(&a)))
268 }
269
270 #[inline]
271 pub fn semicolon_for_expr(context: &RewriteContext, expr: &ast::Expr) -> bool {
272     match expr.node {
273         ast::ExprKind::Ret(..) | ast::ExprKind::Continue(..) | ast::ExprKind::Break(..) => {
274             context.config.trailing_semicolon()
275         }
276         _ => false,
277     }
278 }
279
280 #[inline]
281 pub fn semicolon_for_stmt(context: &RewriteContext, stmt: &ast::Stmt) -> bool {
282     match stmt.node {
283         ast::StmtKind::Semi(ref expr) => match expr.node {
284             ast::ExprKind::While(..)
285             | ast::ExprKind::WhileLet(..)
286             | ast::ExprKind::Loop(..)
287             | ast::ExprKind::ForLoop(..) => false,
288             ast::ExprKind::Break(..) | ast::ExprKind::Continue(..) | ast::ExprKind::Ret(..) => {
289                 context.config.trailing_semicolon()
290             }
291             _ => true,
292         },
293         ast::StmtKind::Expr(..) => false,
294         _ => true,
295     }
296 }
297
298 #[inline]
299 pub fn stmt_expr(stmt: &ast::Stmt) -> Option<&ast::Expr> {
300     match stmt.node {
301         ast::StmtKind::Expr(ref expr) => Some(expr),
302         _ => None,
303     }
304 }
305
306 #[inline]
307 pub fn count_newlines(input: &str) -> usize {
308     // Using `as_bytes` to omit UTF-8 decoding
309     input.as_bytes().iter().filter(|&&c| c == b'\n').count()
310 }
311
312 // For format_missing and last_pos, need to use the source callsite (if applicable).
313 // Required as generated code spans aren't guaranteed to follow on from the last span.
314 macro_rules! source {
315     ($this:ident, $sp:expr) => {
316         $sp.source_callsite()
317     };
318 }
319
320 pub fn mk_sp(lo: BytePos, hi: BytePos) -> Span {
321     Span::new(lo, hi, NO_EXPANSION)
322 }
323
324 // Return true if the given span does not intersect with file lines.
325 macro_rules! out_of_file_lines_range {
326     ($self:ident, $span:expr) => {
327         !$self.config.file_lines().is_all() && !$self
328             .config
329             .file_lines()
330             .intersects(&$self.codemap.lookup_line_range($span))
331     };
332 }
333
334 macro_rules! skip_out_of_file_lines_range {
335     ($self:ident, $span:expr) => {
336         if out_of_file_lines_range!($self, $span) {
337             return None;
338         }
339     };
340 }
341
342 macro_rules! skip_out_of_file_lines_range_visitor {
343     ($self:ident, $span:expr) => {
344         if out_of_file_lines_range!($self, $span) {
345             $self.push_rewrite($span, None);
346             return;
347         }
348     };
349 }
350
351 // Wraps String in an Option. Returns Some when the string adheres to the
352 // Rewrite constraints defined for the Rewrite trait and None otherwise.
353 pub fn wrap_str(s: String, max_width: usize, shape: Shape) -> Option<String> {
354     if is_valid_str(&filter_normal_code(&s), max_width, shape) {
355         Some(s)
356     } else {
357         None
358     }
359 }
360
361 fn is_valid_str(snippet: &str, max_width: usize, shape: Shape) -> bool {
362     if !snippet.is_empty() {
363         // First line must fits with `shape.width`.
364         if first_line_width(snippet) > shape.width {
365             return false;
366         }
367         // If the snippet does not include newline, we are done.
368         if first_line_width(snippet) == snippet.len() {
369             return true;
370         }
371         // The other lines must fit within the maximum width.
372         if snippet.lines().skip(1).any(|line| line.len() > max_width) {
373             return false;
374         }
375         // A special check for the last line, since the caller may
376         // place trailing characters on this line.
377         if last_line_width(snippet) > shape.used_width() + shape.width {
378             return false;
379         }
380     }
381     true
382 }
383
384 #[inline]
385 pub fn colon_spaces(before: bool, after: bool) -> &'static str {
386     match (before, after) {
387         (true, true) => " : ",
388         (true, false) => " :",
389         (false, true) => ": ",
390         (false, false) => ":",
391     }
392 }
393
394 #[inline]
395 pub fn left_most_sub_expr(e: &ast::Expr) -> &ast::Expr {
396     match e.node {
397         ast::ExprKind::Call(ref e, _)
398         | ast::ExprKind::Binary(_, ref e, _)
399         | ast::ExprKind::Cast(ref e, _)
400         | ast::ExprKind::Type(ref e, _)
401         | ast::ExprKind::Assign(ref e, _)
402         | ast::ExprKind::AssignOp(_, ref e, _)
403         | ast::ExprKind::Field(ref e, _)
404         | ast::ExprKind::Index(ref e, _)
405         | ast::ExprKind::Range(Some(ref e), _, _)
406         | ast::ExprKind::Try(ref e) => left_most_sub_expr(e),
407         _ => e,
408     }
409 }
410
411 #[inline]
412 pub fn starts_with_newline(s: &str) -> bool {
413     s.starts_with('\n') || s.starts_with("\r\n")
414 }
415
416 #[inline]
417 pub fn first_line_ends_with(s: &str, c: char) -> bool {
418     s.lines().next().map_or(false, |l| l.ends_with(c))
419 }