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.
12 use std::cmp::Ordering;
14 use syntax::ast::{self, Visibility, Attribute, MetaItem, MetaItemKind, NestedMetaItem,
15 NestedMetaItemKind, Path};
16 use syntax::codemap::{BytePos, Span, NO_EXPANSION};
20 use rewrite::{Rewrite, RewriteContext};
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
30 .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 Visibility::Public => Cow::from("pub "),
41 Visibility::Inherited => Cow::from(""),
42 Visibility::Crate(_) => Cow::from("pub(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_unsafety(unsafety: ast::Unsafety) -> &'static str {
63 ast::Unsafety::Unsafe => "unsafe ",
64 ast::Unsafety::Normal => "",
69 pub fn format_mutability(mutability: ast::Mutability) -> &'static str {
71 ast::Mutability::Mutable => "mut ",
72 ast::Mutability::Immutable => "",
77 pub fn format_abi(abi: abi::Abi, explicit_abi: bool) -> String {
78 if abi == abi::Abi::C && !explicit_abi {
81 format!("extern {} ", abi)
85 // The width of the first line in s.
87 pub fn first_line_width(s: &str) -> usize {
94 // The width of the last line in s.
96 pub fn last_line_width(s: &str) -> usize {
98 Some(n) => s.len() - n - 1,
104 pub fn trimmed_last_line_width(s: &str) -> usize {
105 match s.rfind('\n') {
106 Some(n) => s[(n + 1)..].trim().len(),
107 None => s.trim().len(),
112 fn is_skip(meta_item: &MetaItem) -> bool {
113 match meta_item.node {
114 MetaItemKind::Word => meta_item.name == SKIP_ANNOTATION,
115 MetaItemKind::List(ref l) => {
116 meta_item.name == "cfg_attr" && l.len() == 2 && is_skip_nested(&l[1])
123 fn is_skip_nested(meta_item: &NestedMetaItem) -> bool {
124 match meta_item.node {
125 NestedMetaItemKind::MetaItem(ref mi) => is_skip(mi),
126 NestedMetaItemKind::Literal(_) => false,
131 pub fn contains_skip(attrs: &[Attribute]) -> bool {
134 .any(|a| a.meta().map_or(false, |a| is_skip(&a)))
137 // Find the end of a TyParam
139 pub fn end_typaram(typaram: &ast::TyParam) -> BytePos {
143 .map_or(typaram.span, |bound| match *bound {
144 ast::RegionTyParamBound(ref lt) => lt.span,
145 ast::TraitTyParamBound(ref prt, _) => prt.span,
151 pub fn semicolon_for_expr(expr: &ast::Expr) -> bool {
153 ast::ExprKind::Ret(..) |
154 ast::ExprKind::Continue(..) |
155 ast::ExprKind::Break(..) => true,
161 pub fn semicolon_for_stmt(stmt: &ast::Stmt) -> bool {
163 ast::StmtKind::Semi(ref expr) => {
165 ast::ExprKind::While(..) |
166 ast::ExprKind::WhileLet(..) |
167 ast::ExprKind::Loop(..) |
168 ast::ExprKind::ForLoop(..) => false,
172 ast::StmtKind::Expr(..) => false,
178 pub fn stmt_expr(stmt: &ast::Stmt) -> Option<&ast::Expr> {
180 ast::StmtKind::Expr(ref expr) => Some(expr),
186 pub fn trim_newlines(input: &str) -> &str {
187 match input.find(|c| c != '\n' && c != '\r') {
189 let end = input.rfind(|c| c != '\n' && c != '\r').unwrap_or(0) + 1;
196 // Macro for deriving implementations of Serialize/Deserialize for enums
198 macro_rules! impl_enum_serialize_and_deserialize {
199 ( $e:ident, $( $x:ident ),* ) => {
200 impl ::serde::ser::Serialize for $e {
201 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
202 where S: ::serde::ser::Serializer
204 use serde::ser::Error;
206 // We don't know whether the user of the macro has given us all options.
207 #[allow(unreachable_patterns)]
210 $e::$x => serializer.serialize_str(stringify!($x)),
213 Err(S::Error::custom(format!("Cannot serialize {:?}", self)))
219 impl<'de> ::serde::de::Deserialize<'de> for $e {
220 fn deserialize<D>(d: D) -> Result<Self, D::Error>
221 where D: ::serde::Deserializer<'de> {
222 use std::ascii::AsciiExt;
223 use serde::de::{Error, Visitor};
224 use std::marker::PhantomData;
226 struct StringOnly<T>(PhantomData<T>);
227 impl<'de, T> Visitor<'de> for StringOnly<T>
228 where T: ::serde::Deserializer<'de> {
230 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
231 formatter.write_str("string")
233 fn visit_str<E>(self, value: &str) -> Result<String, E> {
234 Ok(String::from(value))
237 let s = d.deserialize_string(StringOnly::<D>(PhantomData))?;
239 if stringify!($x).eq_ignore_ascii_case(&s) {
243 static ALLOWED: &'static[&str] = &[$(stringify!($x),)*];
244 Err(D::Error::unknown_variant(&s, ALLOWED))
248 impl ::std::str::FromStr for $e {
249 type Err = &'static str;
251 fn from_str(s: &str) -> Result<Self, Self::Err> {
252 use std::ascii::AsciiExt;
254 if stringify!($x).eq_ignore_ascii_case(s) {
262 impl ::config::ConfigType for $e {
263 fn doc_hint() -> String {
264 let mut variants = Vec::new();
266 variants.push(stringify!($x));
268 format!("[{}]", variants.join("|"))
274 // Same as try!, but for Option
276 macro_rules! try_opt {
277 ($expr:expr) => (match $expr {
279 None => { return None; }
285 match writeln!(&mut ::std::io::stderr(), $($arg)* ) {
287 Err(x) => panic!("Unable to write to stderr: {}", x),
292 // For format_missing and last_pos, need to use the source callsite (if applicable).
293 // Required as generated code spans aren't guaranteed to follow on from the last span.
294 macro_rules! source {
295 ($this:ident, $sp: expr) => {
296 $sp.source_callsite()
300 pub fn mk_sp(lo: BytePos, hi: BytePos) -> Span {
308 // Wraps string-like values in an Option. Returns Some when the string adheres
309 // to the Rewrite constraints defined for the Rewrite trait and else otherwise.
310 pub fn wrap_str<S: AsRef<str>>(s: S, max_width: usize, shape: Shape) -> Option<S> {
312 let snippet = s.as_ref();
314 if !snippet.is_empty() {
315 if !snippet.contains('\n') && snippet.len() > shape.width {
318 let mut lines = snippet.lines();
320 if lines.next().unwrap().len() > shape.width {
324 // The other lines must fit within the maximum width.
325 if lines.any(|line| line.len() > max_width) {
329 // `width` is the maximum length of the last line, excluding
331 // A special check for the last line, since the caller may
332 // place trailing characters on this line.
333 if snippet.lines().rev().next().unwrap().len() > shape.used_width() + shape.width {
343 impl Rewrite for String {
344 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
345 wrap_str(self, context.config.max_width(), shape).map(ToOwned::to_owned)
349 // Binary search in integer range. Returns the first Ok value returned by the
351 // The callback takes an integer and returns either an Ok, or an Err indicating
352 // whether the `guess' was too high (Ordering::Less), or too low.
353 // This function is guaranteed to try to the hi value first.
354 pub fn binary_search<C, T>(mut lo: usize, mut hi: usize, callback: C) -> Option<T>
356 C: Fn(usize) -> Result<T, Ordering>,
361 match callback(middle) {
362 Ok(val) => return Some(val),
363 Err(Ordering::Less) => {
370 middle = (hi + lo) / 2;
377 pub fn colon_spaces(before: bool, after: bool) -> &'static str {
378 match (before, after) {
379 (true, true) => " : ",
380 (true, false) => " :",
381 (false, true) => ": ",
382 (false, false) => ":",
387 fn bin_search_test() {
388 let closure = |i| match i {
390 j if j > 4 => Err(Ordering::Less),
391 j if j < 4 => Err(Ordering::Greater),
395 assert_eq!(Some(()), binary_search(1, 10, &closure));
396 assert_eq!(None, binary_search(1, 3, &closure));
397 assert_eq!(Some(()), binary_search(0, 44, &closure));
398 assert_eq!(Some(()), binary_search(4, 125, &closure));
399 assert_eq!(None, binary_search(6, 100, &closure));
402 pub fn left_most_sub_expr(e: &ast::Expr) -> &ast::Expr {
404 ast::ExprKind::InPlace(ref e, _) |
405 ast::ExprKind::Call(ref e, _) |
406 ast::ExprKind::Binary(_, ref e, _) |
407 ast::ExprKind::Cast(ref e, _) |
408 ast::ExprKind::Type(ref e, _) |
409 ast::ExprKind::Assign(ref e, _) |
410 ast::ExprKind::AssignOp(_, ref e, _) |
411 ast::ExprKind::Field(ref e, _) |
412 ast::ExprKind::TupField(ref e, _) |
413 ast::ExprKind::Index(ref e, _) |
414 ast::ExprKind::Range(Some(ref e), _, _) |
415 ast::ExprKind::Try(ref e) => left_most_sub_expr(e),