fomat-macros-0.3.1/.gitignore010064400017500001750000000000311301261527000143030ustar0000000000000000target Cargo.lock .*.swp fomat-macros-0.3.1/Cargo.toml.orig010064400017500001750000000007471343454644100152330ustar0000000000000000[package] name = "fomat-macros" version = "0.3.1" authors = ["Michał Krasnoborski "] description = "Alternative syntax for print/write/format-like macros with a small templating language" documentation = "https://docs.rs/fomat-macros/0.3.1/fomat_macros/" repository = "https://github.com/krdln/fomat-macros" readme = "README.md" keywords = ["macro", "print", "template", "format", "interpolation"] license = "MIT" [dev-dependencies] tar = "0.4.9" tempdir = "0.3.5" fomat-macros-0.3.1/Cargo.toml0000644000000020240000000000000114600ustar00# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g. crates.io) dependencies # # If you believe there's an error in this file please file an # issue against the rust-lang/cargo repository. If you're # editing this file be aware that the upstream Cargo.toml # will likely look very different (and much more reasonable) [package] name = "fomat-macros" version = "0.3.1" authors = ["Michał Krasnoborski "] description = "Alternative syntax for print/write/format-like macros with a small templating language" documentation = "https://docs.rs/fomat-macros/0.3.1/fomat_macros/" readme = "README.md" keywords = ["macro", "print", "template", "format", "interpolation"] license = "MIT" repository = "https://github.com/krdln/fomat-macros" [dev-dependencies.tar] version = "0.4.9" [dev-dependencies.tempdir] version = "0.3.5" fomat-macros-0.3.1/LICENSE010064400017500001750000000020771301372125600133370ustar0000000000000000The MIT License (MIT) Copyright (c) 2016 Michał Krasnoborski Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. fomat-macros-0.3.1/README.md010064400017500001750000000064251343454644100136220ustar0000000000000000# fomat-macros [**documentation**](https://docs.rs/fomat-macros), [**crate**](https://crates.io/crates/fomat-macros) This crate provides alternative syntax for `write!`, `writeln!`, `print!`, `println!`, `eprint!`, `eprintln!` and `format!` macros from the [Rust](https://www.rust-lang.org/) standard library. The names of macros in this crate are formed by removing the letter `r` from their `std` counterparts: `wite!`, `witeln!`, `pint!`, `pintln!`, `epint!`, `epintln!`, `fomat!`. ## Installation Add this to your `Cargo.toml`: ```toml [dependencies] fomat-macros = "0.3.1" ``` And `use` the macros in your `.rs` file, eg.: ```rust use fomat_macros::pintln; ``` This version requires Rust 1.30. For support for older versions, [see version 0.2.1](https://github.com/krdln/fomat-macros/tree/v0.2.1). ## Examples ```rust pintln!("Hello, world!"); pintln!(); // empty line pintln!("The answer is "(40 + 2)); // parentheses use the Display trait pintln!([vec![1, 2, 3]] " -- numbers"); // brackets use the Debug trait ``` As you can see, instead the format string and arguments, we have a list of *things* to print without any separators. Each *thing* may be a string literal or an expression in brackets (apart of `()` and `[]` there are also braces `{}`, which may be used for more advanced format specifiers, see the docs). You can also use `if`, `if let`, `match` and `for` constructs inside the macro. They use regular Rust syntax, except everything inside the `{}` blocks will use the list-of-things-to-print syntax again. ```rust let list = vec![1, 2, 3]; let s = fomat!( for x in &list { (x) " :: " } "nil" ); // s == "1 :: 2 :: 3 :: nil" ``` For loops can also use an optional separator. [For details, see the docs.](https://docs.rs/fomat-macros/0.2/fomat_macros/#for-loops) There's also a shorthand for debugging, which prints both the expression and value. To enable, put `=` as the first character inside the any kind of brackets. ```rust let list = vec![1, 2, 3]; epintln!([=list]); // prints list = [1, 2, 3] ``` ## Why? What was the motivation to create this crate? * More locality – everything is written in the same order it will be printed. But that might a personal preference. * Easier to refactor – especially when you suddenly want to add a conditional print inside a long format string. Compare: ```rust let s = fomat!( "first line\n" if condition() { (foo) } "third line\n" ); ``` ```rust let s = { use ::std::fmt::Write; let mut s = "first line\n".to_owned(); if condition() { write!(s, "{}", foo).unwrap() } write!(s, "third line\n").unwrap(); s }; ``` * Speed! `fomat!` may be faster than `format!` (see `cargo bench`). That's because there's just one virtual call for single invocation of `fomat!` instead of one per each argument in `std::format!`. ## Limitations The `write!` and `writeln!` macros work on everything that has a `.write_fmt` method. This crate requires also the `.write_str` method. It works for any `io::Write` or `fmt::Write`, but in unlikely circumstances if you're using something custom, you should consult the source. ## Is it a templating language? Kind of, but please don't use it as HTML-templating language for security critical code, as it performs no escaping of special characters. fomat-macros-0.3.1/benches/bench.rs010064400017500001750000000077221343453144500153760ustar0000000000000000#![feature(test)] extern crate test; #[macro_use] extern crate fomat_macros; use test::{Bencher, black_box}; #[bench] fn literal_fomat(b: &mut Bencher) { b.iter(|| fomat!("Hello")) } #[bench] fn literal_format(b: &mut Bencher) { b.iter(|| format!("Hello")) } #[bench] fn short_fomat(b: &mut Bencher) { let world = "world"; b.iter(|| fomat!("Hello, "(black_box(world))"!") ) } #[bench] fn short_format(b: &mut Bencher) { let world = "world"; b.iter(|| format!("Hello, {}!", black_box(world)) ) } #[bench] fn two_fomat(b: &mut Bencher) { b.iter(|| fomat!("One"(3)(2+2))) } #[bench] fn two_format(b: &mut Bencher) { b.iter(|| format!("One{}{}", 3, 2+2)) } #[bench] fn three_fomat(b: &mut Bencher) { b.iter(|| fomat!("One"(2)(3)(2+2))) } #[bench] fn three_format(b: &mut Bencher) { b.iter(|| format!("One{}{}{}", 2, 3, 2+2)) } #[bench] fn long_fomat(b: &mut Bencher) { let world = "world"; b.iter(|| fomat!( "Lorem ipsum dolor sit amet, consectetur adipiscing elit. In convallis ligula nibh, at maximus diam eleifend sit amet. Suspendisse mattis nisi quis eleifend commodo. Praesent ut dui luctus, ullamcorper felis et, dictum purus. Nullam elit nunc, dictum ornare arcu vitae, suscipit pulvinar felis. Donec malesuada sollicitudin arcu, sit amet laoreet dolor elementum eu. Cras quam augue, feugiat ac imperdiet vel, posuere et elit. Nunc consequat bibendum dolor at auctor. Cras vel urna fermentum, viverra est ut, posuere elit. Suspendisse mattis aliquam tincidunt. Pellentesque ac risus eu nunc molestie cursus id in risus. Pellentesque vel ipsum sed lectus vehicula fermentum vitae vel est. Phasellus suscipit dolor eu finibus tincidunt. Duis interdum lectus at interdum viverra. Phasellus in mi dapibus, condimentum ligula at, rhoncus quam. Morbi pulvinar tortor sit amet fringilla sodales. Duis feugiat felis ut ante efficitur, vitae consectetur leo luctus. Vivamus congue, ex vel ullamcorper auctor, quam dolor vulputate purus, quis dapibus nulla ipsum in ligula. Sed sed vehicula odio. Quisque bibendum efficitur sodales. In aliquet sollicitudin venenatis. Sed id euismod nulla. Cras risus ligula, mattis in arcu eu, pulvinar aliquet metus. Mauris et convallis eros, in tempus sem." (world)(1)(2)(3)[vec![4]] "!" ) ) } #[bench] fn long_format(b: &mut Bencher) { let world = "world"; b.iter(|| format!( "Lorem ipsum dolor sit amet, consectetur adipiscing elit. In convallis ligula nibh, at maximus diam eleifend sit amet. Suspendisse mattis nisi quis eleifend commodo. Praesent ut dui luctus, ullamcorper felis et, dictum purus. Nullam elit nunc, dictum ornare arcu vitae, suscipit pulvinar felis. Donec malesuada sollicitudin arcu, sit amet laoreet dolor elementum eu. Cras quam augue, feugiat ac imperdiet vel, posuere et elit. Nunc consequat bibendum dolor at auctor. Cras vel urna fermentum, viverra est ut, posuere elit. Suspendisse mattis aliquam tincidunt. Pellentesque ac risus eu nunc molestie cursus id in risus. Pellentesque vel ipsum sed lectus vehicula fermentum vitae vel est. Phasellus suscipit dolor eu finibus tincidunt. Duis interdum lectus at interdum viverra. Phasellus in mi dapibus, condimentum ligula at, rhoncus quam. Morbi pulvinar tortor sit amet fringilla sodales. Duis feugiat felis ut ante efficitur, vitae consectetur leo luctus. Vivamus congue, ex vel ullamcorper auctor, quam dolor vulputate purus, quis dapibus nulla ipsum in ligula. Sed sed vehicula odio. Quisque bibendum efficitur sodales. In aliquet sollicitudin venenatis. Sed id euismod nulla. Cras risus ligula, mattis in arcu eu, pulvinar aliquet metus. Mauris et convallis eros, in tempus sem.{}{}{}{}{:?}!", world, 1, 2, 3, vec![4] ) ) } fomat-macros-0.3.1/src/lib.rs010064400017500001750000000643651343454477500142650ustar0000000000000000//! This crate provides alternative syntax for //! `write!`, `writeln!`, `print!`, `println!` and `format!` macros. //! It also introduces macros to print on `stderr`. //! //! The names of macros in this crate are formed by //! removing the letter `r` from their `std` counterparts. //! //! Index: [**examples**](#examples) •  //! [**syntax**](#syntax-overview): //! [`"string"`](#string-literals), //! [`()`, `[]`](#expressions-in--and--brackets), //! [`{}`](#curly-braces), //! [`for`](#for-loops), //! [`if`](#if-and-if-let), //! [`match`](#match), //! [`=`](#debugging-shorthand) •  //! [**troubleshooting**](#troubleshooting) •  //! [**macros**](#macros) //! //! # Examples //! //! ``` //! use fomat_macros::pintln; //! //! fn main() { //! pintln!("Hello, World!"); //! pintln!("Display trait: "(2+2)); //! pintln!("Debug trait: "[vec![1, 2, 3]]); //! pintln!("Multiple " "parameters" (1) " " [2]); //! //! pintln!("Formatting parameters: " {(1./3.):5.2}); // 0.333 //! pintln!("Debug: "[= 2 + 2]); // Debug: 2 + 2 = 4 //! } //! ``` //! //! This crate also contains a small templating language, //! allowing you to mix constructs like `for` with //! the printing syntax. The following should print `1 :: 2 :: 3 :: nil`. //! //! ``` //! # use fomat_macros::pintln; //! # fn main() { //! let list = [1, 2, 3]; //! pintln!( for x in &list { (x) " :: " } "nil" ); //! # } //! ``` //! //! You can also use the macros without importing them //! ``` //! fomat_macros::pintln!("2 + 2 = "(2 + 2)); //! ``` //! //! # Syntax overview //! //! All the macros share the same syntax, so //! it will be described in this section. //! //! The macros take list of *things* to print as an argument. //! Each *thing* could be either a string literal, something //! inside brackets (`()`, `[]` or `{}`) or a Rust construct //! (`for`, `if let`, `if` or `match`). There has to be //! no separator (like a comma) between those *things*. //! //! Whitespace is ignored outside the string literals. //! //! ## String literals //! //! String literals will be formatted directly as they are. //! Note that this also applies to `{` and `}` characters. //! //! ``` //! # use fomat_macros::fomat; //! # fn main() { //! let s = fomat!("Hi." "{}"); //! assert_eq!(s, "Hi.{}"); //! # } //! ``` //! //! ## Expressions in `()` and `[]` brackets. //! //! Expressions in these brackets will be evaluated and //! printed using: //! //! * `Display` trait for `(expr)` (equivalent to `{}` format). //! * `Debug` trait for `[expr]` (equivalent to `{:?}` format). //! //! Like in `std`, they are implicitly borrowed. //! //! ``` //! # use fomat_macros::fomat; //! # fn main() { //! let s = fomat!( ("string") (2 + 2) ", " [vec![1]] ); //! assert_eq!(s, "string4, [1]") //! # } //! ``` //! //! ## Curly braces //! //! ### `write!` passthrough //! //! If you want to use regular `format!` syntax for some //! part of your string, place `format!` arguments //! inside the curly braces: //! //! ``` //! # use fomat_macros::wite; //! # fn main() { //! use std::io::Write; //! //! let mut v = vec![]; //! wite!(v, "foo " {"{} baz {}", "bar", "quux"}); //! assert_eq!(v, "foo bar baz quux".as_bytes()); //! # } //! ``` //! //! ### Single argument //! //! If you only want to print a single argument //! with a custom format parameters, //! you can use the `{token_tree:format_parameters}` //! syntax. //! //! The following will use binary format, //! zero-aligned to 8 places. //! //! ``` //! # use fomat_macros::fomat; //! # fn main() { //! let s = fomat!({13:08b}); //! assert_eq!(s, "00001101"); //! # } //! ``` //! //! Please note that there can be only a single //! token tree before the colon – usually //! a literal or an identifier. Anything //! longer has to be wrapped in parentheses //! (like that `{(10+3):08b}`). //! //! ## For loops //! //! For loops use the regular Rust syntax, //! except the body //! will use this printing syntax again. //! //! ``` //! # use fomat_macros::fomat; //! # fn main() { //! let list = [1, 2, 3]; //! let s = fomat!( for x in &list { (x) " :: " } "nil" ); //! assert_eq!(s, "1 :: 2 :: 3 :: nil"); //! # } //! ``` //! //! For loops can also use an optional separator, //! denoted by `sep` or `separated` keyword. //! //! ``` //! # use fomat_macros::fomat; //! # fn main() { //! # let list = ["a", "b"]; //! let s = fomat!( //! for (i, x) in list.iter().enumerate() { (i) " → " (x) } //! separated { ", " } //! ); //! assert_eq!(s, "0 → a, 1 → b"); //! # } //! ``` //! //! For loops (and other syntax elements) can also be nested: //! //! ``` //! # use fomat_macros::fomat; //! # fn main() { //! let matrix = [[0, 1], [2, 3]]; //! assert_eq!( //! fomat!( for row in &matrix { for x in row { {x:3} } "\n" } ), //! " 0 1\n 2 3\n" //! ); //! # } //! ``` //! //! ## If and if let //! //! They use the regular Rust syntax, //! except of the body (inside `{}`), //! which uses the printing syntax. //! //! The benefits of using this syntax instead //! of getting `if` "outside" of the printing //! macros is apparent when the conditional is //! a part of a longer string (you don't //! have to split this into three separate `write!`s): //! //! ``` //! # use fomat_macros::fomat; //! # fn main() { //! let opt = Some(5); //! let s = fomat!( //! "a\n" //! if let Some(x) = opt { (x) "\n" } else { "nothing\n" } //! "b\n" //! ); //! assert_eq!(s, "a\n5\nb\n"); //! # } //! ``` //! //! The `else` clause is optional. //! //! `else if`-chaining is not supported. As a workaround, //! use `else { if ... }` or `match`. //! //! ## Match //! //! Match uses the regular Rust syntax, //! except arms has to use `{}` blocks, //! which will be interpreted using printing syntax. //! //! ``` //! # use fomat_macros::fomat; //! # fn main() { //! let v = [Some(1), None, Some(2)]; //! let s = fomat!( //! for x in &v { //! match *x { //! Some(x) => { (x) } //! None => { "_" } //! } //! } //! ); //! assert_eq!(s, "1_2"); //! # } //! ``` //! //! Match arms should not be separated by commas. //! //! ## Debugging shorthand //! //! If you want to print both the expression and the value, //! place equal sign as a first character in brackets. //! The trait used to print the value will depend on //! the kind of brackets used. //! //! ``` //! # use fomat_macros::fomat; //! # fn main() { //! let word = "foo"; //! let arr = [10]; //! let s = fomat!( (=word) ", " [=&arr] ", " {=5:#b} ); //! assert_eq!(s, "word = foo, &arr = [10], 5 = 0b101"); //! # } //! ``` //! //! # Troubleshooting //! //! ## Recursion depth //! //! If you hit the error about recursion depth, //! which occurs when you try to print more than //! about 50 elements, you can use this workaround //! instead of increasing the limit: split everything //! into two (or more) dummy `if true` blocks. //! //! ## Errors in macro parsing //! //! If you hit `expected a literal`, that either means //! either you've made a syntactic mistake //! or really a string literal is expected here. //! Remember, naked identifiers won't be printed //! unless you put them in parentheses. use std::fmt; #[doc(hidden)] pub struct DisplayOnce { closure: std::cell::Cell> } impl DisplayOnce where F: FnOnce(&mut fmt::Formatter) -> fmt::Result { pub fn new(f: F) -> Self { Self { closure: std::cell::Cell::new(Some(f)) } } } impl fmt::Display for DisplayOnce where F: FnOnce(&mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self.closure.replace(None).take() { Some(closure) => closure(f), None => Ok(()) } } } /// Wrapper implementing Display for every closure with matching signature /// /// This wrapper implements Display for every closure implementing /// `Fn(&mut fmt::Formatter) -> fmt::Result`. /// /// Can be create using [`lazy_fomat`][lazy_fomat] pub struct DisplayFn(F); impl DisplayFn where F: Fn(&mut fmt::Formatter) -> fmt::Result { /// Creates an object which `Display::fmt` impl will call this closure. pub fn new(f: F) -> Self { Self(f) } } impl fmt::Display for DisplayFn where F: Fn(&mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { (self.0)(f) } } /// Writes to a specified writer. Analogous to `write!`. /// /// See the crate root for general help on the syntax. /// /// The first argument should be something that implements either `io::Write` /// or `fmt::Write`. This expression will be evaluated once. /// /// The list of things to write should be written after /// the first comma, without any further delimiters. /// /// # Return value /// /// This macro returns `io::Result<()>` or `fmt::Result`, /// just as `write!` from `std`. /// /// # Examples /// /// ``` /// # use fomat_macros::wite; /// # fn main() { /// use ::std::io::Write; /// use ::std::io::BufWriter; /// let mut v = vec![]; /// let world = "World"; /// wite!(v, "Hello, "(world)"!").unwrap(); /// wite!(BufWriter::new(&mut v), " "(2+2)).unwrap(); /// assert_eq!(v, "Hello, World! 4".as_bytes()); /// # } /// ``` #[macro_export] macro_rules! wite { // single tt rules --------------------------------------------------------- (@one $w:ident, ($e:expr)) => { ::std::fmt::Display::fmt(&$e, $w) }; (@one $w:ident, [$e:expr]) => { ::std::fmt::Debug::fmt(&$e, $w) }; (@one $w:ident, {$e:tt : $($fmt:tt)*}) => { write!($w, concat!("{:", $crate::wite!(@stringify-dense $($fmt)*), "}"), $e) }; (@one $w:ident, {$($arg:tt)*}) => { write!($w, $($arg)*) }; (@one $w:ident, $string:tt) => { $w.write_str(concat!($string)) }; (@stringify-dense) => { "" }; (@stringify-dense $($tt:tt)+) => { concat!( $(stringify!($tt)),+ ) }; // expression parsing (manually, because we can't use :expr before `{`) (@expr.. $w:ident {$($before:tt)*} ($($e:tt)*) {$($block:tt)*} $($rest:tt)* ) => { $crate::wite!(@rec $w, $($before)* ($($e)*) {$($block)*} $($rest)*) }; (@expr.. $w:ident {$($before:tt)*} ($($expr:tt)*) $tt:tt $($rest:tt)* ) => { $crate::wite!(@expr.. $w {$($before)*} ($($expr)* $tt) $($rest)*) }; (@expr $w:ident {$($before:tt)*} ($($expr:tt)*) $tt:tt $($rest:tt)* ) => { $crate::wite!(@expr.. $w {$($before)*} ($($expr)* $tt) $($rest)*) }; // recursive parsing ------------------------------------------------------- // for (@rec $w:ident, for $p:pat in ($e:expr) { $($body:tt)* } sep { $($sep:tt)* } $($rest:tt)* ) => { { let mut first_iteration = true; for $p in $e { if first_iteration { first_iteration = false; } else { $crate::wite!(@rec $w, $($sep)*); } $crate::wite!(@rec $w, $($body)*); } $crate::wite!(@rec $w, $($rest)*); } }; (@rec $w:ident, for $p:pat in ($e:expr) { $($body:tt)* } separated { $($sep:tt)* } $($rest:tt)* ) => { $crate::wite!(@rec $w, for $p in ($e) { $($body)* } sep { $($sep)* }$($rest)*) }; (@rec $w:ident, for $p:pat in ($e:expr) { $($body:tt)* } $($rest:tt)*) => { $crate::wite!(@rec $w, for $p in ($e) { $($body)* } sep {} $($rest)*) }; (@rec $w:ident, for $p:pat in $($tt:tt)* ) => { $crate::wite!(@expr $w { for $p in } () $($tt)*) }; // match (@rec $w:ident, match ($e:expr) { $( $($p:pat)|+ $(if $g:expr)* => { $($body:tt)* } )* } $($rest:tt)* ) => { { match $e { $( $($p)|+ $(if $g)* => { $crate::wite!(@rec $w, $($body)*) } )* } $crate::wite!(@rec $w, $($rest)*); } }; (@rec $w:ident, match $($tt:tt)* ) => { $crate::wite!(@expr $w { match } () $($tt)*) }; // if let (@rec $w:ident, if let $p:pat = ($e:expr) { $($then:tt)* } else { $($els:tt)* } $($rest:tt)* ) => { { if let $p = $e { $crate::wite!(@rec $w, $($then)*); } else { $crate::wite!(@rec $w, $($els)*); } $crate::wite!(@rec $w, $($rest)*); } }; (@rec $w:ident, if let $p:pat = ($e:expr) { $($then:tt)* } else if $($rest:tt)* ) => { $crate::wite!(@ifelseerror) }; (@rec $w:ident, if let $p:pat = ($e:expr) { $($then:tt)* } $($rest:tt)* ) => { $crate::wite!(@rec $w, if let $p = ($e) { $($then)* } else {} $($rest)*); }; (@rec $w:ident, if let $p:pat = $($tt:tt)* ) => { $crate::wite!(@expr $w { if let $p = } () $($tt)*) }; // if (@rec $w:ident, if ($cond:expr) { $($then:tt)* } else { $($els:tt)* } $($rest:tt)* ) => { { if $cond { $crate::wite!(@rec $w, $($then)*); } else { $crate::wite!(@rec $w, $($els)*); } $crate::wite!(@rec $w, $($rest)*); } }; (@rec $w:ident, if ($cont:expr) { $($then:tt)* } else if $($rest:tt)* ) => { $crate::wite!(@ifelseerror) }; (@rec $w:ident, if ($cond:expr) { $($then:tt)* } $($rest:tt)* ) => { $crate::wite!(@rec $w, if ($cond) { $($then)* } else {} $($rest)*); }; (@rec $w:ident, if $($tt:tt)* ) => { $crate::wite!(@expr $w { if } () $($tt)*) }; // equal-sign debugging (@rec $w:ident, (= $e:expr) $($rest:tt)*) => { $crate::wite!(@rec $w, (concat!(stringify!($e), " = ")) ($e) $($rest)*) }; (@rec $w:ident, [= $e:expr] $($rest:tt)*) => { $crate::wite!(@rec $w, (concat!(stringify!($e), " = ")) [$e] $($rest)*) }; (@rec $w:ident, {= $e:tt : $($fmt:tt)*} $($rest:tt)*) => { $crate::wite!(@rec $w, (concat!(stringify!($e), " = ")) {$e : $($fmt)*} $($rest)*) }; // single tt (@rec $w:ident, $part:tt $($rest:tt)*) => { { match $crate::wite!(@one $w, $part) { Ok(_) => (), error => return error, } $crate::wite!(@rec $w, $($rest)*); } }; // terminator (@rec $w:ident, ) => { () }; (@ifelseerror) => { { let ERROR: () = "`else if` is not supported"; let NOTE: () = "use `match` or `else { if ... }` instead"; } }; // entry point ------------------------------------------------------------- ($writer:expr, $($part:tt)*) => { write!( $writer, "{}", $crate::DisplayOnce::new(|f| { $crate::wite!(@rec f, $($part)*); Ok(()) }) ) }; } /// Writes to a specified writer, with an appended newline. Analogous to `writeln!`. /// /// See the documentation for [`wite!`](macro.wite.html). /// /// When there are no arguments, the comma may be omitted. /// /// # Examples /// /// ```no_run /// # use fomat_macros::witeln; /// # fn main() { /// # use ::std::io::Write; /// # let mut file = vec![]; /// witeln!(file).unwrap(); /// witeln!(file, "Hi").unwrap(); /// # } /// ``` #[macro_export] macro_rules! witeln { ($writer:expr, $($arg:tt)*) => { $crate::wite!($writer, $($arg)* "\n") }; ($writer:expr) => { $crate::wite!($writer, "\n") }; } /// Prints to stdout. Analogous to `print!`. /// /// See the crate root for general help on the syntax. /// /// # Return value /// /// The macro returns `()`. /// /// # Panics /// /// The macro panics when printing was not successful. /// /// # Behaviour in `#[test]` /// /// The behaviour when testing is similar to `print!`: /// the output of this macro will be captured by the /// testing framework (meaning that by default `cargo test` /// won't show the output). /// /// The only limitation and difference from `print!` is /// that when `pint!` is called by a different crate /// than the one being tested, the output won't be captured /// and will allways be printed to stdout. /// /// # Examples /// /// ```no_run /// # use fomat_macros::pint; /// # fn main() { /// pint!("four = "(2+2)); /// # } /// ``` #[macro_export] macro_rules! pint { ($($arg:tt)*) => { { { #[cfg(not(test))] { use ::std::io::Write; let o = ::std::io::stdout(); $crate::wite!(o.lock(), $($arg)*).unwrap(); } #[cfg(test)] { print!("{}", $crate::fomat!($($arg)*)) } } } } } /// Prints to stdout, with an appended newline. Analoguous to `println!`. /// /// See the docs for [`print!`](macro.pint.html) for more details. /// /// # Examples /// /// ```no_run /// # use fomat_macros::pintln; /// # fn main() { /// pintln!(); /// pintln!((2 * 2)); /// # } /// ``` #[macro_export] macro_rules! pintln { ($($arg:tt)*) => { { #[cfg(not(test))] { $crate::pint!($($arg)* "\n") } #[cfg(test)] { print!("{}", fomat!($($arg)* "\n")) } } } } /// Prints to stderr. Analogous to `eprint!`. /// /// See the crate root for general help on the syntax. /// /// # Return value /// /// None /// /// # Panics /// /// This macro, in contrary to `pint!`, silently ignores /// all errors. /// /// # Examples /// /// ```no_run /// # use fomat_macros::epint; /// # fn main() { /// epint!("foo") /// # } /// ``` #[macro_export] macro_rules! epint { ($($arg:tt)*) => { { use ::std::io::Write; let o = ::std::io::stderr(); $crate::wite!(o.lock(), $($arg)*).unwrap(); } } } /// Same as `epint` #[macro_export] #[deprecated(since="0.2.1", note="use `epint` instead")] macro_rules! perr { ($($arg:tt)*) => { $crate::epint!($($arg)*) } } /// Prints to stderr, with an appended newline. Analogous to `eprintln!`. /// /// See the docs for [`epint!`](macro.epint.html) for more info. /// /// # Examples /// /// ```no_run /// # use fomat_macros::epintln; /// # fn main() { /// let x = 3; /// epintln!((=x)); /// # } /// ``` #[macro_export] macro_rules! epintln { ($($arg:tt)*) => { $crate::epint!($($arg)* "\n") } } /// Same as `epintln` #[macro_export] #[deprecated(since="0.2.1", note="use `epint` instead")] macro_rules! perrln { ($($arg:tt)*) => { $crate::epintln!($($arg)*) } } /// Creates a formatted string. Analogous to `format!`. /// /// See the crate root for general help on the syntax. /// /// This macro returns `String` containing the formatted text. /// /// # Panics /// /// The macro will panic if formatting fails (which shoudn't happen for any /// of `std` types). /// /// # Examples /// /// ``` /// # use fomat_macros::fomat; /// # fn main() { /// let v = [1, 2]; /// /// let s = fomat!("Hello, "[v]); /// assert_eq!(s, "Hello, [1, 2]"); /// /// let s = fomat!(for x in &v { (x*x) ";" }); /// assert_eq!(s, "1;4;"); /// # } /// ``` #[macro_export] macro_rules! fomat { // capacity estimation ----------------------------------------------------- (@cap ($len:expr, $multiplier:expr)) => { ($len, $multiplier) }; // skip all irrelevant tts and conditional bodies (@cap ($($lm:tt)*) for $p:pat in $($tt:tt)*) => { $crate::fomat!(@cap-ignore ($($lm)*) $($tt)*) }; (@cap ($($lm:tt)*) sep $($tt:tt)*) => { $crate::fomat!(@cap-ignore ($($lm)*) $($tt)*) }; (@cap ($($lm:tt)*) separated $($tt:tt)*) => { $crate::fomat!(@cap-ignore ($($lm)*) $($tt)*) }; (@cap ($($lm:tt)*) if let $p:pat = $($tt:tt)*) => { $crate::fomat!(@cap-ignore ($($lm)*) $($tt)*) }; (@cap ($($lm:tt)*) if $($tt:tt)*) => { $crate::fomat!(@cap-ignore ($($lm)*) $($tt)*) }; (@cap ($($lm:tt)*) else $($tt:tt)*) => { $crate::fomat!(@cap-ignore ($($lm)*) $($tt)*) }; (@cap ($($lm:tt)*) match $($tt:tt)*) => { $crate::fomat!(@cap-ignore ($($lm)*) $($tt)*) }; // When there's any unconditional string interpolation, // we multiply the initial capacity by 2 // (which would probably happen anyway). (@cap ($len:expr, $mul:expr) ($($x:tt)*) $($rest:tt)*) => { $crate::fomat!(@cap ($len, 2) $($rest)*) }; (@cap ($len:expr, $mul:expr) [$($x:tt)*] $($rest:tt)*) => { $crate::fomat!(@cap ($len, 2) $($rest)*) }; (@cap ($len:expr, $mul:expr) {$($x:tt)*} $($rest:tt)*) => { $crate::fomat!(@cap ($len, 2) $($rest)*) }; // Now the only legal tt is a string literal (@cap ($len:expr, $mul:expr) $string:tt $($rest:tt)*) => { // Concat forces the token to be a string literal. $crate::fomat!(@cap ($len + concat!($string).len(), $mul) $($rest)*) }; // Ignores everything till after next block (@cap-ignore ($($lm:tt)*) { $($block:tt)* } $($rest:tt)*) => { $crate::fomat!(@cap ($($lm)*) $($rest)*) }; (@cap-ignore ($($lm:tt)*) $tt:tt $($rest:tt)*) => { $crate::fomat!(@cap-ignore ($($lm)*) $($rest)*) }; // entry points ------------------------------------------------------------ () => { String::new() }; ($($arg:tt)*) => { { use ::std::fmt::Write; let (len, mul) = $crate::fomat!(@cap (0, 1) $($arg)*); let mut _s = String::with_capacity(len * mul); $crate::wite!(_s, $($arg)*).ok(); _s } } } /// Creates a displayable object based on its arguments. /// /// This macro works in a similar way to [`fomat`](fomat), /// but instead of `String` it returns an object ([`DisplayFn`](DisplayFn)) /// that implements [`Display`][std::fmt::Display] and can be printed later /// (using `format`, `fomat` or calling `Display::fmt` directly). /// /// See the [crate root](crate) for general help on the syntax. /// /// Prefix the arguments with `move` to force moving all variables /// (can help when `'static` bound is required). /// /// # Examples /// /// Direct usage /// /// ``` /// # use fomat_macros::{fomat, lazy_fomat}; /// let fence = lazy_fomat!(for _ in 0..5 { "-" }); /// let s = fomat!((fence)" hello "(fence)); /// /// assert_eq!(s, "----- hello -----"); /// ``` /// /// Returning `impl Display` /// /// ``` /// # use fomat_macros::lazy_fomat; /// fn greet(name: String) -> impl ::std::fmt::Display { /// lazy_fomat!(move "Hello, "(name)"!") /// } /// /// assert_eq!(greet("World".into()).to_string(), "Hello, World!"); /// ``` #[macro_export] macro_rules! lazy_fomat { (move $($arg:tt)*) => { $crate::DisplayFn::new(move |f| { $crate::wite!(@rec f, $($arg)*); Ok(()) }) }; ($($arg:tt)*) => { $crate::DisplayFn::new(|f| { $crate::wite!(@rec f, $($arg)*); Ok(()) }) }; } #[test] fn basics() { let world = "World"; assert_eq!(fomat!("Hello, "(world)"!"), "Hello, World!"); let x = 3; assert_eq!(fomat!((x)" * 2 = "(x * 2)), "3 * 2 = 6"); } #[test] fn empty() { assert_eq!(fomat!(), ""); } #[test] fn debug() { let v = [1,2,3]; assert_eq!(fomat!([v] "."), "[1, 2, 3]."); } #[test] fn test_if() { let s = fomat!( if true { "A" "A" } else { "X" } if false { "X" } else { "D" "D" } if true { "T" "T" } if false { "X" } if let Some(x) = Some(5) { (x) (x) } else { "E" "E" } if let None = Some(5) { "X" } else { "F" "F" } if let Some(x) = Some(5) { (x) } if let None = Some(5) { "X" } if {let t = true; t} { "K" } "." ); assert_eq!(s, "AADDTT55FF5K."); } #[test] fn format() { assert_eq!( fomat!({5:02}), "05" ); assert_eq!( fomat!({"{}-{}", 4, 2}), "4-2" ); } #[test] fn separator() { let v = [1, 2, 3]; let s1 = fomat!( for x in &v { (x) } separated { "-" "-" } "." ); let s2 = fomat!( for x in &v { (x) } sep { "--" } "." ); assert_eq!(s1, "1--2--3."); assert_eq!(s2, "1--2--3."); } #[test] fn test_match() { let s = fomat!( match Some(5) { Some(x) if x > 3 => { (x) "!" } Some(2) | None => {} _ => {} } "." ); assert_eq!(s, "5!."); } #[test] fn capacity() { assert_eq!(fomat!("Hello, " "world!").capacity(), 13); assert_eq!(fomat!("Hello, "[40+2]).capacity(), 14); let s = fomat!( "Hello" for x in [1][1..].iter() { (x) "a" } if let Some(()) = None { "b" } if false { "c" } else {} match 1 { 2 => { "e" } _ => {} } "!" ); assert_eq!(s.capacity(), 6); } #[test] fn fmt_write() { use std::fmt; struct Foo; impl fmt::Display for Foo { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { wite!(f, "foo"(42)) } } assert_eq!(format!("{}", Foo), "foo42"); } #[test] fn equal_sign() { let x = 5; let v = [10]; assert_eq!(fomat!((=x) "."), "x = 5."); assert_eq!(fomat!([=&v] "."), "&v = [10]."); assert_eq!(fomat!({=13:05b} "."), "13 = 01101."); } #[test] fn depth() { let _ = fomat!( "1" "2" "3" "4" "5" "6" "7" "8" "9" "0" "1" "2" "3" "4" "5" "6" "7" "8" "9" "0" "1" "2" "3" "4" "5" "6" "7" "8" "9" "0" "1" "2" "3" "4" "5" "6" "7" "8" "9" "0" "1" "2" "3" "4" "5" "6" "7" "8" "9" "0" ); } #[test] fn non_static_writer() { use std::io::Write; use std::io::Result; use std::fmt::Arguments; struct Prepender<'a, T: Write> { prefix: &'a str, writer: T, } impl<'a, T: Write> Write for Prepender<'a, T> { fn write(&mut self, buf: &[u8]) -> Result { self.writer.write(buf) } fn flush(&mut self) -> Result<()> { self.writer.flush() } fn write_fmt(&mut self, fmt: Arguments) -> Result<()> { self.writer.write_all(self.prefix.as_bytes())?; self.writer.write_fmt(fmt) } } let mut buf = vec![]; witeln!( Prepender { prefix: &"foo ".to_owned(), writer: &mut buf }, (2+2) ).unwrap(); assert_eq!(buf, "foo 4\n".as_bytes()); } #[test] fn no_semicolon() { if true { pint!("foo") } else { epint!("bar") } pintln!("foo" "bar") } #[test] fn move_and_borrow() { // Test if fomat! arguments can move some and borrow other variables. let iter = vec![1, 2, 3].into_iter(); let borrow_me = vec![1, 2, 3]; let s = fomat!(for x in iter { (x) } (borrow_me.len())); assert_eq!(s, "1233"); assert_eq!(borrow_me, [1, 2, 3]); } fomat-macros-0.3.1/tests/capturing.rs010064400017500001750000000065521327220606200160400ustar0000000000000000extern crate tempdir; extern crate tar; use std::path::Path; const FILES: &'static [(&'static str, &'static str)] = &[ ("Cargo.toml", r#" [package] name = "pint" version = "0.1.0" [dependencies] fomat-macros = { path = "PATH" } "#), ("src/main.rs", r#" #[macro_use] extern crate fomat_macros; fn foo() { pint!("stdout"(1)); pintln!("stdout"(2)); epint!("stderr"(1)); epintln!("stderr"(2)); perr!("stderr"(1)); perrln!("stderr"(2)); } fn main() { foo(); } #[test] fn capturing() { foo(); } "#), ("src/lib.rs", r#" #[macro_use] extern crate fomat_macros; pub fn called_from_other_crate() { pintln!("nocapture"(1)); } "#), ("tests/nocapture.rs", r#" extern crate pint; #[test] fn nocapture() { pint::called_from_other_crate(); } "#), ]; fn unpack_files(directory: &Path, replace_path: &str) { use tar::{Builder, Header, Archive}; let mut builder = Builder::new(Vec::new()); for &(name, data) in FILES { let data = data.replace("PATH", replace_path); let mut header = Header::new_gnu(); header.set_path(name).unwrap(); header.set_size(data.len() as u64); header.set_cksum(); builder.append(&header, data.as_bytes()).unwrap(); } let archive: &[u8] = &builder.into_inner().unwrap(); Archive::new(archive).unpack(directory) .expect("Can't unpack test crate"); } #[test] fn capturing() { use std::process::Command; use std::env; use std::str::from_utf8; let rootdir = { let mut rootdir = env::current_exe().unwrap(); while rootdir.file_name() != Some("target".as_ref()) { assert!( rootdir.pop() ); } assert!( rootdir.pop() ); rootdir }; let pintdir = tempdir::TempDir::new("fomat-macros-capturing-test") .expect("Can't create tempdir"); unpack_files(pintdir.as_ref(), rootdir.to_str().unwrap()); assert!( Command::new("cargo").arg("build") .current_dir(&pintdir) .status().unwrap().success() ); let expected_stdout = "stdout1stdout2\n"; let expected_stderr = "stderr1stderr2\nstderr1stderr2\n"; let output = Command::new("target/debug/pint") .current_dir(&pintdir) .output().unwrap(); assert!(output.status.success()); assert_eq!(from_utf8(&output.stdout).unwrap(), expected_stdout); assert_eq!(from_utf8(&output.stderr).unwrap(), expected_stderr); let output = Command::new("cargo") .arg("test") .current_dir(&pintdir) .output().unwrap(); assert!(output.status.success()); assert!(!from_utf8(&output.stdout).unwrap().contains(expected_stdout)); assert!(from_utf8(&output.stderr).unwrap().contains(expected_stderr)); assert!(from_utf8(&output.stdout).unwrap().contains("nocapture1")); let output = Command::new("cargo") .args(&["test", "--", "--nocapture"]) .current_dir(&pintdir) .output().unwrap(); assert!(output.status.success()); assert!(from_utf8(&output.stdout).unwrap().contains(expected_stdout)); assert!(from_utf8(&output.stderr).unwrap().contains(expected_stderr)); } fomat-macros-0.3.1/tests/extern.rs010064400017500001750000000003241303264506300153420ustar0000000000000000#[macro_use] extern crate fomat_macros; #[test] fn macro_use() { let c: Vec = vec!["a".into()]; let _ = fomat!( "
    " for x in &c { "
  • " (x) "
  • " } "
