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.
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.
15 use rustc_target::spec::abi;
17 self, Attribute, CrateSugar, MetaItem, MetaItemKind, NestedMetaItem, NestedMetaItemKind, Path,
18 Visibility, VisibilityKind,
21 use syntax::source_map::{BytePos, Span, NO_EXPANSION};
23 use comment::{filter_normal_code, CharClasses, FullCodeCharKind};
24 use rewrite::RewriteContext;
27 pub const DEPR_SKIP_ANNOTATION: &str = "rustfmt_skip";
28 pub const SKIP_ANNOTATION: &str = "rustfmt::skip";
30 pub fn rewrite_ident<'a>(context: &'a RewriteContext, ident: ast::Ident) -> &'a str {
31 context.snippet(ident.span)
34 // Computes the length of a string's last line, minus offset.
35 pub fn extra_offset(text: &str, shape: Shape) -> usize {
36 match text.rfind('\n') {
37 // 1 for newline character
38 Some(idx) => text.len().saturating_sub(idx + 1 + shape.used_width()),
43 pub fn is_same_visibility(a: &Visibility, b: &Visibility) -> bool {
44 match (&a.node, &b.node) {
46 VisibilityKind::Restricted { path: p, .. },
47 VisibilityKind::Restricted { path: q, .. },
48 ) => p.to_string() == q.to_string(),
49 (VisibilityKind::Public, VisibilityKind::Public)
50 | (VisibilityKind::Inherited, VisibilityKind::Inherited)
52 VisibilityKind::Crate(CrateSugar::PubCrate),
53 VisibilityKind::Crate(CrateSugar::PubCrate),
56 VisibilityKind::Crate(CrateSugar::JustCrate),
57 VisibilityKind::Crate(CrateSugar::JustCrate),
63 // Uses Cow to avoid allocating in the common cases.
64 pub fn format_visibility(context: &RewriteContext, vis: &Visibility) -> Cow<'static, str> {
66 VisibilityKind::Public => Cow::from("pub "),
67 VisibilityKind::Inherited => Cow::from(""),
68 VisibilityKind::Crate(CrateSugar::PubCrate) => Cow::from("pub(crate) "),
69 VisibilityKind::Crate(CrateSugar::JustCrate) => Cow::from("crate "),
70 VisibilityKind::Restricted { ref path, .. } => {
71 let Path { ref segments, .. } = **path;
72 let mut segments_iter = segments.iter().map(|seg| rewrite_ident(context, seg.ident));
76 .expect("Non-global path in pub(restricted)?");
78 let is_keyword = |s: &str| s == "self" || s == "super";
79 let path = segments_iter.collect::<Vec<_>>().join("::");
80 let in_str = if is_keyword(&path) { "" } else { "in " };
82 Cow::from(format!("pub({}{}) ", in_str, path))
88 pub fn format_async(is_async: ast::IsAsync) -> &'static str {
90 ast::IsAsync::Async { .. } => "async ",
91 ast::IsAsync::NotAsync => "",
96 pub fn format_constness(constness: ast::Constness) -> &'static str {
98 ast::Constness::Const => "const ",
99 ast::Constness::NotConst => "",
104 pub fn format_defaultness(defaultness: ast::Defaultness) -> &'static str {
106 ast::Defaultness::Default => "default ",
107 ast::Defaultness::Final => "",
112 pub fn format_unsafety(unsafety: ast::Unsafety) -> &'static str {
114 ast::Unsafety::Unsafe => "unsafe ",
115 ast::Unsafety::Normal => "",
120 pub fn format_auto(is_auto: ast::IsAuto) -> &'static str {
122 ast::IsAuto::Yes => "auto ",
123 ast::IsAuto::No => "",
128 pub fn format_mutability(mutability: ast::Mutability) -> &'static str {
130 ast::Mutability::Mutable => "mut ",
131 ast::Mutability::Immutable => "",
136 pub fn format_abi(abi: abi::Abi, explicit_abi: bool, is_mod: bool) -> Cow<'static, str> {
137 if abi == abi::Abi::Rust && !is_mod {
139 } else if abi == abi::Abi::C && !explicit_abi {
142 Cow::from(format!("extern {} ", abi))
147 // Transform `Vec<syntax::ptr::P<T>>` into `Vec<&T>`
148 pub fn ptr_vec_to_ref_vec<T>(vec: &[ptr::P<T>]) -> Vec<&T> {
149 vec.iter().map(|x| &**x).collect::<Vec<_>>()
153 pub fn filter_attributes(attrs: &[ast::Attribute], style: ast::AttrStyle) -> Vec<ast::Attribute> {
156 .filter(|a| a.style == style)
162 pub fn inner_attributes(attrs: &[ast::Attribute]) -> Vec<ast::Attribute> {
163 filter_attributes(attrs, ast::AttrStyle::Inner)
167 pub fn outer_attributes(attrs: &[ast::Attribute]) -> Vec<ast::Attribute> {
168 filter_attributes(attrs, ast::AttrStyle::Outer)
172 pub fn is_single_line(s: &str) -> bool {
173 s.chars().find(|&c| c == '\n').is_none()
177 pub fn first_line_contains_single_line_comment(s: &str) -> bool {
178 s.lines().next().map_or(false, |l| l.contains("//"))
182 pub fn last_line_contains_single_line_comment(s: &str) -> bool {
183 s.lines().last().map_or(false, |l| l.contains("//"))
187 pub fn is_attributes_extendable(attrs_str: &str) -> bool {
188 !attrs_str.contains('\n') && !last_line_contains_single_line_comment(attrs_str)
191 // The width of the first line in s.
193 pub fn first_line_width(s: &str) -> usize {
200 // The width of the last line in s.
202 pub fn last_line_width(s: &str) -> usize {
203 match s.rfind('\n') {
204 Some(n) => s.len() - n - 1,
209 // The total used width of the last line.
211 pub fn last_line_used_width(s: &str, offset: usize) -> usize {
212 if s.contains('\n') {
220 pub fn trimmed_last_line_width(s: &str) -> usize {
221 match s.rfind('\n') {
222 Some(n) => s[(n + 1)..].trim().len(),
223 None => s.trim().len(),
228 pub fn last_line_extendable(s: &str) -> bool {
229 if s.ends_with("\"#") {
232 for c in s.chars().rev() {
234 '(' | ')' | ']' | '}' | '?' | '>' => continue,
236 _ if c.is_whitespace() => continue,
244 fn is_skip(meta_item: &MetaItem) -> bool {
245 match meta_item.node {
246 MetaItemKind::Word => {
247 let path_str = meta_item.ident.to_string();
248 path_str == SKIP_ANNOTATION || path_str == DEPR_SKIP_ANNOTATION
250 MetaItemKind::List(ref l) => {
251 meta_item.name() == "cfg_attr" && l.len() == 2 && is_skip_nested(&l[1])
258 fn is_skip_nested(meta_item: &NestedMetaItem) -> bool {
259 match meta_item.node {
260 NestedMetaItemKind::MetaItem(ref mi) => is_skip(mi),
261 NestedMetaItemKind::Literal(_) => false,
266 pub fn contains_skip(attrs: &[Attribute]) -> bool {
269 .any(|a| a.meta().map_or(false, |a| is_skip(&a)))
273 pub fn semicolon_for_expr(context: &RewriteContext, expr: &ast::Expr) -> bool {
275 ast::ExprKind::Ret(..) | ast::ExprKind::Continue(..) | ast::ExprKind::Break(..) => {
276 context.config.trailing_semicolon()
283 pub fn semicolon_for_stmt(context: &RewriteContext, stmt: &ast::Stmt) -> bool {
285 ast::StmtKind::Semi(ref expr) => match expr.node {
286 ast::ExprKind::While(..)
287 | ast::ExprKind::WhileLet(..)
288 | ast::ExprKind::Loop(..)
289 | ast::ExprKind::ForLoop(..) => false,
290 ast::ExprKind::Break(..) | ast::ExprKind::Continue(..) | ast::ExprKind::Ret(..) => {
291 context.config.trailing_semicolon()
295 ast::StmtKind::Expr(..) => false,
301 pub fn stmt_expr(stmt: &ast::Stmt) -> Option<&ast::Expr> {
303 ast::StmtKind::Expr(ref expr) => Some(expr),
309 pub fn count_newlines(input: &str) -> usize {
310 // Using bytes to omit UTF-8 decoding
311 bytecount::count(input.as_bytes(), b'\n')
314 // For format_missing and last_pos, need to use the source callsite (if applicable).
315 // Required as generated code spans aren't guaranteed to follow on from the last span.
316 macro_rules! source {
317 ($this:ident, $sp:expr) => {
318 $sp.source_callsite()
322 pub fn mk_sp(lo: BytePos, hi: BytePos) -> Span {
323 Span::new(lo, hi, NO_EXPANSION)
326 // Return true if the given span does not intersect with file lines.
327 macro_rules! out_of_file_lines_range {
328 ($self:ident, $span:expr) => {
329 !$self.config.file_lines().is_all()
333 .intersects(&$self.source_map.lookup_line_range($span))
337 macro_rules! skip_out_of_file_lines_range {
338 ($self:ident, $span:expr) => {
339 if out_of_file_lines_range!($self, $span) {
345 macro_rules! skip_out_of_file_lines_range_visitor {
346 ($self:ident, $span:expr) => {
347 if out_of_file_lines_range!($self, $span) {
348 $self.push_rewrite($span, None);
354 // Wraps String in an Option. Returns Some when the string adheres to the
355 // Rewrite constraints defined for the Rewrite trait and None otherwise.
356 pub fn wrap_str(s: String, max_width: usize, shape: Shape) -> Option<String> {
357 if is_valid_str(&filter_normal_code(&s), max_width, shape) {
364 fn is_valid_str(snippet: &str, max_width: usize, shape: Shape) -> bool {
365 if !snippet.is_empty() {
366 // First line must fits with `shape.width`.
367 if first_line_width(snippet) > shape.width {
370 // If the snippet does not include newline, we are done.
371 if first_line_width(snippet) == snippet.len() {
374 // The other lines must fit within the maximum width.
375 if snippet.lines().skip(1).any(|line| line.len() > max_width) {
378 // A special check for the last line, since the caller may
379 // place trailing characters on this line.
380 if last_line_width(snippet) > shape.used_width() + shape.width {
388 pub fn colon_spaces(before: bool, after: bool) -> &'static str {
389 match (before, after) {
390 (true, true) => " : ",
391 (true, false) => " :",
392 (false, true) => ": ",
393 (false, false) => ":",
398 pub fn left_most_sub_expr(e: &ast::Expr) -> &ast::Expr {
400 ast::ExprKind::Call(ref e, _)
401 | ast::ExprKind::Binary(_, ref e, _)
402 | ast::ExprKind::Cast(ref e, _)
403 | ast::ExprKind::Type(ref e, _)
404 | ast::ExprKind::Assign(ref e, _)
405 | ast::ExprKind::AssignOp(_, ref e, _)
406 | ast::ExprKind::Field(ref e, _)
407 | ast::ExprKind::Index(ref e, _)
408 | ast::ExprKind::Range(Some(ref e), _, _)
409 | ast::ExprKind::Try(ref e) => left_most_sub_expr(e),
415 pub fn starts_with_newline(s: &str) -> bool {
416 s.starts_with('\n') || s.starts_with("\r\n")
420 pub fn first_line_ends_with(s: &str, c: char) -> bool {
421 s.lines().next().map_or(false, |l| l.ends_with(c))
424 // States whether an expression's last line exclusively consists of closing
425 // parens, braces, and brackets in its idiomatic formatting.
426 pub fn is_block_expr(context: &RewriteContext, expr: &ast::Expr, repr: &str) -> bool {
428 ast::ExprKind::Mac(..)
429 | ast::ExprKind::Call(..)
430 | ast::ExprKind::MethodCall(..)
431 | ast::ExprKind::Array(..)
432 | ast::ExprKind::Struct(..)
433 | ast::ExprKind::While(..)
434 | ast::ExprKind::WhileLet(..)
435 | ast::ExprKind::If(..)
436 | ast::ExprKind::IfLet(..)
437 | ast::ExprKind::Block(..)
438 | ast::ExprKind::Loop(..)
439 | ast::ExprKind::ForLoop(..)
440 | ast::ExprKind::Match(..) => repr.contains('\n'),
441 ast::ExprKind::Paren(ref expr)
442 | ast::ExprKind::Binary(_, _, ref expr)
443 | ast::ExprKind::Index(_, ref expr)
444 | ast::ExprKind::Unary(_, ref expr)
445 | ast::ExprKind::Closure(_, _, _, _, ref expr, _)
446 | ast::ExprKind::Try(ref expr)
447 | ast::ExprKind::Yield(Some(ref expr)) => is_block_expr(context, expr, repr),
448 // This can only be a string lit
449 ast::ExprKind::Lit(_) => {
450 repr.contains('\n') && trimmed_last_line_width(repr) <= context.config.tab_spaces()
456 /// Remove trailing spaces from the specified snippet. We do not remove spaces
457 /// inside strings or comments.
458 pub fn remove_trailing_white_spaces(text: &str) -> String {
459 let mut buffer = String::with_capacity(text.len());
460 let mut space_buffer = String::with_capacity(128);
461 for (char_kind, c) in CharClasses::new(text.chars()) {
464 if char_kind == FullCodeCharKind::InString {
465 buffer.push_str(&space_buffer);
467 space_buffer.clear();
470 _ if c.is_whitespace() => {
471 space_buffer.push(c);
474 if !space_buffer.is_empty() {
475 buffer.push_str(&space_buffer);
476 space_buffer.clear();
486 fn test_remove_trailing_white_spaces() {
487 let s = " r#\"\n test\n \"#";
488 assert_eq!(remove_trailing_white_spaces(&s), s);