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.
11 use std::cmp::Ordering;
13 use syntax::ast::{self, Visibility, Attribute, MetaItem, MetaItemKind};
14 use syntax::codemap::{CodeMap, Span, BytePos};
18 use comment::FindUncommented;
19 use rewrite::{Rewrite, RewriteContext};
23 pub trait CodeMapSpanUtils {
24 fn span_after(&self, original: Span, needle: &str) -> BytePos;
25 fn span_after_last(&self, original: Span, needle: &str) -> BytePos;
26 fn span_before(&self, original: Span, needle: &str) -> BytePos;
29 impl CodeMapSpanUtils for CodeMap {
31 fn span_after(&self, original: Span, needle: &str) -> BytePos {
32 let snippet = self.span_to_snippet(original).unwrap();
33 let offset = snippet.find_uncommented(needle).unwrap() + needle.len();
35 original.lo + BytePos(offset as u32)
39 fn span_after_last(&self, original: Span, needle: &str) -> BytePos {
40 let snippet = self.span_to_snippet(original).unwrap();
43 while let Some(additional_offset) = snippet[offset..].find_uncommented(needle) {
44 offset += additional_offset + needle.len();
47 original.lo + BytePos(offset as u32)
51 fn span_before(&self, original: Span, needle: &str) -> BytePos {
52 let snippet = self.span_to_snippet(original).unwrap();
53 let offset = snippet.find_uncommented(needle).unwrap();
55 original.lo + BytePos(offset as u32)
59 // Computes the length of a string's last line, minus offset.
61 pub fn extra_offset(text: &str, offset: Indent) -> usize {
62 match text.rfind('\n') {
63 // 1 for newline character
64 Some(idx) => text.len() - idx - 1 - offset.width(),
70 pub fn format_visibility(vis: Visibility) -> &'static str {
72 Visibility::Public => "pub ",
73 Visibility::Inherited => "",
78 pub fn format_unsafety(unsafety: ast::Unsafety) -> &'static str {
80 ast::Unsafety::Unsafe => "unsafe ",
81 ast::Unsafety::Normal => "",
86 pub fn format_mutability(mutability: ast::Mutability) -> &'static str {
88 ast::Mutability::Mutable => "mut ",
89 ast::Mutability::Immutable => "",
94 // FIXME(#451): include "C"?
95 pub fn format_abi(abi: abi::Abi) -> String {
96 format!("extern {} ", abi)
99 // The width of the first line in s.
101 pub fn first_line_width(s: &str) -> usize {
108 // The width of the last line in s.
110 pub fn last_line_width(s: &str) -> usize {
111 match s.rfind('\n') {
112 Some(n) => s.len() - n - 1,
118 fn is_skip(meta_item: &MetaItem) -> bool {
119 match meta_item.node {
120 MetaItemKind::Word(ref s) => *s == SKIP_ANNOTATION,
121 MetaItemKind::List(ref s, ref l) => *s == "cfg_attr" && l.len() == 2 && is_skip(&l[1]),
127 pub fn contains_skip(attrs: &[Attribute]) -> bool {
128 attrs.iter().any(|a| is_skip(&a.node.value))
131 // Find the end of a TyParam
133 pub fn end_typaram(typaram: &ast::TyParam) -> BytePos {
136 .map_or(typaram.span, |bound| {
138 ast::RegionTyParamBound(ref lt) => lt.span,
139 ast::TraitTyParamBound(ref prt, _) => prt.span,
146 pub fn semicolon_for_expr(expr: &ast::Expr) -> bool {
148 ast::ExprKind::Ret(..) |
149 ast::ExprKind::Again(..) |
150 ast::ExprKind::Break(..) => true,
156 pub fn semicolon_for_stmt(stmt: &ast::Stmt) -> bool {
158 ast::StmtKind::Semi(ref expr, _) => {
160 ast::ExprKind::While(..) |
161 ast::ExprKind::WhileLet(..) |
162 ast::ExprKind::Loop(..) |
163 ast::ExprKind::ForLoop(..) => false,
167 ast::StmtKind::Expr(..) => false,
173 pub fn trim_newlines(input: &str) -> &str {
174 match input.find(|c| c != '\n' && c != '\r') {
176 let end = input.rfind(|c| c != '\n' && c != '\r').unwrap_or(0) + 1;
184 #[cfg(target_pointer_width="64")]
185 // Based on the trick layed out at
186 // http://graphics.stanford.edu/~seander/bithacks.html#RoundUpPowerOf2
187 pub fn round_up_to_power_of_two(mut x: usize) -> usize {
188 x = x.wrapping_sub(1);
199 #[cfg(target_pointer_width="32")]
200 pub fn round_up_to_power_of_two(mut x: usize) -> usize {
201 x = x.wrapping_sub(1);
210 // Macro for deriving implementations of Decodable for enums
212 macro_rules! impl_enum_decodable {
213 ( $e:ident, $( $x:ident ),* ) => {
214 impl ::rustc_serialize::Decodable for $e {
215 fn decode<D: ::rustc_serialize::Decoder>(d: &mut D) -> Result<Self, D::Error> {
216 use std::ascii::AsciiExt;
217 let s = try!(d.read_str());
219 if stringify!($x).eq_ignore_ascii_case(&s) {
223 Err(d.error("Bad variant"))
227 impl ::std::str::FromStr for $e {
228 type Err = &'static str;
230 fn from_str(s: &str) -> Result<Self, Self::Err> {
231 use std::ascii::AsciiExt;
233 if stringify!($x).eq_ignore_ascii_case(s) {
241 impl ::config::ConfigType for $e {
242 fn get_variant_names() -> String {
243 let mut variants = Vec::new();
245 variants.push(stringify!($x));
247 format!("[{}]", variants.join("|"))
253 // Same as try!, but for Option
255 macro_rules! try_opt {
256 ($expr:expr) => (match $expr {
258 None => { return None; }
262 // Wraps string-like values in an Option. Returns Some when the string adheres
263 // to the Rewrite constraints defined for the Rewrite trait and else otherwise.
264 pub fn wrap_str<S: AsRef<str>>(s: S, max_width: usize, width: usize, offset: Indent) -> Option<S> {
266 let snippet = s.as_ref();
268 if !snippet.contains('\n') && snippet.len() > width {
271 let mut lines = snippet.lines();
273 // The caller of this function has already placed `offset`
274 // characters on the first line.
275 let first_line_max_len = try_opt!(max_width.checked_sub(offset.width()));
276 if lines.next().unwrap().len() > first_line_max_len {
280 // The other lines must fit within the maximum width.
281 if lines.find(|line| line.len() > max_width).is_some() {
285 // `width` is the maximum length of the last line, excluding
287 // A special check for the last line, since the caller may
288 // place trailing characters on this line.
289 if snippet.lines().rev().next().unwrap().len() > offset.width() + width {
298 impl Rewrite for String {
299 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
300 wrap_str(self, context.config.max_width, width, offset).map(ToOwned::to_owned)
304 // Binary search in integer range. Returns the first Ok value returned by the
306 // The callback takes an integer and returns either an Ok, or an Err indicating
307 // whether the `guess' was too high (Ordering::Less), or too low.
308 // This function is guaranteed to try to the hi value first.
309 pub fn binary_search<C, T>(mut lo: usize, mut hi: usize, callback: C) -> Option<T>
310 where C: Fn(usize) -> Result<T, Ordering>
315 match callback(middle) {
316 Ok(val) => return Some(val),
317 Err(Ordering::Less) => {
324 middle = (hi + lo) / 2;
331 fn bin_search_test() {
335 j if j > 4 => Err(Ordering::Less),
336 j if j < 4 => Err(Ordering::Greater),
341 assert_eq!(Some(()), binary_search(1, 10, &closure));
342 assert_eq!(None, binary_search(1, 3, &closure));
343 assert_eq!(Some(()), binary_search(0, 44, &closure));
344 assert_eq!(Some(()), binary_search(4, 125, &closure));
345 assert_eq!(None, binary_search(6, 100, &closure));
349 fn power_rounding() {
350 assert_eq!(0, round_up_to_power_of_two(0));
351 assert_eq!(1, round_up_to_power_of_two(1));
352 assert_eq!(64, round_up_to_power_of_two(33));
353 assert_eq!(256, round_up_to_power_of_two(256));