" ); } fomat-macros-0.3.1/after.txt010064400017500001750000000022011343453174000141650ustar0000000000000000 running 14 tests test basics ... ignored test capacity ... ignored test debug ... ignored test depth ... ignored test empty ... ignored test equal_sign ... ignored test fmt_write ... ignored test format ... ignored test hello ... ignored test no_semicolon ... ignored test non_static_writer ... ignored test separator ... ignored test test_if ... ignored test test_match ... ignored test result: ok. 0 passed; 0 failed; 14 ignored; 0 measured; 0 filtered out running 10 tests test literal_fomat ... bench: 22 ns/iter (+/- 1) test literal_format ... bench: 22 ns/iter (+/- 2) test long_fomat ... bench: 170 ns/iter (+/- 50) test long_format ... bench: 197 ns/iter (+/- 10) test short_fomat ... bench: 39 ns/iter (+/- 16) test short_format ... bench: 38 ns/iter (+/- 9) test three_fomat ... bench: 55 ns/iter (+/- 4) test three_format ... bench: 78 ns/iter (+/- 17) test two_fomat ... bench: 45 ns/iter (+/- 4) test two_format ... bench: 51 ns/iter (+/- 10) test result: ok. 0 passed; 0 failed; 0 ignored; 10 measured; 0 filtered out fomat-macros-0.3.1/before.txt010064400017500001750000000022001343453207200143240ustar0000000000000000 running 14 tests test basics ... ignored test capacity ... ignored test debug ... ignored test depth ... ignored test empty ... ignored test equal_sign ... ignored test fmt_write ... ignored test format ... ignored test hello ... ignored test no_semicolon ... ignored test non_static_writer ... ignored test separator ... ignored test test_if ... ignored test test_match ... ignored test result: ok. 0 passed; 0 failed; 14 ignored; 0 measured; 0 filtered out running 10 tests test literal_fomat ... bench: 15 ns/iter (+/- 1) test literal_format ... bench: 23 ns/iter (+/- 3) test long_fomat ... bench: 213 ns/iter (+/- 16) test long_format ... bench: 196 ns/iter (+/- 16) test short_fomat ... bench: 32 ns/iter (+/- 7) test short_format ... bench: 37 ns/iter (+/- 7) test three_fomat ... bench: 68 ns/iter (+/- 13) test three_format ... bench: 65 ns/iter (+/- 7) test two_fomat ... bench: 50 ns/iter (+/- 7) test two_format ... bench: 51 ns/iter (+/- 10) test result: ok. 0 passed; 0 failed; 0 ignored; 10 measured; 0 filtered out