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 itertools::Itertools;
16 use syntax::ast::{self, Visibility, Attribute, MetaItem, MetaItemKind, Path};
17 use syntax::codemap::BytePos;
21 use rewrite::{Rewrite, RewriteContext};
25 // Computes the length of a string's last line, minus offset.
26 pub fn extra_offset(text: &str, offset: Indent) -> usize {
27 match text.rfind('\n') {
28 // 1 for newline character
29 Some(idx) => text.len().checked_sub(idx + 1 + offset.width()).unwrap_or(0),
34 // Uses Cow to avoid allocating in the common cases.
35 pub fn format_visibility(vis: &Visibility) -> Cow<'static, str> {
37 Visibility::Public => Cow::from("pub "),
38 Visibility::Inherited => Cow::from(""),
39 Visibility::Crate(_) => Cow::from("pub(crate) "),
40 Visibility::Restricted { ref path, .. } => {
41 let Path { global, ref segments, .. } = **path;
42 let prefix = if global { "::" } else { "" };
43 let mut segments_iter = segments.iter().map(|seg| seg.identifier.name.as_str());
45 Cow::from(format!("pub({}{}) ", prefix, segments_iter.join("::")))
51 pub fn format_unsafety(unsafety: ast::Unsafety) -> &'static str {
53 ast::Unsafety::Unsafe => "unsafe ",
54 ast::Unsafety::Normal => "",
59 pub fn format_mutability(mutability: ast::Mutability) -> &'static str {
61 ast::Mutability::Mutable => "mut ",
62 ast::Mutability::Immutable => "",
67 pub fn format_abi(abi: abi::Abi, explicit_abi: bool) -> String {
68 if abi == abi::Abi::C && !explicit_abi {
71 format!("extern {} ", abi)
75 // The width of the first line in s.
77 pub fn first_line_width(s: &str) -> usize {
84 // The width of the last line in s.
86 pub fn last_line_width(s: &str) -> usize {
88 Some(n) => s.len() - n - 1,
93 pub fn trimmed_last_line_width(s: &str) -> usize {
95 Some(n) => s[(n + 1)..].trim().len(),
96 None => s.trim().len(),
101 fn is_skip(meta_item: &MetaItem) -> bool {
102 match meta_item.node {
103 MetaItemKind::Word(ref s) => *s == SKIP_ANNOTATION,
104 MetaItemKind::List(ref s, ref l) => *s == "cfg_attr" && l.len() == 2 && is_skip(&l[1]),
110 pub fn contains_skip(attrs: &[Attribute]) -> bool {
111 attrs.iter().any(|a| is_skip(&a.node.value))
114 // Find the end of a TyParam
116 pub fn end_typaram(typaram: &ast::TyParam) -> BytePos {
119 .map_or(typaram.span, |bound| {
121 ast::RegionTyParamBound(ref lt) => lt.span,
122 ast::TraitTyParamBound(ref prt, _) => prt.span,
129 pub fn semicolon_for_expr(expr: &ast::Expr) -> bool {
131 ast::ExprKind::Ret(..) |
132 ast::ExprKind::Again(..) |
133 ast::ExprKind::Break(..) => true,
139 pub fn semicolon_for_stmt(stmt: &ast::Stmt) -> bool {
141 ast::StmtKind::Semi(ref expr, _) => {
143 ast::ExprKind::While(..) |
144 ast::ExprKind::WhileLet(..) |
145 ast::ExprKind::Loop(..) |
146 ast::ExprKind::ForLoop(..) => false,
150 ast::StmtKind::Expr(..) => false,
156 pub fn trim_newlines(input: &str) -> &str {
157 match input.find(|c| c != '\n' && c != '\r') {
159 let end = input.rfind(|c| c != '\n' && c != '\r').unwrap_or(0) + 1;
166 // Macro for deriving implementations of Decodable for enums
168 macro_rules! impl_enum_decodable {
169 ( $e:ident, $( $x:ident ),* ) => {
170 impl ::rustc_serialize::Decodable for $e {
171 fn decode<D: ::rustc_serialize::Decoder>(d: &mut D) -> Result<Self, D::Error> {
172 use std::ascii::AsciiExt;
173 let s = try!(d.read_str());
175 if stringify!($x).eq_ignore_ascii_case(&s) {
179 Err(d.error("Bad variant"))
183 impl ::std::str::FromStr for $e {
184 type Err = &'static str;
186 fn from_str(s: &str) -> Result<Self, Self::Err> {
187 use std::ascii::AsciiExt;
189 if stringify!($x).eq_ignore_ascii_case(s) {
197 impl ::config::ConfigType for $e {
198 fn doc_hint() -> String {
199 let mut variants = Vec::new();
201 variants.push(stringify!($x));
203 format!("[{}]", variants.join("|"))
209 // Same as try!, but for Option
211 macro_rules! try_opt {
212 ($expr:expr) => (match $expr {
214 None => { return None; }
220 match writeln!(&mut ::std::io::stderr(), $($arg)* ) {
222 Err(x) => panic!("Unable to write to stderr: {}", x),
228 // Wraps string-like values in an Option. Returns Some when the string adheres
229 // to the Rewrite constraints defined for the Rewrite trait and else otherwise.
230 pub fn wrap_str<S: AsRef<str>>(s: S, max_width: usize, width: usize, offset: Indent) -> Option<S> {
232 let snippet = s.as_ref();
234 if !snippet.contains('\n') && snippet.len() > width {
237 let mut lines = snippet.lines();
239 // The caller of this function has already placed `offset`
240 // characters on the first line.
241 let first_line_max_len = try_opt!(max_width.checked_sub(offset.width()));
242 if lines.next().unwrap().len() > first_line_max_len {
246 // The other lines must fit within the maximum width.
247 if lines.find(|line| line.len() > max_width).is_some() {
251 // `width` is the maximum length of the last line, excluding
253 // A special check for the last line, since the caller may
254 // place trailing characters on this line.
255 if snippet.lines().rev().next().unwrap().len() > offset.width() + width {
264 impl Rewrite for String {
265 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
266 wrap_str(self, context.config.max_width, width, offset).map(ToOwned::to_owned)
270 // Binary search in integer range. Returns the first Ok value returned by the
272 // The callback takes an integer and returns either an Ok, or an Err indicating
273 // whether the `guess' was too high (Ordering::Less), or too low.
274 // This function is guaranteed to try to the hi value first.
275 pub fn binary_search<C, T>(mut lo: usize, mut hi: usize, callback: C) -> Option<T>
276 where C: Fn(usize) -> Result<T, Ordering>
281 match callback(middle) {
282 Ok(val) => return Some(val),
283 Err(Ordering::Less) => {
290 middle = (hi + lo) / 2;
297 fn bin_search_test() {
301 j if j > 4 => Err(Ordering::Less),
302 j if j < 4 => Err(Ordering::Greater),
307 assert_eq!(Some(()), binary_search(1, 10, &closure));
308 assert_eq!(None, binary_search(1, 3, &closure));
309 assert_eq!(Some(()), binary_search(0, 44, &closure));
310 assert_eq!(Some(()), binary_search(4, 125, &closure));
311 assert_eq!(None, binary_search(6, 100, &closure));
314 pub fn left_most_sub_expr(e: &ast::Expr) -> &ast::Expr {
316 ast::ExprKind::InPlace(ref e, _) |
317 ast::ExprKind::Call(ref e, _) |
318 ast::ExprKind::Binary(_, ref e, _) |
319 ast::ExprKind::Cast(ref e, _) |
320 ast::ExprKind::Type(ref e, _) |
321 ast::ExprKind::Assign(ref e, _) |
322 ast::ExprKind::AssignOp(_, ref e, _) |
323 ast::ExprKind::Field(ref e, _) |
324 ast::ExprKind::TupField(ref e, _) |
325 ast::ExprKind::Index(ref e, _) |
326 ast::ExprKind::Range(Some(ref e), _, _) => left_most_sub_expr(e),
327 // FIXME needs Try in Syntex
328 // ast::ExprKind::Try(ref f) => left_most_sub_expr(e),