Skip to content

Commit a00e182

Browse files
authored
Rollup merge of rust-lang#41192 - zackw:eprintln, r=alexcrichton
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. Issues rust-lang#39228 and rust-lang#40528; previous PR rust-lang#39229; accepted RFC rust-lang/rfcs#1869; proposed revision to The Book rust-lang/book#615. I have _not_ revised this any since the original submission; I will do that later this week. I wanted to get this PR in place since it's been quite a while since the RFC was merged. Known outstanding review comments: * [x] @steveklabnik requested a new chapter for the unstable version of The Book -- please see if the proposed revisions to the second edition cover it. * [x] @nodakai asked if it were possible to merge the internal methods `_print` and `_eprint` - not completely, since they both refer to different internal globals which we don't want to expose, but I will see if some duplication can be factored out. Please let me know if I missed anything.
2 parents bb8d51c + 72588a2 commit a00e182

File tree

6 files changed

+128
-26
lines changed

6 files changed

+128
-26
lines changed

src/doc/unstable-book/src/SUMMARY.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -178,7 +178,7 @@
178178
- [peek](library-features/peek.md)
179179
- [placement_in](library-features/placement-in.md)
180180
- [placement_new_protocol](library-features/placement-new-protocol.md)
181-
- [print](library-features/print.md)
181+
- [print_internals](library-features/print-internals.md)
182182
- [proc_macro_internals](library-features/proc-macro-internals.md)
183183
- [process_try_wait](library-features/process-try-wait.md)
184184
- [question_mark_carrier](library-features/question-mark-carrier.md)

src/doc/unstable-book/src/library-features/print.md renamed to src/doc/unstable-book/src/library-features/print-internals.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
# `print`
1+
# `print_internals`
22

33
This feature is internal to the Rust compiler and is not intended for general use.
44

src/libstd/io/mod.rs

+3-1
Original file line numberDiff line numberDiff line change
@@ -287,9 +287,11 @@ pub use self::error::{Result, Error, ErrorKind};
287287
#[stable(feature = "rust1", since = "1.0.0")]
288288
pub use self::util::{copy, sink, Sink, empty, Empty, repeat, Repeat};
289289
#[stable(feature = "rust1", since = "1.0.0")]
290-
pub use self::stdio::{stdin, stdout, stderr, _print, Stdin, Stdout, Stderr};
290+
pub use self::stdio::{stdin, stdout, stderr, Stdin, Stdout, Stderr};
291291
#[stable(feature = "rust1", since = "1.0.0")]
292292
pub use self::stdio::{StdoutLock, StderrLock, StdinLock};
293+
#[unstable(feature = "print_internals", issue = "0")]
294+
pub use self::stdio::{_print, _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

+37-22
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ use io::{self, BufReader, LineWriter};
1717
use sync::{Arc, Mutex, MutexGuard};
1818
use sys::stdio;
1919
use sys_common::remutex::{ReentrantMutex, ReentrantMutexGuard};
20-
use thread::LocalKeyState;
20+
use thread::{LocalKey, LocalKeyState};
2121

2222
/// Stdout used by print! and println! macros
2323
thread_local! {
@@ -659,41 +659,56 @@ pub fn set_print(sink: Option<Box<Write + Send>>) -> Option<Box<Write + Send>> {
659659
})
660660
}
661661

662-
#[unstable(feature = "print",
663-
reason = "implementation detail which may disappear or be replaced at any time",
664-
issue = "0")]
665-
#[doc(hidden)]
666-
pub fn _print(args: fmt::Arguments) {
667-
// As an implementation of the `println!` macro, we want to try our best to
668-
// not panic wherever possible and get the output somewhere. There are
669-
// currently two possible vectors for panics we take care of here:
670-
//
671-
// 1. If the TLS key for the local stdout has been destroyed, accessing it
672-
// would cause a panic. Note that we just lump in the uninitialized case
673-
// here for convenience, we're not trying to avoid a panic.
674-
// 2. If the local stdout is currently in use (e.g. we're in the middle of
675-
// already printing) then accessing again would cause a panic.
676-
//
677-
// If, however, the actual I/O causes an error, we do indeed panic.
678-
let result = match LOCAL_STDOUT.state() {
662+
/// Write `args` to output stream `local_s` if possible, `global_s`
663+
/// otherwise. `label` identifies the stream in a panic message.
664+
///
665+
/// This function is used to print error messages, so it takes extra
666+
/// care to avoid causing a panic when `local_stream` is unusable.
667+
/// For instance, if the TLS key for the local stream is uninitialized
668+
/// or already destroyed, or if the local stream is locked by another
669+
/// thread, it will just fall back to the global stream.
670+
///
671+
/// However, if the actual I/O causes an error, this function does panic.
672+
fn print_to<T>(args: fmt::Arguments,
673+
local_s: &'static LocalKey<RefCell<Option<Box<Write+Send>>>>,
674+
global_s: fn() -> T,
675+
label: &str) where T: Write {
676+
let result = match local_s.state() {
679677
LocalKeyState::Uninitialized |
680-
LocalKeyState::Destroyed => stdout().write_fmt(args),
678+
LocalKeyState::Destroyed => global_s().write_fmt(args),
681679
LocalKeyState::Valid => {
682-
LOCAL_STDOUT.with(|s| {
680+
local_s.with(|s| {
683681
if let Ok(mut borrowed) = s.try_borrow_mut() {
684682
if let Some(w) = borrowed.as_mut() {
685683
return w.write_fmt(args);
686684
}
687685
}
688-
stdout().write_fmt(args)
686+
global_s().write_fmt(args)
689687
})
690688
}
691689
};
692690
if let Err(e) = result {
693-
panic!("failed printing to stdout: {}", e);
691+
panic!("failed printing to {}: {}", label, e);
694692
}
695693
}
696694

695+
#[unstable(feature = "print_internals",
696+
reason = "implementation detail which may disappear or be replaced at any time",
697+
issue = "0")]
698+
#[doc(hidden)]
699+
pub fn _print(args: fmt::Arguments) {
700+
print_to(args, &LOCAL_STDOUT, stdout, "stdout");
701+
}
702+
703+
#[unstable(feature = "print_internals",
704+
reason = "implementation detail which may disappear or be replaced at any time",
705+
issue = "0")]
706+
#[doc(hidden)]
707+
pub fn _eprint(args: fmt::Arguments) {
708+
use panicking::LOCAL_STDERR;
709+
print_to(args, &LOCAL_STDERR, stderr, "stderr");
710+
}
711+
697712
#[cfg(test)]
698713
mod tests {
699714
use thread;

src/libstd/macros.rs

+46-1
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,9 +108,12 @@ 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
///
110-
/// Panics if writing to `io::stdout()` fails.
116+
/// Panics if writing to `io::stdout` fails.
111117
///
112118
/// # Examples
113119
///
@@ -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+
#[stable(feature = "eprint", since="1.18.0")]
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+
#[stable(feature = "eprint", since="1.18.0")]
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+
// ignore-emscripten spawning processes is not supported
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)