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.
13 use rustc_target::spec::abi;
14 use syntax::ast::{self, Attribute, CrateSugar, MetaItem, MetaItemKind, NestedMetaItem,
15 NestedMetaItemKind, Path, Visibility, VisibilityKind};
16 use syntax::codemap::{BytePos, Span, NO_EXPANSION};
20 use rewrite::RewriteContext;
23 // When we get scoped annotations, we should have rustfmt::skip.
24 const SKIP_ANNOTATION: &str = "rustfmt_skip";
26 // Computes the length of a string's last line, minus offset.
27 pub fn extra_offset(text: &str, shape: Shape) -> usize {
28 match text.rfind('\n') {
29 // 1 for newline character
30 Some(idx) => text.len()
31 .checked_sub(idx + 1 + shape.used_width())
37 // Uses Cow to avoid allocating in the common cases.
38 pub fn format_visibility(vis: &Visibility) -> Cow<'static, str> {
40 VisibilityKind::Public => Cow::from("pub "),
41 VisibilityKind::Inherited => Cow::from(""),
42 VisibilityKind::Crate(CrateSugar::PubCrate) => Cow::from("pub(crate) "),
43 VisibilityKind::Crate(CrateSugar::JustCrate) => Cow::from("crate "),
44 VisibilityKind::Restricted { ref path, .. } => {
45 let Path { ref segments, .. } = **path;
46 let mut segments_iter = segments.iter().map(|seg| seg.ident.name.to_string());
50 .expect("Non-global path in pub(restricted)?");
52 let is_keyword = |s: &str| s == "self" || s == "super";
53 let path = segments_iter.collect::<Vec<_>>().join("::");
54 let in_str = if is_keyword(&path) { "" } else { "in " };
56 Cow::from(format!("pub({}{}) ", in_str, path))
62 pub fn format_constness(constness: ast::Constness) -> &'static str {
64 ast::Constness::Const => "const ",
65 ast::Constness::NotConst => "",
70 pub fn format_defaultness(defaultness: ast::Defaultness) -> &'static str {
72 ast::Defaultness::Default => "default ",
73 ast::Defaultness::Final => "",
78 pub fn format_unsafety(unsafety: ast::Unsafety) -> &'static str {
80 ast::Unsafety::Unsafe => "unsafe ",
81 ast::Unsafety::Normal => "",
86 pub fn format_auto(is_auto: ast::IsAuto) -> &'static str {
88 ast::IsAuto::Yes => "auto ",
89 ast::IsAuto::No => "",
94 pub fn format_mutability(mutability: ast::Mutability) -> &'static str {
96 ast::Mutability::Mutable => "mut ",
97 ast::Mutability::Immutable => "",
102 pub fn format_abi(abi: abi::Abi, explicit_abi: bool, is_mod: bool) -> Cow<'static, str> {
103 if abi == abi::Abi::Rust && !is_mod {
105 } else if abi == abi::Abi::C && !explicit_abi {
108 Cow::from(format!("extern {} ", abi))
113 // Transform `Vec<syntax::ptr::P<T>>` into `Vec<&T>`
114 pub fn ptr_vec_to_ref_vec<T>(vec: &[ptr::P<T>]) -> Vec<&T> {
115 vec.iter().map(|x| &**x).collect::<Vec<_>>()
119 pub fn filter_attributes(attrs: &[ast::Attribute], style: ast::AttrStyle) -> Vec<ast::Attribute> {
122 .filter(|a| a.style == style)
128 pub fn inner_attributes(attrs: &[ast::Attribute]) -> Vec<ast::Attribute> {
129 filter_attributes(attrs, ast::AttrStyle::Inner)
133 pub fn outer_attributes(attrs: &[ast::Attribute]) -> Vec<ast::Attribute> {
134 filter_attributes(attrs, ast::AttrStyle::Outer)
138 pub fn is_single_line(s: &str) -> bool {
139 s.chars().find(|&c| c == '\n').is_none()
143 pub fn first_line_contains_single_line_comment(s: &str) -> bool {
144 s.lines().next().map_or(false, |l| l.contains("//"))
148 pub fn last_line_contains_single_line_comment(s: &str) -> bool {
149 s.lines().last().map_or(false, |l| l.contains("//"))
153 pub fn is_attributes_extendable(attrs_str: &str) -> bool {
154 !attrs_str.contains('\n') && !last_line_contains_single_line_comment(attrs_str)
157 // The width of the first line in s.
159 pub fn first_line_width(s: &str) -> usize {
166 // The width of the last line in s.
168 pub fn last_line_width(s: &str) -> usize {
169 match s.rfind('\n') {
170 Some(n) => s.len() - n - 1,
175 // The total used width of the last line.
177 pub fn last_line_used_width(s: &str, offset: usize) -> usize {
178 if s.contains('\n') {
186 pub fn trimmed_last_line_width(s: &str) -> usize {
187 match s.rfind('\n') {
188 Some(n) => s[(n + 1)..].trim().len(),
189 None => s.trim().len(),
194 pub fn last_line_extendable(s: &str) -> bool {
195 if s.ends_with("\"#") {
198 for c in s.chars().rev() {
200 '(' | ')' | ']' | '}' | '?' | '>' => continue,
202 _ if c.is_whitespace() => continue,
210 fn is_skip(meta_item: &MetaItem) -> bool {
211 match meta_item.node {
212 MetaItemKind::Word => meta_item.ident.name == SKIP_ANNOTATION,
213 MetaItemKind::List(ref l) => {
214 meta_item.ident.name == "cfg_attr" && l.len() == 2 && is_skip_nested(&l[1])
221 fn is_skip_nested(meta_item: &NestedMetaItem) -> bool {
222 match meta_item.node {
223 NestedMetaItemKind::MetaItem(ref mi) => is_skip(mi),
224 NestedMetaItemKind::Literal(_) => false,
229 pub fn contains_skip(attrs: &[Attribute]) -> bool {
232 .any(|a| a.meta().map_or(false, |a| is_skip(&a)))
236 pub fn semicolon_for_expr(context: &RewriteContext, expr: &ast::Expr) -> bool {
238 ast::ExprKind::Ret(..) | ast::ExprKind::Continue(..) | ast::ExprKind::Break(..) => {
239 context.config.trailing_semicolon()
246 pub fn semicolon_for_stmt(context: &RewriteContext, stmt: &ast::Stmt) -> bool {
248 ast::StmtKind::Semi(ref expr) => match expr.node {
249 ast::ExprKind::While(..)
250 | ast::ExprKind::WhileLet(..)
251 | ast::ExprKind::Loop(..)
252 | ast::ExprKind::ForLoop(..) => false,
253 ast::ExprKind::Break(..) | ast::ExprKind::Continue(..) | ast::ExprKind::Ret(..) => {
254 context.config.trailing_semicolon()
258 ast::StmtKind::Expr(..) => false,
264 pub fn stmt_expr(stmt: &ast::Stmt) -> Option<&ast::Expr> {
266 ast::StmtKind::Expr(ref expr) => Some(expr),
272 pub fn count_newlines(input: &str) -> usize {
273 // Using `as_bytes` to omit UTF-8 decoding
274 input.as_bytes().iter().filter(|&&c| c == b'\n').count()
277 // For format_missing and last_pos, need to use the source callsite (if applicable).
278 // Required as generated code spans aren't guaranteed to follow on from the last span.
279 macro_rules! source {
280 ($this:ident, $sp:expr) => {
281 $sp.source_callsite()
285 pub fn mk_sp(lo: BytePos, hi: BytePos) -> Span {
286 Span::new(lo, hi, NO_EXPANSION)
289 // Return true if the given span does not intersect with file lines.
290 macro_rules! out_of_file_lines_range {
291 ($self:ident, $span:expr) => {
292 !$self.config.file_lines().is_all()
296 .intersects(&$self.codemap.lookup_line_range($span))
300 macro_rules! skip_out_of_file_lines_range {
301 ($self:ident, $span:expr) => {
302 if out_of_file_lines_range!($self, $span) {
308 macro_rules! skip_out_of_file_lines_range_visitor {
309 ($self:ident, $span:expr) => {
310 if out_of_file_lines_range!($self, $span) {
311 $self.push_rewrite($span, None);
317 // Wraps String in an Option. Returns Some when the string adheres to the
318 // Rewrite constraints defined for the Rewrite trait and else otherwise.
319 pub fn wrap_str(s: String, max_width: usize, shape: Shape) -> Option<String> {
320 if is_valid_str(&s, max_width, shape) {
327 fn is_valid_str(snippet: &str, max_width: usize, shape: Shape) -> bool {
328 if !snippet.is_empty() {
329 // First line must fits with `shape.width`.
330 if first_line_width(snippet) > shape.width {
333 // If the snippet does not include newline, we are done.
334 if first_line_width(snippet) == snippet.len() {
337 // The other lines must fit within the maximum width.
338 if snippet.lines().skip(1).any(|line| line.len() > max_width) {
341 // A special check for the last line, since the caller may
342 // place trailing characters on this line.
343 if last_line_width(snippet) > shape.used_width() + shape.width {
351 pub fn colon_spaces(before: bool, after: bool) -> &'static str {
352 match (before, after) {
353 (true, true) => " : ",
354 (true, false) => " :",
355 (false, true) => ": ",
356 (false, false) => ":",
361 pub fn paren_overhead(context: &RewriteContext) -> usize {
362 if context.config.spaces_within_parens_and_brackets() {
369 pub fn left_most_sub_expr(e: &ast::Expr) -> &ast::Expr {
371 ast::ExprKind::Call(ref e, _)
372 | ast::ExprKind::Binary(_, ref e, _)
373 | ast::ExprKind::Cast(ref e, _)
374 | ast::ExprKind::Type(ref e, _)
375 | ast::ExprKind::Assign(ref e, _)
376 | ast::ExprKind::AssignOp(_, ref e, _)
377 | ast::ExprKind::Field(ref e, _)
378 | ast::ExprKind::Index(ref e, _)
379 | ast::ExprKind::Range(Some(ref e), _, _)
380 | ast::ExprKind::Try(ref e) => left_most_sub_expr(e),
385 // isatty shamelessly adapted from cargo.
387 pub fn isatty() -> bool {
390 unsafe { libc::isatty(libc::STDOUT_FILENO) != 0 }
393 pub fn isatty() -> bool {
397 let handle = winapi::um::processenv::GetStdHandle(winapi::um::winbase::STD_OUTPUT_HANDLE);
399 winapi::um::consoleapi::GetConsoleMode(handle, &mut out) != 0
403 pub fn use_colored_tty(color: Color) -> bool {
405 Color::Always => true,
406 Color::Never => false,
407 Color::Auto => isatty(),
411 pub fn starts_with_newline(s: &str) -> bool {
412 s.starts_with('\n') || s.starts_with("\r\n")