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, CrateSugar, MetaItem, MetaItemKind, NestedMetaItem,
15 NestedMetaItemKind, Path, Visibility};
16 use syntax::codemap::{BytePos, Span, NO_EXPANSION};
19 use rewrite::RewriteContext;
22 // When we get scoped annotations, we should have rustfmt::skip.
23 const SKIP_ANNOTATION: &str = "rustfmt_skip";
25 // Computes the length of a string's last line, minus offset.
26 pub fn extra_offset(text: &str, shape: Shape) -> usize {
27 match text.rfind('\n') {
28 // 1 for newline character
29 Some(idx) => text.len()
30 .checked_sub(idx + 1 + shape.used_width())
36 // Uses Cow to avoid allocating in the common cases.
37 pub fn format_visibility(vis: &Visibility) -> Cow<'static, str> {
39 Visibility::Public => Cow::from("pub "),
40 Visibility::Inherited => Cow::from(""),
41 Visibility::Crate(_, CrateSugar::PubCrate) => Cow::from("pub(crate) "),
42 Visibility::Crate(_, CrateSugar::JustCrate) => Cow::from("crate "),
43 Visibility::Restricted { ref path, .. } => {
44 let Path { ref segments, .. } = **path;
45 let mut segments_iter = segments.iter().map(|seg| seg.identifier.name.to_string());
49 .expect("Non-global path in pub(restricted)?");
51 let is_keyword = |s: &str| s == "self" || s == "super";
52 let path = segments_iter.collect::<Vec<_>>().join("::");
53 let in_str = if is_keyword(&path) { "" } else { "in " };
55 Cow::from(format!("pub({}{}) ", in_str, path))
61 pub fn format_constness(constness: ast::Constness) -> &'static str {
63 ast::Constness::Const => "const ",
64 ast::Constness::NotConst => "",
69 pub fn format_defaultness(defaultness: ast::Defaultness) -> &'static str {
71 ast::Defaultness::Default => "default ",
72 ast::Defaultness::Final => "",
77 pub fn format_unsafety(unsafety: ast::Unsafety) -> &'static str {
79 ast::Unsafety::Unsafe => "unsafe ",
80 ast::Unsafety::Normal => "",
85 pub fn format_mutability(mutability: ast::Mutability) -> &'static str {
87 ast::Mutability::Mutable => "mut ",
88 ast::Mutability::Immutable => "",
93 pub fn format_abi(abi: abi::Abi, explicit_abi: bool, is_mod: bool) -> Cow<'static, str> {
94 if abi == abi::Abi::Rust && !is_mod {
96 } else if abi == abi::Abi::C && !explicit_abi {
99 Cow::from(format!("extern {} ", abi))
104 // Transform `Vec<syntax::ptr::P<T>>` into `Vec<&T>`
105 pub fn ptr_vec_to_ref_vec<T>(vec: &[ptr::P<T>]) -> Vec<&T> {
106 vec.iter().map(|x| &**x).collect::<Vec<_>>()
110 pub fn filter_attributes(attrs: &[ast::Attribute], style: ast::AttrStyle) -> Vec<ast::Attribute> {
113 .filter(|a| a.style == style)
119 pub fn inner_attributes(attrs: &[ast::Attribute]) -> Vec<ast::Attribute> {
120 filter_attributes(attrs, ast::AttrStyle::Inner)
124 pub fn outer_attributes(attrs: &[ast::Attribute]) -> Vec<ast::Attribute> {
125 filter_attributes(attrs, ast::AttrStyle::Outer)
129 pub fn last_line_contains_single_line_comment(s: &str) -> bool {
130 s.lines().last().map_or(false, |l| l.contains("//"))
134 pub fn is_attributes_extendable(attrs_str: &str) -> bool {
135 !attrs_str.contains('\n') && !last_line_contains_single_line_comment(attrs_str)
138 // The width of the first line in s.
140 pub fn first_line_width(s: &str) -> usize {
147 // The width of the last line in s.
149 pub fn last_line_width(s: &str) -> usize {
150 match s.rfind('\n') {
151 Some(n) => s.len() - n - 1,
156 // The total used width of the last line.
158 pub fn last_line_used_width(s: &str, offset: usize) -> usize {
159 if s.contains('\n') {
167 pub fn trimmed_last_line_width(s: &str) -> usize {
168 match s.rfind('\n') {
169 Some(n) => s[(n + 1)..].trim().len(),
170 None => s.trim().len(),
175 pub fn last_line_extendable(s: &str) -> bool {
176 if s.ends_with("\"#") {
179 for c in s.chars().rev() {
181 ')' | ']' | '}' | '?' => continue,
183 _ if c.is_whitespace() => continue,
191 fn is_skip(meta_item: &MetaItem) -> bool {
192 match meta_item.node {
193 MetaItemKind::Word => meta_item.name == SKIP_ANNOTATION,
194 MetaItemKind::List(ref l) => {
195 meta_item.name == "cfg_attr" && l.len() == 2 && is_skip_nested(&l[1])
202 fn is_skip_nested(meta_item: &NestedMetaItem) -> bool {
203 match meta_item.node {
204 NestedMetaItemKind::MetaItem(ref mi) => is_skip(mi),
205 NestedMetaItemKind::Literal(_) => false,
210 pub fn contains_skip(attrs: &[Attribute]) -> bool {
213 .any(|a| a.meta().map_or(false, |a| is_skip(&a)))
216 // Find the end of a TyParam
218 pub fn end_typaram(typaram: &ast::TyParam) -> BytePos {
222 .map_or(typaram.span, |bound| match *bound {
223 ast::RegionTyParamBound(ref lt) => lt.span,
224 ast::TraitTyParamBound(ref prt, _) => prt.span,
230 pub fn semicolon_for_expr(context: &RewriteContext, expr: &ast::Expr) -> bool {
232 ast::ExprKind::Ret(..) | ast::ExprKind::Continue(..) | ast::ExprKind::Break(..) => {
233 context.config.trailing_semicolon()
240 pub fn semicolon_for_stmt(context: &RewriteContext, stmt: &ast::Stmt) -> bool {
242 ast::StmtKind::Semi(ref expr) => match expr.node {
243 ast::ExprKind::While(..)
244 | ast::ExprKind::WhileLet(..)
245 | ast::ExprKind::Loop(..)
246 | ast::ExprKind::ForLoop(..) => false,
247 ast::ExprKind::Break(..) | ast::ExprKind::Continue(..) | ast::ExprKind::Ret(..) => {
248 context.config.trailing_semicolon()
252 ast::StmtKind::Expr(..) => false,
258 pub fn stmt_expr(stmt: &ast::Stmt) -> Option<&ast::Expr> {
260 ast::StmtKind::Expr(ref expr) => Some(expr),
266 pub fn count_newlines(input: &str) -> usize {
267 input.chars().filter(|&c| c == '\n').count()
271 pub fn trim_newlines(input: &str) -> &str {
272 match input.find(|c| c != '\n' && c != '\r') {
274 let end = input.rfind(|c| c != '\n' && c != '\r').unwrap_or(0) + 1;
281 // Macro for deriving implementations of Serialize/Deserialize for enums
283 macro_rules! impl_enum_serialize_and_deserialize {
284 ( $e:ident, $( $x:ident ),* ) => {
285 impl ::serde::ser::Serialize for $e {
286 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
287 where S: ::serde::ser::Serializer
289 use serde::ser::Error;
291 // We don't know whether the user of the macro has given us all options.
292 #[allow(unreachable_patterns)]
295 $e::$x => serializer.serialize_str(stringify!($x)),
298 Err(S::Error::custom(format!("Cannot serialize {:?}", self)))
304 impl<'de> ::serde::de::Deserialize<'de> for $e {
305 fn deserialize<D>(d: D) -> Result<Self, D::Error>
306 where D: ::serde::Deserializer<'de> {
307 use serde::de::{Error, Visitor};
308 use std::marker::PhantomData;
310 struct StringOnly<T>(PhantomData<T>);
311 impl<'de, T> Visitor<'de> for StringOnly<T>
312 where T: ::serde::Deserializer<'de> {
314 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
315 formatter.write_str("string")
317 fn visit_str<E>(self, value: &str) -> Result<String, E> {
318 Ok(String::from(value))
321 let s = d.deserialize_string(StringOnly::<D>(PhantomData))?;
323 if stringify!($x).eq_ignore_ascii_case(&s) {
327 static ALLOWED: &'static[&str] = &[$(stringify!($x),)*];
328 Err(D::Error::unknown_variant(&s, ALLOWED))
332 impl ::std::str::FromStr for $e {
333 type Err = &'static str;
335 fn from_str(s: &str) -> Result<Self, Self::Err> {
337 if stringify!($x).eq_ignore_ascii_case(s) {
345 impl ::config::ConfigType for $e {
346 fn doc_hint() -> String {
347 let mut variants = Vec::new();
349 variants.push(stringify!($x));
351 format!("[{}]", variants.join("|"))
359 match writeln!(&mut ::std::io::stderr(), $($arg)* ) {
361 Err(x) => panic!("Unable to write to stderr: {}", x),
366 // For format_missing and last_pos, need to use the source callsite (if applicable).
367 // Required as generated code spans aren't guaranteed to follow on from the last span.
368 macro_rules! source {
369 ($this:ident, $sp: expr) => {
370 $sp.source_callsite()
374 pub fn mk_sp(lo: BytePos, hi: BytePos) -> Span {
375 Span::new(lo, hi, NO_EXPANSION)
378 // Return true if the given span does not intersect with file lines.
379 macro_rules! out_of_file_lines_range {
380 ($self:ident, $span:expr) => {
383 .intersects(&$self.codemap.lookup_line_range($span))
387 macro_rules! skip_out_of_file_lines_range {
388 ($self:ident, $span:expr) => {
389 if out_of_file_lines_range!($self, $span) {
395 macro_rules! skip_out_of_file_lines_range_visitor {
396 ($self:ident, $span:expr) => {
397 if out_of_file_lines_range!($self, $span) {
398 $self.push_rewrite($span, None);
404 // Wraps String in an Option. Returns Some when the string adheres to the
405 // Rewrite constraints defined for the Rewrite trait and else otherwise.
406 pub fn wrap_str(s: String, max_width: usize, shape: Shape) -> Option<String> {
407 if is_valid_str(&s, max_width, shape) {
414 fn is_valid_str(snippet: &str, max_width: usize, shape: Shape) -> bool {
415 if !snippet.is_empty() {
416 // First line must fits with `shape.width`.
417 if first_line_width(snippet) > shape.width {
420 // If the snippet does not include newline, we are done.
421 if first_line_width(snippet) == snippet.len() {
424 // The other lines must fit within the maximum width.
425 if snippet.lines().skip(1).any(|line| line.len() > max_width) {
428 // A special check for the last line, since the caller may
429 // place trailing characters on this line.
430 if last_line_width(snippet) > shape.used_width() + shape.width {
438 pub fn colon_spaces(before: bool, after: bool) -> &'static str {
439 match (before, after) {
440 (true, true) => " : ",
441 (true, false) => " :",
442 (false, true) => ": ",
443 (false, false) => ":",
448 pub fn paren_overhead(context: &RewriteContext) -> usize {
449 if context.config.spaces_within_parens_and_brackets() {
456 pub fn left_most_sub_expr(e: &ast::Expr) -> &ast::Expr {
458 ast::ExprKind::InPlace(ref e, _)
459 | ast::ExprKind::Call(ref e, _)
460 | ast::ExprKind::Binary(_, ref e, _)
461 | ast::ExprKind::Cast(ref e, _)
462 | ast::ExprKind::Type(ref e, _)
463 | ast::ExprKind::Assign(ref e, _)
464 | ast::ExprKind::AssignOp(_, ref e, _)
465 | ast::ExprKind::Field(ref e, _)
466 | ast::ExprKind::TupField(ref e, _)
467 | ast::ExprKind::Index(ref e, _)
468 | ast::ExprKind::Range(Some(ref e), _, _)
469 | ast::ExprKind::Try(ref e) => left_most_sub_expr(e),
474 // isatty shamelessly adapted from cargo.
476 pub fn isatty() -> bool {
479 unsafe { libc::isatty(libc::STDOUT_FILENO) != 0 }
482 pub fn isatty() -> bool {
483 extern crate kernel32;
487 let handle = kernel32::GetStdHandle(winapi::winbase::STD_OUTPUT_HANDLE);
489 kernel32::GetConsoleMode(handle, &mut out) != 0
493 pub fn use_colored_tty(color: Color) -> bool {
495 Color::Always => true,
496 Color::Never => false,
497 Color::Auto => isatty(),
501 pub fn starts_with_newline(s: &str) -> bool {
502 s.starts_with('\n') || s.starts_with("\r\n")