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::{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) -> Cow<'static, str> {
92 if abi == abi::Abi::C && !explicit_abi {
95 Cow::from(format!("extern {} ", abi))
100 // Transform `Vec<syntax::ptr::P<T>>` into `Vec<&T>`
101 pub fn ptr_vec_to_ref_vec<T>(vec: &[ptr::P<T>]) -> Vec<&T> {
102 vec.iter().map(|x| &**x).collect::<Vec<_>>()
106 pub fn filter_attributes(attrs: &[ast::Attribute], style: ast::AttrStyle) -> Vec<ast::Attribute> {
109 .filter(|a| a.style == style)
115 pub fn inner_attributes(attrs: &[ast::Attribute]) -> Vec<ast::Attribute> {
116 filter_attributes(attrs, ast::AttrStyle::Inner)
120 pub fn outer_attributes(attrs: &[ast::Attribute]) -> Vec<ast::Attribute> {
121 filter_attributes(attrs, ast::AttrStyle::Outer)
125 pub fn last_line_contains_single_line_comment(s: &str) -> bool {
126 s.lines().last().map_or(false, |l| l.contains("//"))
130 pub fn is_attributes_extendable(attrs_str: &str) -> bool {
131 !attrs_str.contains('\n') && !last_line_contains_single_line_comment(attrs_str)
134 // The width of the first line in s.
136 pub fn first_line_width(s: &str) -> usize {
143 // The width of the last line in s.
145 pub fn last_line_width(s: &str) -> usize {
146 match s.rfind('\n') {
147 Some(n) => s.len() - n - 1,
152 // The total used width of the last line.
154 pub fn last_line_used_width(s: &str, offset: usize) -> usize {
155 if s.contains('\n') {
163 pub fn trimmed_last_line_width(s: &str) -> usize {
164 match s.rfind('\n') {
165 Some(n) => s[(n + 1)..].trim().len(),
166 None => s.trim().len(),
171 pub fn last_line_extendable(s: &str) -> bool {
172 s.lines().last().map_or(false, |s| {
176 .all(|c| c == ')' || c == ']' || c == '}' || c == '?')
181 fn is_skip(meta_item: &MetaItem) -> bool {
182 match meta_item.node {
183 MetaItemKind::Word => meta_item.name == SKIP_ANNOTATION,
184 MetaItemKind::List(ref l) => {
185 meta_item.name == "cfg_attr" && l.len() == 2 && is_skip_nested(&l[1])
192 fn is_skip_nested(meta_item: &NestedMetaItem) -> bool {
193 match meta_item.node {
194 NestedMetaItemKind::MetaItem(ref mi) => is_skip(mi),
195 NestedMetaItemKind::Literal(_) => false,
200 pub fn contains_skip(attrs: &[Attribute]) -> bool {
203 .any(|a| a.meta().map_or(false, |a| is_skip(&a)))
206 // Find the end of a TyParam
208 pub fn end_typaram(typaram: &ast::TyParam) -> BytePos {
212 .map_or(typaram.span, |bound| match *bound {
213 ast::RegionTyParamBound(ref lt) => lt.span,
214 ast::TraitTyParamBound(ref prt, _) => prt.span,
220 pub fn semicolon_for_expr(context: &RewriteContext, expr: &ast::Expr) -> bool {
222 ast::ExprKind::Ret(..) | ast::ExprKind::Continue(..) | ast::ExprKind::Break(..) => {
223 context.config.trailing_semicolon()
230 pub fn semicolon_for_stmt(context: &RewriteContext, stmt: &ast::Stmt) -> bool {
232 ast::StmtKind::Semi(ref expr) => match expr.node {
233 ast::ExprKind::While(..) |
234 ast::ExprKind::WhileLet(..) |
235 ast::ExprKind::Loop(..) |
236 ast::ExprKind::ForLoop(..) => false,
237 ast::ExprKind::Break(..) | ast::ExprKind::Continue(..) | ast::ExprKind::Ret(..) => {
238 context.config.trailing_semicolon()
242 ast::StmtKind::Expr(..) => false,
248 pub fn stmt_expr(stmt: &ast::Stmt) -> Option<&ast::Expr> {
250 ast::StmtKind::Expr(ref expr) => Some(expr),
256 pub fn trim_newlines(input: &str) -> &str {
257 match input.find(|c| c != '\n' && c != '\r') {
259 let end = input.rfind(|c| c != '\n' && c != '\r').unwrap_or(0) + 1;
266 // Macro for deriving implementations of Serialize/Deserialize for enums
268 macro_rules! impl_enum_serialize_and_deserialize {
269 ( $e:ident, $( $x:ident ),* ) => {
270 impl ::serde::ser::Serialize for $e {
271 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
272 where S: ::serde::ser::Serializer
274 use serde::ser::Error;
276 // We don't know whether the user of the macro has given us all options.
277 #[allow(unreachable_patterns)]
280 $e::$x => serializer.serialize_str(stringify!($x)),
283 Err(S::Error::custom(format!("Cannot serialize {:?}", self)))
289 impl<'de> ::serde::de::Deserialize<'de> for $e {
290 fn deserialize<D>(d: D) -> Result<Self, D::Error>
291 where D: ::serde::Deserializer<'de> {
292 use std::ascii::AsciiExt;
293 use serde::de::{Error, Visitor};
294 use std::marker::PhantomData;
296 struct StringOnly<T>(PhantomData<T>);
297 impl<'de, T> Visitor<'de> for StringOnly<T>
298 where T: ::serde::Deserializer<'de> {
300 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
301 formatter.write_str("string")
303 fn visit_str<E>(self, value: &str) -> Result<String, E> {
304 Ok(String::from(value))
307 let s = d.deserialize_string(StringOnly::<D>(PhantomData))?;
309 if stringify!($x).eq_ignore_ascii_case(&s) {
313 static ALLOWED: &'static[&str] = &[$(stringify!($x),)*];
314 Err(D::Error::unknown_variant(&s, ALLOWED))
318 impl ::std::str::FromStr for $e {
319 type Err = &'static str;
321 fn from_str(s: &str) -> Result<Self, Self::Err> {
322 use std::ascii::AsciiExt;
324 if stringify!($x).eq_ignore_ascii_case(s) {
332 impl ::config::ConfigType for $e {
333 fn doc_hint() -> String {
334 let mut variants = Vec::new();
336 variants.push(stringify!($x));
338 format!("[{}]", variants.join("|"))
344 // Same as try!, but for Option
346 macro_rules! try_opt {
347 ($expr:expr) => (match $expr {
349 None => { return None; }
355 match writeln!(&mut ::std::io::stderr(), $($arg)* ) {
357 Err(x) => panic!("Unable to write to stderr: {}", x),
362 // For format_missing and last_pos, need to use the source callsite (if applicable).
363 // Required as generated code spans aren't guaranteed to follow on from the last span.
364 macro_rules! source {
365 ($this:ident, $sp: expr) => {
366 $sp.source_callsite()
370 pub fn mk_sp(lo: BytePos, hi: BytePos) -> Span {
371 Span::new(lo, hi, NO_EXPANSION)
374 // Return true if the given span does not intersect with file lines.
375 macro_rules! out_of_file_lines_range {
376 ($self:ident, $span:expr) => {
379 .intersects(&$self.codemap.lookup_line_range($span))
383 macro_rules! skip_out_of_file_lines_range {
384 ($self:ident, $span:expr) => {
385 if out_of_file_lines_range!($self, $span) {
391 macro_rules! skip_out_of_file_lines_range_visitor {
392 ($self:ident, $span:expr) => {
393 if out_of_file_lines_range!($self, $span) {
394 $self.push_rewrite($span, None);
400 // Wraps string-like values in an Option. Returns Some when the string adheres
401 // to the Rewrite constraints defined for the Rewrite trait and else otherwise.
402 pub fn wrap_str<S: AsRef<str>>(s: S, max_width: usize, shape: Shape) -> Option<S> {
404 let snippet = s.as_ref();
406 if !snippet.is_empty() {
407 if !snippet.contains('\n') && snippet.len() > shape.width {
410 let mut lines = snippet.lines();
412 if lines.next().unwrap().len() > shape.width {
416 // The other lines must fit within the maximum width.
417 if lines.any(|line| line.len() > max_width) {
421 // `width` is the maximum length of the last line, excluding
423 // A special check for the last line, since the caller may
424 // place trailing characters on this line.
425 if snippet.lines().rev().next().unwrap().len() > shape.used_width() + shape.width {
435 impl Rewrite for String {
436 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
437 wrap_str(self, context.config.max_width(), shape).map(ToOwned::to_owned)
442 pub fn colon_spaces(before: bool, after: bool) -> &'static str {
443 match (before, after) {
444 (true, true) => " : ",
445 (true, false) => " :",
446 (false, true) => ": ",
447 (false, false) => ":",
452 pub fn paren_overhead(context: &RewriteContext) -> usize {
453 if context.config.spaces_within_parens() {
460 pub fn left_most_sub_expr(e: &ast::Expr) -> &ast::Expr {
462 ast::ExprKind::InPlace(ref e, _) |
463 ast::ExprKind::Call(ref e, _) |
464 ast::ExprKind::Binary(_, ref e, _) |
465 ast::ExprKind::Cast(ref e, _) |
466 ast::ExprKind::Type(ref e, _) |
467 ast::ExprKind::Assign(ref e, _) |
468 ast::ExprKind::AssignOp(_, ref e, _) |
469 ast::ExprKind::Field(ref e, _) |
470 ast::ExprKind::TupField(ref e, _) |
471 ast::ExprKind::Index(ref e, _) |
472 ast::ExprKind::Range(Some(ref e), _, _) |
473 ast::ExprKind::Try(ref e) => left_most_sub_expr(e),
478 // isatty shamelessly adapted from cargo.
480 pub fn isatty() -> bool {
483 unsafe { libc::isatty(libc::STDOUT_FILENO) != 0 }
486 pub fn isatty() -> bool {
487 extern crate kernel32;
491 let handle = kernel32::GetStdHandle(winapi::winbase::STD_OUTPUT_HANDLE);
493 kernel32::GetConsoleMode(handle, &mut out) != 0