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 syntax::{abi, ptr};
14 use syntax::ast::{self, Attribute, MetaItem, MetaItemKind, NestedMetaItem, NestedMetaItemKind,
16 use syntax::codemap::{BytePos, Span, NO_EXPANSION};
18 use rewrite::RewriteContext;
21 // When we get scoped annotations, we should have rustfmt::skip.
22 const SKIP_ANNOTATION: &'static str = "rustfmt_skip";
24 // Computes the length of a string's last line, minus offset.
25 pub fn extra_offset(text: &str, shape: Shape) -> usize {
26 match text.rfind('\n') {
27 // 1 for newline character
28 Some(idx) => text.len()
29 .checked_sub(idx + 1 + shape.used_width())
35 // Uses Cow to avoid allocating in the common cases.
36 pub fn format_visibility(vis: &Visibility) -> Cow<'static, str> {
38 Visibility::Public => Cow::from("pub "),
39 Visibility::Inherited => Cow::from(""),
40 Visibility::Crate(_) => Cow::from("pub(crate) "),
41 Visibility::Restricted { ref path, .. } => {
42 let Path { ref segments, .. } = **path;
43 let mut segments_iter = segments.iter().map(|seg| seg.identifier.name.to_string());
47 .expect("Non-global path in pub(restricted)?");
49 let is_keyword = |s: &str| s == "self" || s == "super";
50 let path = segments_iter.collect::<Vec<_>>().join("::");
51 let in_str = if is_keyword(&path) { "" } else { "in " };
53 Cow::from(format!("pub({}{}) ", in_str, path))
59 pub fn format_constness(constness: ast::Constness) -> &'static str {
61 ast::Constness::Const => "const ",
62 ast::Constness::NotConst => "",
67 pub fn format_defaultness(defaultness: ast::Defaultness) -> &'static str {
69 ast::Defaultness::Default => "default ",
70 ast::Defaultness::Final => "",
75 pub fn format_unsafety(unsafety: ast::Unsafety) -> &'static str {
77 ast::Unsafety::Unsafe => "unsafe ",
78 ast::Unsafety::Normal => "",
83 pub fn format_mutability(mutability: ast::Mutability) -> &'static str {
85 ast::Mutability::Mutable => "mut ",
86 ast::Mutability::Immutable => "",
91 pub fn format_abi(abi: abi::Abi, explicit_abi: bool, is_mod: bool) -> Cow<'static, str> {
92 if abi == abi::Abi::Rust && !is_mod {
94 } else if abi == abi::Abi::C && !explicit_abi {
97 Cow::from(format!("extern {} ", abi))
102 // Transform `Vec<syntax::ptr::P<T>>` into `Vec<&T>`
103 pub fn ptr_vec_to_ref_vec<T>(vec: &[ptr::P<T>]) -> Vec<&T> {
104 vec.iter().map(|x| &**x).collect::<Vec<_>>()
108 pub fn filter_attributes(attrs: &[ast::Attribute], style: ast::AttrStyle) -> Vec<ast::Attribute> {
111 .filter(|a| a.style == style)
117 pub fn inner_attributes(attrs: &[ast::Attribute]) -> Vec<ast::Attribute> {
118 filter_attributes(attrs, ast::AttrStyle::Inner)
122 pub fn outer_attributes(attrs: &[ast::Attribute]) -> Vec<ast::Attribute> {
123 filter_attributes(attrs, ast::AttrStyle::Outer)
127 pub fn last_line_contains_single_line_comment(s: &str) -> bool {
128 s.lines().last().map_or(false, |l| l.contains("//"))
132 pub fn is_attributes_extendable(attrs_str: &str) -> bool {
133 !attrs_str.contains('\n') && !last_line_contains_single_line_comment(attrs_str)
136 // The width of the first line in s.
138 pub fn first_line_width(s: &str) -> usize {
145 // The width of the last line in s.
147 pub fn last_line_width(s: &str) -> usize {
148 match s.rfind('\n') {
149 Some(n) => s.len() - n - 1,
154 // The total used width of the last line.
156 pub fn last_line_used_width(s: &str, offset: usize) -> usize {
157 if s.contains('\n') {
165 pub fn trimmed_last_line_width(s: &str) -> usize {
166 match s.rfind('\n') {
167 Some(n) => s[(n + 1)..].trim().len(),
168 None => s.trim().len(),
173 pub fn last_line_extendable(s: &str) -> bool {
174 if s.ends_with("\"#") {
177 for c in s.chars().rev() {
179 ')' | ']' | '}' | '?' => continue,
181 _ if c.is_whitespace() => continue,
189 fn is_skip(meta_item: &MetaItem) -> bool {
190 match meta_item.node {
191 MetaItemKind::Word => meta_item.name == SKIP_ANNOTATION,
192 MetaItemKind::List(ref l) => {
193 meta_item.name == "cfg_attr" && l.len() == 2 && is_skip_nested(&l[1])
200 fn is_skip_nested(meta_item: &NestedMetaItem) -> bool {
201 match meta_item.node {
202 NestedMetaItemKind::MetaItem(ref mi) => is_skip(mi),
203 NestedMetaItemKind::Literal(_) => false,
208 pub fn contains_skip(attrs: &[Attribute]) -> bool {
211 .any(|a| a.meta().map_or(false, |a| is_skip(&a)))
214 // Find the end of a TyParam
216 pub fn end_typaram(typaram: &ast::TyParam) -> BytePos {
220 .map_or(typaram.span, |bound| match *bound {
221 ast::RegionTyParamBound(ref lt) => lt.span,
222 ast::TraitTyParamBound(ref prt, _) => prt.span,
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 trim_newlines(input: &str) -> &str {
265 match input.find(|c| c != '\n' && c != '\r') {
267 let end = input.rfind(|c| c != '\n' && c != '\r').unwrap_or(0) + 1;
274 // Macro for deriving implementations of Serialize/Deserialize for enums
276 macro_rules! impl_enum_serialize_and_deserialize {
277 ( $e:ident, $( $x:ident ),* ) => {
278 impl ::serde::ser::Serialize for $e {
279 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
280 where S: ::serde::ser::Serializer
282 use serde::ser::Error;
284 // We don't know whether the user of the macro has given us all options.
285 #[allow(unreachable_patterns)]
288 $e::$x => serializer.serialize_str(stringify!($x)),
291 Err(S::Error::custom(format!("Cannot serialize {:?}", self)))
297 impl<'de> ::serde::de::Deserialize<'de> for $e {
298 fn deserialize<D>(d: D) -> Result<Self, D::Error>
299 where D: ::serde::Deserializer<'de> {
300 use std::ascii::AsciiExt;
301 use serde::de::{Error, Visitor};
302 use std::marker::PhantomData;
304 struct StringOnly<T>(PhantomData<T>);
305 impl<'de, T> Visitor<'de> for StringOnly<T>
306 where T: ::serde::Deserializer<'de> {
308 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
309 formatter.write_str("string")
311 fn visit_str<E>(self, value: &str) -> Result<String, E> {
312 Ok(String::from(value))
315 let s = d.deserialize_string(StringOnly::<D>(PhantomData))?;
317 if stringify!($x).eq_ignore_ascii_case(&s) {
321 static ALLOWED: &'static[&str] = &[$(stringify!($x),)*];
322 Err(D::Error::unknown_variant(&s, ALLOWED))
326 impl ::std::str::FromStr for $e {
327 type Err = &'static str;
329 fn from_str(s: &str) -> Result<Self, Self::Err> {
330 use std::ascii::AsciiExt;
332 if stringify!($x).eq_ignore_ascii_case(s) {
340 impl ::config::ConfigType for $e {
341 fn doc_hint() -> String {
342 let mut variants = Vec::new();
344 variants.push(stringify!($x));
346 format!("[{}]", variants.join("|"))
354 match writeln!(&mut ::std::io::stderr(), $($arg)* ) {
356 Err(x) => panic!("Unable to write to stderr: {}", x),
361 // For format_missing and last_pos, need to use the source callsite (if applicable).
362 // Required as generated code spans aren't guaranteed to follow on from the last span.
363 macro_rules! source {
364 ($this:ident, $sp: expr) => {
365 $sp.source_callsite()
369 pub fn mk_sp(lo: BytePos, hi: BytePos) -> Span {
370 Span::new(lo, hi, NO_EXPANSION)
373 // Return true if the given span does not intersect with file lines.
374 macro_rules! out_of_file_lines_range {
375 ($self:ident, $span:expr) => {
378 .intersects(&$self.codemap.lookup_line_range($span))
382 macro_rules! skip_out_of_file_lines_range {
383 ($self:ident, $span:expr) => {
384 if out_of_file_lines_range!($self, $span) {
390 macro_rules! skip_out_of_file_lines_range_visitor {
391 ($self:ident, $span:expr) => {
392 if out_of_file_lines_range!($self, $span) {
393 $self.push_rewrite($span, None);
399 // Wraps String in an Option. Returns Some when the string adheres to the
400 // Rewrite constraints defined for the Rewrite trait and else otherwise.
401 pub fn wrap_str(s: String, max_width: usize, shape: Shape) -> Option<String> {
402 if is_valid_str(&s, max_width, shape) {
409 fn is_valid_str(snippet: &str, max_width: usize, shape: Shape) -> bool {
410 if !snippet.is_empty() {
411 // First line must fits with `shape.width`.
412 if first_line_width(snippet) > shape.width {
415 // If the snippet does not include newline, we are done.
416 if first_line_width(snippet) == snippet.len() {
419 // The other lines must fit within the maximum width.
420 if snippet.lines().skip(1).any(|line| line.len() > max_width) {
423 // A special check for the last line, since the caller may
424 // place trailing characters on this line.
425 if last_line_width(snippet) > shape.used_width() + shape.width {
433 pub fn colon_spaces(before: bool, after: bool) -> &'static str {
434 match (before, after) {
435 (true, true) => " : ",
436 (true, false) => " :",
437 (false, true) => ": ",
438 (false, false) => ":",
443 pub fn paren_overhead(context: &RewriteContext) -> usize {
444 if context.config.spaces_within_parens() {
451 pub fn left_most_sub_expr(e: &ast::Expr) -> &ast::Expr {
453 ast::ExprKind::InPlace(ref e, _) |
454 ast::ExprKind::Call(ref e, _) |
455 ast::ExprKind::Binary(_, ref e, _) |
456 ast::ExprKind::Cast(ref e, _) |
457 ast::ExprKind::Type(ref e, _) |
458 ast::ExprKind::Assign(ref e, _) |
459 ast::ExprKind::AssignOp(_, ref e, _) |
460 ast::ExprKind::Field(ref e, _) |
461 ast::ExprKind::TupField(ref e, _) |
462 ast::ExprKind::Index(ref e, _) |
463 ast::ExprKind::Range(Some(ref e), _, _) |
464 ast::ExprKind::Try(ref e) => left_most_sub_expr(e),
469 // isatty shamelessly adapted from cargo.
471 pub fn isatty() -> bool {
474 unsafe { libc::isatty(libc::STDOUT_FILENO) != 0 }
477 pub fn isatty() -> bool {
478 extern crate kernel32;
482 let handle = kernel32::GetStdHandle(winapi::winbase::STD_OUTPUT_HANDLE);
484 kernel32::GetConsoleMode(handle, &mut out) != 0
488 pub fn starts_with_newline(s: &str) -> bool {
489 s.starts_with('\n') || s.starts_with("\r\n")