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;
15 self, Attribute, CrateSugar, MetaItem, MetaItemKind, NestedMetaItem, NestedMetaItemKind, Path,
16 Visibility, VisibilityKind,
18 use syntax::codemap::{BytePos, Span, NO_EXPANSION};
22 use rewrite::RewriteContext;
25 // When we get scoped annotations, we should have rustfmt::skip.
26 const SKIP_ANNOTATION: &str = "rustfmt_skip";
28 // Computes the length of a string's last line, minus offset.
29 pub fn extra_offset(text: &str, shape: Shape) -> usize {
30 match text.rfind('\n') {
31 // 1 for newline character
32 Some(idx) => text.len()
33 .checked_sub(idx + 1 + shape.used_width())
39 // Uses Cow to avoid allocating in the common cases.
40 pub fn format_visibility(vis: &Visibility) -> Cow<'static, str> {
42 VisibilityKind::Public => Cow::from("pub "),
43 VisibilityKind::Inherited => Cow::from(""),
44 VisibilityKind::Crate(CrateSugar::PubCrate) => Cow::from("pub(crate) "),
45 VisibilityKind::Crate(CrateSugar::JustCrate) => Cow::from("crate "),
46 VisibilityKind::Restricted { ref path, .. } => {
47 let Path { ref segments, .. } = **path;
48 let mut segments_iter = segments.iter().map(|seg| seg.ident.name.to_string());
52 .expect("Non-global path in pub(restricted)?");
54 let is_keyword = |s: &str| s == "self" || s == "super";
55 let path = segments_iter.collect::<Vec<_>>().join("::");
56 let in_str = if is_keyword(&path) { "" } else { "in " };
58 Cow::from(format!("pub({}{}) ", in_str, path))
64 pub fn format_constness(constness: ast::Constness) -> &'static str {
66 ast::Constness::Const => "const ",
67 ast::Constness::NotConst => "",
72 pub fn format_defaultness(defaultness: ast::Defaultness) -> &'static str {
74 ast::Defaultness::Default => "default ",
75 ast::Defaultness::Final => "",
80 pub fn format_unsafety(unsafety: ast::Unsafety) -> &'static str {
82 ast::Unsafety::Unsafe => "unsafe ",
83 ast::Unsafety::Normal => "",
88 pub fn format_auto(is_auto: ast::IsAuto) -> &'static str {
90 ast::IsAuto::Yes => "auto ",
91 ast::IsAuto::No => "",
96 pub fn format_mutability(mutability: ast::Mutability) -> &'static str {
98 ast::Mutability::Mutable => "mut ",
99 ast::Mutability::Immutable => "",
104 pub fn format_abi(abi: abi::Abi, explicit_abi: bool, is_mod: bool) -> Cow<'static, str> {
105 if abi == abi::Abi::Rust && !is_mod {
107 } else if abi == abi::Abi::C && !explicit_abi {
110 Cow::from(format!("extern {} ", abi))
115 // Transform `Vec<syntax::ptr::P<T>>` into `Vec<&T>`
116 pub fn ptr_vec_to_ref_vec<T>(vec: &[ptr::P<T>]) -> Vec<&T> {
117 vec.iter().map(|x| &**x).collect::<Vec<_>>()
121 pub fn filter_attributes(attrs: &[ast::Attribute], style: ast::AttrStyle) -> Vec<ast::Attribute> {
124 .filter(|a| a.style == style)
130 pub fn inner_attributes(attrs: &[ast::Attribute]) -> Vec<ast::Attribute> {
131 filter_attributes(attrs, ast::AttrStyle::Inner)
135 pub fn outer_attributes(attrs: &[ast::Attribute]) -> Vec<ast::Attribute> {
136 filter_attributes(attrs, ast::AttrStyle::Outer)
140 pub fn last_line_contains_single_line_comment(s: &str) -> bool {
141 s.lines().last().map_or(false, |l| l.contains("//"))
145 pub fn is_attributes_extendable(attrs_str: &str) -> bool {
146 !attrs_str.contains('\n') && !last_line_contains_single_line_comment(attrs_str)
149 // The width of the first line in s.
151 pub fn first_line_width(s: &str) -> usize {
158 // The width of the last line in s.
160 pub fn last_line_width(s: &str) -> usize {
161 match s.rfind('\n') {
162 Some(n) => s.len() - n - 1,
167 // The total used width of the last line.
169 pub fn last_line_used_width(s: &str, offset: usize) -> usize {
170 if s.contains('\n') {
178 pub fn trimmed_last_line_width(s: &str) -> usize {
179 match s.rfind('\n') {
180 Some(n) => s[(n + 1)..].trim().len(),
181 None => s.trim().len(),
186 pub fn last_line_extendable(s: &str) -> bool {
187 if s.ends_with("\"#") {
190 for c in s.chars().rev() {
192 '(' | ')' | ']' | '}' | '?' | '>' => continue,
194 _ if c.is_whitespace() => continue,
202 fn is_skip(meta_item: &MetaItem) -> bool {
203 match meta_item.node {
204 MetaItemKind::Word => meta_item.ident.name == SKIP_ANNOTATION,
205 MetaItemKind::List(ref l) => {
206 meta_item.ident.name == "cfg_attr" && l.len() == 2 && is_skip_nested(&l[1])
213 fn is_skip_nested(meta_item: &NestedMetaItem) -> bool {
214 match meta_item.node {
215 NestedMetaItemKind::MetaItem(ref mi) => is_skip(mi),
216 NestedMetaItemKind::Literal(_) => false,
221 pub fn contains_skip(attrs: &[Attribute]) -> bool {
224 .any(|a| a.meta().map_or(false, |a| is_skip(&a)))
228 pub fn semicolon_for_expr(context: &RewriteContext, expr: &ast::Expr) -> bool {
230 ast::ExprKind::Ret(..) | ast::ExprKind::Continue(..) | ast::ExprKind::Break(..) => {
231 context.config.trailing_semicolon()
238 pub fn semicolon_for_stmt(context: &RewriteContext, stmt: &ast::Stmt) -> bool {
240 ast::StmtKind::Semi(ref expr) => match expr.node {
241 ast::ExprKind::While(..)
242 | ast::ExprKind::WhileLet(..)
243 | ast::ExprKind::Loop(..)
244 | ast::ExprKind::ForLoop(..) => false,
245 ast::ExprKind::Break(..) | ast::ExprKind::Continue(..) | ast::ExprKind::Ret(..) => {
246 context.config.trailing_semicolon()
250 ast::StmtKind::Expr(..) => false,
256 pub fn stmt_expr(stmt: &ast::Stmt) -> Option<&ast::Expr> {
258 ast::StmtKind::Expr(ref expr) => Some(expr),
264 pub fn count_newlines(input: &str) -> usize {
265 // Using `as_bytes` to omit UTF-8 decoding
266 input.as_bytes().iter().filter(|&&c| c == b'\n').count()
269 // For format_missing and last_pos, need to use the source callsite (if applicable).
270 // Required as generated code spans aren't guaranteed to follow on from the last span.
271 macro_rules! source {
272 ($this:ident, $sp:expr) => {
273 $sp.source_callsite()
277 pub fn mk_sp(lo: BytePos, hi: BytePos) -> Span {
278 Span::new(lo, hi, NO_EXPANSION)
281 // Return true if the given span does not intersect with file lines.
282 macro_rules! out_of_file_lines_range {
283 ($self:ident, $span:expr) => {
284 !$self.config.file_lines().is_all()
288 .intersects(&$self.codemap.lookup_line_range($span))
292 macro_rules! skip_out_of_file_lines_range {
293 ($self:ident, $span:expr) => {
294 if out_of_file_lines_range!($self, $span) {
300 macro_rules! skip_out_of_file_lines_range_visitor {
301 ($self:ident, $span:expr) => {
302 if out_of_file_lines_range!($self, $span) {
303 $self.push_rewrite($span, None);
309 // Wraps String in an Option. Returns Some when the string adheres to the
310 // Rewrite constraints defined for the Rewrite trait and else otherwise.
311 pub fn wrap_str(s: String, max_width: usize, shape: Shape) -> Option<String> {
312 if is_valid_str(&s, max_width, shape) {
319 fn is_valid_str(snippet: &str, max_width: usize, shape: Shape) -> bool {
320 if !snippet.is_empty() {
321 // First line must fits with `shape.width`.
322 if first_line_width(snippet) > shape.width {
325 // If the snippet does not include newline, we are done.
326 if first_line_width(snippet) == snippet.len() {
329 // The other lines must fit within the maximum width.
330 if snippet.lines().skip(1).any(|line| line.len() > max_width) {
333 // A special check for the last line, since the caller may
334 // place trailing characters on this line.
335 if last_line_width(snippet) > shape.used_width() + shape.width {
343 pub fn colon_spaces(before: bool, after: bool) -> &'static str {
344 match (before, after) {
345 (true, true) => " : ",
346 (true, false) => " :",
347 (false, true) => ": ",
348 (false, false) => ":",
353 pub fn paren_overhead(context: &RewriteContext) -> usize {
354 if context.config.spaces_within_parens_and_brackets() {
361 pub fn left_most_sub_expr(e: &ast::Expr) -> &ast::Expr {
363 ast::ExprKind::Call(ref e, _)
364 | ast::ExprKind::Binary(_, ref e, _)
365 | ast::ExprKind::Cast(ref e, _)
366 | ast::ExprKind::Type(ref e, _)
367 | ast::ExprKind::Assign(ref e, _)
368 | ast::ExprKind::AssignOp(_, ref e, _)
369 | ast::ExprKind::Field(ref e, _)
370 | ast::ExprKind::Index(ref e, _)
371 | ast::ExprKind::Range(Some(ref e), _, _)
372 | ast::ExprKind::Try(ref e) => left_most_sub_expr(e),
377 // isatty shamelessly adapted from cargo.
379 pub fn isatty() -> bool {
382 unsafe { libc::isatty(libc::STDOUT_FILENO) != 0 }
385 pub fn isatty() -> bool {
389 let handle = winapi::um::processenv::GetStdHandle(winapi::um::winbase::STD_OUTPUT_HANDLE);
391 winapi::um::consoleapi::GetConsoleMode(handle, &mut out) != 0
395 pub fn use_colored_tty(color: Color) -> bool {
397 Color::Always => true,
398 Color::Never => false,
399 Color::Auto => isatty(),
403 pub fn starts_with_newline(s: &str) -> bool {
404 s.starts_with('\n') || s.starts_with("\r\n")