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::{CodeMap, Span, BytePos};
21 use comment::FindUncommented;
22 use rewrite::{Rewrite, RewriteContext};
26 pub trait CodeMapSpanUtils {
27 fn span_after(&self, original: Span, needle: &str) -> BytePos;
28 fn span_after_last(&self, original: Span, needle: &str) -> BytePos;
29 fn span_before(&self, original: Span, needle: &str) -> BytePos;
32 impl CodeMapSpanUtils for CodeMap {
34 fn span_after(&self, original: Span, needle: &str) -> BytePos {
35 let snippet = self.span_to_snippet(original).unwrap();
36 let offset = snippet.find_uncommented(needle).unwrap() + needle.len();
38 original.lo + BytePos(offset as u32)
42 fn span_after_last(&self, original: Span, needle: &str) -> BytePos {
43 let snippet = self.span_to_snippet(original).unwrap();
46 while let Some(additional_offset) = snippet[offset..].find_uncommented(needle) {
47 offset += additional_offset + needle.len();
50 original.lo + BytePos(offset as u32)
54 fn span_before(&self, original: Span, needle: &str) -> BytePos {
55 let snippet = self.span_to_snippet(original).unwrap();
56 let offset = snippet.find_uncommented(needle).unwrap();
58 original.lo + BytePos(offset as u32)
62 // Computes the length of a string's last line, minus offset.
64 pub fn extra_offset(text: &str, offset: Indent) -> usize {
65 match text.rfind('\n') {
66 // 1 for newline character
67 Some(idx) => text.len() - idx - 1 - offset.width(),
72 // Uses Cow to avoid allocating in the common cases.
73 pub fn format_visibility(vis: &Visibility) -> Cow<'static, str> {
75 Visibility::Public => Cow::from("pub "),
76 Visibility::Inherited => Cow::from(""),
77 Visibility::Crate(_) => Cow::from("pub(crate) "),
78 Visibility::Restricted { ref path, .. } => {
79 let Path { global, ref segments, .. } = **path;
80 let prefix = if global {
85 let mut segments_iter = segments.iter().map(|seg| seg.identifier.name.as_str());
87 Cow::from(format!("pub({}{}) ", prefix, segments_iter.join("::")))
93 pub fn format_unsafety(unsafety: ast::Unsafety) -> &'static str {
95 ast::Unsafety::Unsafe => "unsafe ",
96 ast::Unsafety::Normal => "",
101 pub fn format_mutability(mutability: ast::Mutability) -> &'static str {
103 ast::Mutability::Mutable => "mut ",
104 ast::Mutability::Immutable => "",
109 pub fn format_abi(abi: abi::Abi, explicit_abi: bool) -> String {
110 if abi == abi::Abi::C && !explicit_abi {
113 format!("extern {} ", abi)
117 // The width of the first line in s.
119 pub fn first_line_width(s: &str) -> usize {
126 // The width of the last line in s.
128 pub fn last_line_width(s: &str) -> usize {
129 match s.rfind('\n') {
130 Some(n) => s.len() - n - 1,
135 pub fn trimmed_last_line_width(s: &str) -> usize {
136 match s.rfind('\n') {
137 Some(n) => s[(n + 1)..].trim().len(),
138 None => s.trim().len(),
143 fn is_skip(meta_item: &MetaItem) -> bool {
144 match meta_item.node {
145 MetaItemKind::Word(ref s) => *s == SKIP_ANNOTATION,
146 MetaItemKind::List(ref s, ref l) => *s == "cfg_attr" && l.len() == 2 && is_skip(&l[1]),
152 pub fn contains_skip(attrs: &[Attribute]) -> bool {
153 attrs.iter().any(|a| is_skip(&a.node.value))
156 // Find the end of a TyParam
158 pub fn end_typaram(typaram: &ast::TyParam) -> BytePos {
161 .map_or(typaram.span, |bound| {
163 ast::RegionTyParamBound(ref lt) => lt.span,
164 ast::TraitTyParamBound(ref prt, _) => prt.span,
171 pub fn semicolon_for_expr(expr: &ast::Expr) -> bool {
173 ast::ExprKind::Ret(..) |
174 ast::ExprKind::Again(..) |
175 ast::ExprKind::Break(..) => true,
181 pub fn semicolon_for_stmt(stmt: &ast::Stmt) -> bool {
183 ast::StmtKind::Semi(ref expr, _) => {
185 ast::ExprKind::While(..) |
186 ast::ExprKind::WhileLet(..) |
187 ast::ExprKind::Loop(..) |
188 ast::ExprKind::ForLoop(..) => false,
192 ast::StmtKind::Expr(..) => false,
198 pub fn trim_newlines(input: &str) -> &str {
199 match input.find(|c| c != '\n' && c != '\r') {
201 let end = input.rfind(|c| c != '\n' && c != '\r').unwrap_or(0) + 1;
208 // Macro for deriving implementations of Decodable for enums
210 macro_rules! impl_enum_decodable {
211 ( $e:ident, $( $x:ident ),* ) => {
212 impl ::rustc_serialize::Decodable for $e {
213 fn decode<D: ::rustc_serialize::Decoder>(d: &mut D) -> Result<Self, D::Error> {
214 use std::ascii::AsciiExt;
215 let s = try!(d.read_str());
217 if stringify!($x).eq_ignore_ascii_case(&s) {
221 Err(d.error("Bad variant"))
225 impl ::std::str::FromStr for $e {
226 type Err = &'static str;
228 fn from_str(s: &str) -> Result<Self, Self::Err> {
229 use std::ascii::AsciiExt;
231 if stringify!($x).eq_ignore_ascii_case(s) {
239 impl ::config::ConfigType for $e {
240 fn doc_hint() -> String {
241 let mut variants = Vec::new();
243 variants.push(stringify!($x));
245 format!("[{}]", variants.join("|"))
251 // Same as try!, but for Option
253 macro_rules! try_opt {
254 ($expr:expr) => (match $expr {
256 None => { return None; }
262 match writeln!(&mut ::std::io::stderr(), $($arg)* ) {
264 Err(x) => panic!("Unable to write to stderr: {}", x),
270 // Wraps string-like values in an Option. Returns Some when the string adheres
271 // to the Rewrite constraints defined for the Rewrite trait and else otherwise.
272 pub fn wrap_str<S: AsRef<str>>(s: S, max_width: usize, width: usize, offset: Indent) -> Option<S> {
274 let snippet = s.as_ref();
276 if !snippet.contains('\n') && snippet.len() > width {
279 let mut lines = snippet.lines();
281 // The caller of this function has already placed `offset`
282 // characters on the first line.
283 let first_line_max_len = try_opt!(max_width.checked_sub(offset.width()));
284 if lines.next().unwrap().len() > first_line_max_len {
288 // The other lines must fit within the maximum width.
289 if lines.find(|line| line.len() > max_width).is_some() {
293 // `width` is the maximum length of the last line, excluding
295 // A special check for the last line, since the caller may
296 // place trailing characters on this line.
297 if snippet.lines().rev().next().unwrap().len() > offset.width() + width {
306 impl Rewrite for String {
307 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
308 wrap_str(self, context.config.max_width, width, offset).map(ToOwned::to_owned)
312 // Binary search in integer range. Returns the first Ok value returned by the
314 // The callback takes an integer and returns either an Ok, or an Err indicating
315 // whether the `guess' was too high (Ordering::Less), or too low.
316 // This function is guaranteed to try to the hi value first.
317 pub fn binary_search<C, T>(mut lo: usize, mut hi: usize, callback: C) -> Option<T>
318 where C: Fn(usize) -> Result<T, Ordering>
323 match callback(middle) {
324 Ok(val) => return Some(val),
325 Err(Ordering::Less) => {
332 middle = (hi + lo) / 2;
339 fn bin_search_test() {
343 j if j > 4 => Err(Ordering::Less),
344 j if j < 4 => Err(Ordering::Greater),
349 assert_eq!(Some(()), binary_search(1, 10, &closure));
350 assert_eq!(None, binary_search(1, 3, &closure));
351 assert_eq!(Some(()), binary_search(0, 44, &closure));
352 assert_eq!(Some(()), binary_search(4, 125, &closure));
353 assert_eq!(None, binary_search(6, 100, &closure));
356 pub fn left_most_sub_expr(e: &ast::Expr) -> &ast::Expr {
358 ast::ExprKind::InPlace(ref e, _) |
359 ast::ExprKind::Call(ref e, _) |
360 ast::ExprKind::Binary(_, ref e, _) |
361 ast::ExprKind::Cast(ref e, _) |
362 ast::ExprKind::Type(ref e, _) |
363 ast::ExprKind::Assign(ref e, _) |
364 ast::ExprKind::AssignOp(_, ref e, _) |
365 ast::ExprKind::Field(ref e, _) |
366 ast::ExprKind::TupField(ref e, _) |
367 ast::ExprKind::Index(ref e, _) |
368 ast::ExprKind::Range(Some(ref e), _, _) => left_most_sub_expr(e),
369 // FIXME needs Try in Syntex
370 // ast::ExprKind::Try(ref f) => left_most_sub_expr(e),