|
| 1 | +// Copyright 2013 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. |
| 4 | +// |
| 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. |
| 10 | + |
| 11 | +use prelude::*; |
| 12 | + |
| 13 | +use cast; |
| 14 | +use int; |
| 15 | +use rt::io::Decorator; |
| 16 | +use rt::io::mem::MemWriter; |
| 17 | +use rt::io; |
| 18 | +use str; |
| 19 | +use sys; |
| 20 | +use uint; |
| 21 | +use util; |
| 22 | +use vec; |
| 23 | + |
| 24 | +pub mod parse; |
| 25 | +pub mod rt; |
| 26 | + |
| 27 | +/// A struct to represent both where to emit formatting strings to and how they |
| 28 | +/// should be formatted. A mutable version of this is passed to all formatting |
| 29 | +/// traits. |
| 30 | +pub struct Formatter<'self> { |
| 31 | + /// Flags for formatting (packed version of rt::Flag) |
| 32 | + flags: uint, |
| 33 | + /// Character used as 'fill' whenever there is alignment |
| 34 | + fill: char, |
| 35 | + /// Boolean indication of whether the output should be left-aligned |
| 36 | + alignleft: bool, |
| 37 | + /// Optionally specified integer width that the output should be |
| 38 | + width: Option<uint>, |
| 39 | + /// Optionally specified precision for numeric types |
| 40 | + precision: Option<uint>, |
| 41 | + |
| 42 | + /// Output buffer. |
| 43 | + buf: &'self mut io::Writer, |
| 44 | + |
| 45 | + priv curarg: vec::VecIterator<'self, Argument<'self>>, |
| 46 | + priv args: &'self [Argument<'self>], |
| 47 | +} |
| 48 | + |
| 49 | +/// This struct represents the generic "argument" which is taken by the Xprintf |
| 50 | +/// family of functions. It contains a function to format the given value. At |
| 51 | +/// compile time it is ensured that the function and the value have the correct |
| 52 | +/// types, and then this struct is used to canonicalize arguments to one type. |
| 53 | +pub struct Argument<'self> { |
| 54 | + priv formatter: extern "Rust" fn(&util::Void, &mut Formatter), |
| 55 | + priv value: &'self util::Void, |
| 56 | +} |
| 57 | + |
| 58 | +#[allow(missing_doc)] |
| 59 | +pub trait Bool { fn fmt(&Self, &mut Formatter); } |
| 60 | +#[allow(missing_doc)] |
| 61 | +pub trait Char { fn fmt(&Self, &mut Formatter); } |
| 62 | +#[allow(missing_doc)] |
| 63 | +pub trait Signed { fn fmt(&Self, &mut Formatter); } |
| 64 | +#[allow(missing_doc)] |
| 65 | +pub trait Unsigned { fn fmt(&Self, &mut Formatter); } |
| 66 | +#[allow(missing_doc)] |
| 67 | +pub trait Octal { fn fmt(&Self, &mut Formatter); } |
| 68 | +#[allow(missing_doc)] |
| 69 | +pub trait Binary { fn fmt(&Self, &mut Formatter); } |
| 70 | +#[allow(missing_doc)] |
| 71 | +pub trait LowerHex { fn fmt(&Self, &mut Formatter); } |
| 72 | +#[allow(missing_doc)] |
| 73 | +pub trait UpperHex { fn fmt(&Self, &mut Formatter); } |
| 74 | +#[allow(missing_doc)] |
| 75 | +pub trait String { fn fmt(&Self, &mut Formatter); } |
| 76 | +#[allow(missing_doc)] |
| 77 | +pub trait Poly { fn fmt(&Self, &mut Formatter); } |
| 78 | +#[allow(missing_doc)] |
| 79 | +pub trait Pointer { fn fmt(&Self, &mut Formatter); } |
| 80 | + |
| 81 | +/// The sprintf function takes a precompiled format string and a list of |
| 82 | +/// arguments, to return the resulting formatted string. |
| 83 | +/// |
| 84 | +/// This is currently an unsafe function because the types of all arguments |
| 85 | +/// aren't verified by immediate callers of this function. This currently does |
| 86 | +/// not validate that the correct types of arguments are specified for each |
| 87 | +/// format specifier, nor that each argument itself contains the right function |
| 88 | +/// for formatting the right type value. Because of this, the function is marked |
| 89 | +/// as `unsafe` if this is being called manually. |
| 90 | +/// |
| 91 | +/// Thankfully the rust compiler provides the macro `ifmt!` which will perform |
| 92 | +/// all of this validation at compile-time and provides a safe interface for |
| 93 | +/// invoking this function. |
| 94 | +/// |
| 95 | +/// # Arguments |
| 96 | +/// |
| 97 | +/// * fmts - the precompiled format string to emit. |
| 98 | +/// * args - the list of arguments to the format string. These are only the |
| 99 | +/// positional arguments (not named) |
| 100 | +/// |
| 101 | +/// Note that this function assumes that there are enough arguments for the |
| 102 | +/// format string. |
| 103 | +pub unsafe fn sprintf(fmt: &[rt::Piece], args: &[Argument]) -> ~str { |
| 104 | + let output = MemWriter::new(); |
| 105 | + { |
| 106 | + let mut formatter = Formatter { |
| 107 | + flags: 0, |
| 108 | + width: None, |
| 109 | + precision: None, |
| 110 | + // FIXME(#8248): shouldn't need a transmute |
| 111 | + buf: cast::transmute(&output as &io::Writer), |
| 112 | + alignleft: false, |
| 113 | + fill: ' ', |
| 114 | + args: args, |
| 115 | + curarg: args.iter(), |
| 116 | + }; |
| 117 | + for piece in fmt.iter() { |
| 118 | + formatter.run(piece, None); |
| 119 | + } |
| 120 | + } |
| 121 | + return str::from_bytes_owned(output.inner()); |
| 122 | +} |
| 123 | + |
| 124 | +impl<'self> Formatter<'self> { |
| 125 | + fn run(&mut self, piece: &rt::Piece, cur: Option<&str>) { |
| 126 | + let setcount = |slot: &mut Option<uint>, cnt: &parse::Count| { |
| 127 | + match *cnt { |
| 128 | + parse::CountIs(n) => { *slot = Some(n); } |
| 129 | + parse::CountImplied => { *slot = None; } |
| 130 | + parse::CountIsParam(i) => { |
| 131 | + let v = self.args[i].value; |
| 132 | + unsafe { *slot = Some(*(v as *util::Void as *uint)); } |
| 133 | + } |
| 134 | + parse::CountIsNextParam => { |
| 135 | + let v = self.curarg.next().unwrap().value; |
| 136 | + unsafe { *slot = Some(*(v as *util::Void as *uint)); } |
| 137 | + } |
| 138 | + } |
| 139 | + }; |
| 140 | + |
| 141 | + match *piece { |
| 142 | + rt::String(s) => { self.buf.write(s.as_bytes()); } |
| 143 | + rt::CurrentArgument(()) => { self.buf.write(cur.unwrap().as_bytes()); } |
| 144 | + rt::Argument(ref arg) => { |
| 145 | + // Fill in the format parameters into the formatter |
| 146 | + self.fill = arg.format.fill; |
| 147 | + self.alignleft = arg.format.alignleft; |
| 148 | + self.flags = arg.format.flags; |
| 149 | + setcount(&mut self.width, &arg.format.width); |
| 150 | + setcount(&mut self.precision, &arg.format.precision); |
| 151 | + |
| 152 | + // Extract the correct argument |
| 153 | + let value = match arg.position { |
| 154 | + rt::ArgumentNext => { *self.curarg.next().unwrap() } |
| 155 | + rt::ArgumentIs(i) => self.args[i], |
| 156 | + }; |
| 157 | + |
| 158 | + // Then actually do some printing |
| 159 | + match arg.method { |
| 160 | + None => { (value.formatter)(value.value, self); } |
| 161 | + Some(ref method) => { self.execute(*method, value); } |
| 162 | + } |
| 163 | + } |
| 164 | + } |
| 165 | + } |
| 166 | + |
| 167 | + fn execute(&mut self, method: &rt::Method, arg: Argument) { |
| 168 | + match *method { |
| 169 | + // Pluralization is selection upon a numeric value specified as the |
| 170 | + // parameter. |
| 171 | + rt::Plural(offset, ref selectors, ref default) => { |
| 172 | + // This is validated at compile-time to be a pointer to a |
| 173 | + // '&uint' value. |
| 174 | + let value: &uint = unsafe { cast::transmute(arg.value) }; |
| 175 | + let value = *value; |
| 176 | + |
| 177 | + // First, attempt to match against explicit values without the |
| 178 | + // offsetted value |
| 179 | + for s in selectors.iter() { |
| 180 | + match s.selector { |
| 181 | + Right(val) if value == val => { |
| 182 | + return self.runplural(value, s.result); |
| 183 | + } |
| 184 | + _ => {} |
| 185 | + } |
| 186 | + } |
| 187 | + |
| 188 | + // Next, offset the value and attempt to match against the |
| 189 | + // keyword selectors. |
| 190 | + let value = value - match offset { Some(i) => i, None => 0 }; |
| 191 | + for s in selectors.iter() { |
| 192 | + let run = match s.selector { |
| 193 | + Left(parse::Zero) => value == 0, |
| 194 | + Left(parse::One) => value == 1, |
| 195 | + Left(parse::Two) => value == 2, |
| 196 | + |
| 197 | + // XXX: Few/Many should have a user-specified boundary |
| 198 | + // One possible option would be in the function |
| 199 | + // pointer of the 'arg: Argument' struct. |
| 200 | + Left(parse::Few) => value < 8, |
| 201 | + Left(parse::Many) => value >= 8, |
| 202 | + |
| 203 | + Right(*) => false |
| 204 | + }; |
| 205 | + if run { |
| 206 | + return self.runplural(value, s.result); |
| 207 | + } |
| 208 | + } |
| 209 | + |
| 210 | + self.runplural(value, *default); |
| 211 | + } |
| 212 | + |
| 213 | + // Select is just a matching against the string specified. |
| 214 | + rt::Select(ref selectors, ref default) => { |
| 215 | + // This is validated at compile-time to be a pointer to a |
| 216 | + // string slice, |
| 217 | + let value: & &str = unsafe { cast::transmute(arg.value) }; |
| 218 | + let value = *value; |
| 219 | + |
| 220 | + for s in selectors.iter() { |
| 221 | + if s.selector == value { |
| 222 | + for piece in s.result.iter() { |
| 223 | + self.run(piece, Some(value)); |
| 224 | + } |
| 225 | + return; |
| 226 | + } |
| 227 | + } |
| 228 | + for piece in default.iter() { |
| 229 | + self.run(piece, Some(value)); |
| 230 | + } |
| 231 | + } |
| 232 | + } |
| 233 | + } |
| 234 | + |
| 235 | + fn runplural(&mut self, value: uint, pieces: &[rt::Piece]) { |
| 236 | + do uint::to_str_bytes(value, 10) |buf| { |
| 237 | + let valuestr = str::from_bytes_slice(buf); |
| 238 | + for piece in pieces.iter() { |
| 239 | + self.run(piece, Some(valuestr)); |
| 240 | + } |
| 241 | + } |
| 242 | + } |
| 243 | +} |
| 244 | + |
| 245 | +/// This is a function which calls are emitted to by the compiler itself to |
| 246 | +/// create the Argument structures that are passed into the `sprintf` function. |
| 247 | +#[doc(hidden)] |
| 248 | +pub fn argument<'a, T>(f: extern "Rust" fn(&T, &mut Formatter), |
| 249 | + t: &'a T) -> Argument<'a> { |
| 250 | + unsafe { |
| 251 | + Argument { |
| 252 | + formatter: cast::transmute(f), |
| 253 | + value: cast::transmute(t) |
| 254 | + } |
| 255 | + } |
| 256 | +} |
| 257 | + |
| 258 | +/// When the compiler determines that the type of an argument *must* be a string |
| 259 | +/// (such as for select), then it invokes this method. |
| 260 | +#[doc(hidden)] |
| 261 | +pub fn argumentstr<'a>(s: &'a &str) -> Argument<'a> { |
| 262 | + argument(String::fmt, s) |
| 263 | +} |
| 264 | + |
| 265 | +/// When the compiler determines that the type of an argument *must* be a uint |
| 266 | +/// (such as for plural), then it invokes this method. |
| 267 | +#[doc(hidden)] |
| 268 | +pub fn argumentuint<'a>(s: &'a uint) -> Argument<'a> { |
| 269 | + argument(Unsigned::fmt, s) |
| 270 | +} |
| 271 | + |
| 272 | +// Implementations of the core formatting traits |
| 273 | + |
| 274 | +impl Bool for bool { |
| 275 | + fn fmt(b: &bool, f: &mut Formatter) { |
| 276 | + String::fmt(&(if *b {"true"} else {"false"}), f); |
| 277 | + } |
| 278 | +} |
| 279 | + |
| 280 | +impl<'self> String for &'self str { |
| 281 | + fn fmt(s: & &'self str, f: &mut Formatter) { |
| 282 | + // XXX: formatting args |
| 283 | + f.buf.write(s.as_bytes()) |
| 284 | + } |
| 285 | +} |
| 286 | + |
| 287 | +impl Char for char { |
| 288 | + fn fmt(c: &char, f: &mut Formatter) { |
| 289 | + // XXX: formatting args |
| 290 | + // XXX: shouldn't require an allocation |
| 291 | + let mut s = ~""; |
| 292 | + s.push_char(*c); |
| 293 | + f.buf.write(s.as_bytes()); |
| 294 | + } |
| 295 | +} |
| 296 | + |
| 297 | +impl Signed for int { |
| 298 | + fn fmt(c: &int, f: &mut Formatter) { |
| 299 | + // XXX: formatting args |
| 300 | + do int::to_str_bytes(*c, 10) |buf| { |
| 301 | + f.buf.write(buf); |
| 302 | + } |
| 303 | + } |
| 304 | +} |
| 305 | + |
| 306 | +impl Unsigned for uint { |
| 307 | + fn fmt(c: &uint, f: &mut Formatter) { |
| 308 | + // XXX: formatting args |
| 309 | + do uint::to_str_bytes(*c, 10) |buf| { |
| 310 | + f.buf.write(buf); |
| 311 | + } |
| 312 | + } |
| 313 | +} |
| 314 | + |
| 315 | +impl Octal for uint { |
| 316 | + fn fmt(c: &uint, f: &mut Formatter) { |
| 317 | + // XXX: formatting args |
| 318 | + do uint::to_str_bytes(*c, 8) |buf| { |
| 319 | + f.buf.write(buf); |
| 320 | + } |
| 321 | + } |
| 322 | +} |
| 323 | + |
| 324 | +impl LowerHex for uint { |
| 325 | + fn fmt(c: &uint, f: &mut Formatter) { |
| 326 | + // XXX: formatting args |
| 327 | + do uint::to_str_bytes(*c, 16) |buf| { |
| 328 | + f.buf.write(buf); |
| 329 | + } |
| 330 | + } |
| 331 | +} |
| 332 | + |
| 333 | +impl UpperHex for uint { |
| 334 | + fn fmt(c: &uint, f: &mut Formatter) { |
| 335 | + // XXX: formatting args |
| 336 | + do uint::to_str_bytes(*c, 16) |buf| { |
| 337 | + let mut local = [0u8, ..16]; |
| 338 | + for (l, &b) in local.mut_iter().zip(buf.iter()) { |
| 339 | + *l = match b as char { |
| 340 | + 'a' .. 'f' => (b - 'a' as u8) + 'A' as u8, |
| 341 | + _ => b, |
| 342 | + }; |
| 343 | + } |
| 344 | + f.buf.write(local.slice_to(buf.len())); |
| 345 | + } |
| 346 | + } |
| 347 | +} |
| 348 | + |
| 349 | +impl<T> Poly for T { |
| 350 | + fn fmt(t: &T, f: &mut Formatter) { |
| 351 | + // XXX: formatting args |
| 352 | + let s = sys::log_str(t); |
| 353 | + f.buf.write(s.as_bytes()); |
| 354 | + } |
| 355 | +} |
| 356 | + |
| 357 | +// n.b. use 'const' to get an implementation for both '*mut' and '*' at the same |
| 358 | +// time. |
| 359 | +impl<T> Pointer for *const T { |
| 360 | + fn fmt(t: &*const T, f: &mut Formatter) { |
| 361 | + // XXX: formatting args |
| 362 | + f.buf.write("0x".as_bytes()); |
| 363 | + LowerHex::fmt(&(*t as uint), f); |
| 364 | + } |
| 365 | +} |
| 366 | + |
| 367 | +// If you expected tests to be here, look instead at the run-pass/ifmt.rs test, |
| 368 | +// it's a lot easier than creating all of the rt::Piece structures here. |
0 commit comments