Skip to content

Commit 7612727

Browse files
committed
Add eprint! and eprintln! macros to the prelude.
These are exactly the same as `print!` and `println!` except that they write to stderr instead of stdout. Issue rust-lang#39228.
1 parent 2b97174 commit 7612727

File tree

4 files changed

+123
-0
lines changed

4 files changed

+123
-0
lines changed

src/libstd/io/mod.rs

+2
Original file line numberDiff line numberDiff line change
@@ -290,6 +290,8 @@ pub use self::util::{copy, sink, Sink, empty, Empty, repeat, Repeat};
290290
pub use self::stdio::{stdin, stdout, stderr, _print, Stdin, Stdout, Stderr};
291291
#[stable(feature = "rust1", since = "1.0.0")]
292292
pub use self::stdio::{StdoutLock, StderrLock, StdinLock};
293+
#[unstable(feature = "eprint", issue="39228")]
294+
pub use self::stdio::_eprint;
293295
#[unstable(feature = "libstd_io_internals", issue = "0")]
294296
#[doc(no_inline, hidden)]
295297
pub use self::stdio::{set_panic, set_print};

src/libstd/io/stdio.rs

+36
Original file line numberDiff line numberDiff line change
@@ -694,6 +694,42 @@ pub fn _print(args: fmt::Arguments) {
694694
}
695695
}
696696

697+
#[unstable(feature = "eprint_internal",
698+
reason = "implementation detail which may disappear or be replaced at any time",
699+
issue = "0")]
700+
#[doc(hidden)]
701+
pub fn _eprint(args: fmt::Arguments) {
702+
// As an implementation of the `eprintln!` macro, we want to try our best to
703+
// not panic wherever possible and get the output somewhere. There are
704+
// currently two possible vectors for panics we take care of here:
705+
//
706+
// 1. If the TLS key for the local stderr has been destroyed, accessing it
707+
// would cause a panic. Note that we just lump in the uninitialized case
708+
// here for convenience, we're not trying to avoid a panic.
709+
// 2. If the local stderr is currently in use (e.g. we're in the middle of
710+
// already printing) then accessing again would cause a panic.
711+
//
712+
// If, however, the actual I/O causes an error, we do indeed panic.
713+
use panicking::LOCAL_STDERR;
714+
let result = match LOCAL_STDERR.state() {
715+
LocalKeyState::Uninitialized |
716+
LocalKeyState::Destroyed => stderr().write_fmt(args),
717+
LocalKeyState::Valid => {
718+
LOCAL_STDERR.with(|s| {
719+
if let Ok(mut borrowed) = s.try_borrow_mut() {
720+
if let Some(w) = borrowed.as_mut() {
721+
return w.write_fmt(args);
722+
}
723+
}
724+
stderr().write_fmt(args)
725+
})
726+
}
727+
};
728+
if let Err(e) = result {
729+
panic!("failed printing to stderr: {}", e);
730+
}
731+
}
732+
697733
#[cfg(test)]
698734
mod tests {
699735
use thread;

src/libstd/macros.rs

+45
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,9 @@ macro_rules! panic {
6868
/// necessary to use `io::stdout().flush()` to ensure the output is emitted
6969
/// immediately.
7070
///
71+
/// Use `print!` only for the primary output of your program. Use
72+
/// `eprint!` instead to print error and progress messages.
73+
///
7174
/// # Panics
7275
///
7376
/// Panics if writing to `io::stdout()` fails.
@@ -105,6 +108,9 @@ macro_rules! print {
105108
/// Use the `format!` syntax to write data to the standard output.
106109
/// See `std::fmt` for more information.
107110
///
111+
/// Use `println!` only for the primary output of your program. Use
112+
/// `eprintln!` instead to print error and progress messages.
113+
///
108114
/// # Panics
109115
///
110116
/// Panics if writing to `io::stdout()` fails.
@@ -124,6 +130,45 @@ macro_rules! println {
124130
($fmt:expr, $($arg:tt)*) => (print!(concat!($fmt, "\n"), $($arg)*));
125131
}
126132

133+
/// Macro for printing to the standard error.
134+
///
135+
/// Equivalent to the `print!` macro, except that output goes to
136+
/// `io::stderr()` instead of `io::stdout()`. See `print!` for
137+
/// example usage.
138+
///
139+
/// Use `eprint!` only for error and progress messages. Use `print!`
140+
/// instead for the primary output of your program.
141+
///
142+
/// # Panics
143+
///
144+
/// Panics if writing to `io::stderr()` fails.
145+
#[macro_export]
146+
#[unstable(feature = "eprint", issue="39228")]
147+
#[allow_internal_unstable]
148+
macro_rules! eprint {
149+
($($arg:tt)*) => ($crate::io::_eprint(format_args!($($arg)*)));
150+
}
151+
152+
/// Macro for printing to the standard error, with a newline.
153+
///
154+
/// Equivalent to the `println!` macro, except that output goes to
155+
/// `io::stderr()` instead of `io::stdout()`. See `println!` for
156+
/// example usage.
157+
///
158+
/// Use `eprintln!` only for error and progress messages. Use `println!`
159+
/// instead for the primary output of your program.
160+
///
161+
/// # Panics
162+
///
163+
/// Panics if writing to `io::stderr()` fails.
164+
#[macro_export]
165+
#[unstable(feature = "eprint", issue="39228")]
166+
macro_rules! eprintln {
167+
() => (eprint!("\n"));
168+
($fmt:expr) => (eprint!(concat!($fmt, "\n")));
169+
($fmt:expr, $($arg:tt)*) => (eprint!(concat!($fmt, "\n"), $($arg)*));
170+
}
171+
127172
/// A macro to select an event from a number of receivers.
128173
///
129174
/// This macro is used to wait for the first event to occur on a number of
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
// Copyright 2017 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+
#![feature(eprint)]
12+
13+
use std::{env, process};
14+
15+
fn child() {
16+
print!("[stdout 0]");
17+
print!("[stdout {}]", 1);
18+
println!("[stdout {}]", 2);
19+
println!();
20+
eprint!("[stderr 0]");
21+
eprint!("[stderr {}]", 1);
22+
eprintln!("[stderr {}]", 2);
23+
eprintln!();
24+
}
25+
26+
fn parent() {
27+
let this = env::args().next().unwrap();
28+
let output = process::Command::new(this).arg("-").output().unwrap();
29+
assert!(output.status.success());
30+
31+
let stdout = String::from_utf8(output.stdout).unwrap();
32+
let stderr = String::from_utf8(output.stderr).unwrap();
33+
34+
assert_eq!(stdout, "[stdout 0][stdout 1][stdout 2]\n\n");
35+
assert_eq!(stderr, "[stderr 0][stderr 1][stderr 2]\n\n");
36+
}
37+
38+
fn main() {
39+
if env::args().count() == 2 { child() } else { parent() }
40+
}

0 commit comments

Comments
 (0)