diff --git a/src/liballoc/macros.rs b/src/liballoc/macros.rs index 763f04fcd0d..d489229e27c 100644 --- a/src/liballoc/macros.rs +++ b/src/liballoc/macros.rs @@ -8,12 +8,12 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -/// Creates a `Vec` containing the arguments. +/// Creates a [`Vec`] containing the arguments. /// /// `vec!` allows `Vec`s to be defined with the same syntax as array expressions. /// There are two forms of this macro: /// -/// - Create a `Vec` containing a given list of elements: +/// - Create a [`Vec`] containing a given list of elements: /// /// ``` /// let v = vec![1, 2, 3]; @@ -22,7 +22,7 @@ /// assert_eq!(v[2], 3); /// ``` /// -/// - Create a `Vec` from a given element and size: +/// - Create a [`Vec`] from a given element and size: /// /// ``` /// let v = vec![1; 3]; @@ -30,14 +30,17 @@ /// ``` /// /// Note that unlike array expressions this syntax supports all elements -/// which implement `Clone` and the number of elements doesn't have to be +/// which implement [`Clone`] and the number of elements doesn't have to be /// a constant. /// -/// This will use `clone()` to duplicate an expression, so one should be careful +/// This will use `clone` to duplicate an expression, so one should be careful /// using this with types having a nonstandard `Clone` implementation. For /// example, `vec![Rc::new(1); 5]` will create a vector of five references /// to the same boxed integer value, not five references pointing to independently /// boxed integers. +/// +/// [`Vec`]: ../std/vec/struct.Vec.html +/// [`Clone`]: ../std/clone/trait.Clone.html #[cfg(not(test))] #[macro_export] #[stable(feature = "rust1", since = "1.0.0")] @@ -67,10 +70,22 @@ macro_rules! vec { ($($x:expr,)*) => (vec![$($x),*]) } -/// Use the syntax described in `std::fmt` to create a value of type `String`. -/// See [`std::fmt`][fmt] for more information. +/// Creates a `String` using interpolation of runtime expressions. +/// +/// The first argument `format!` recieves is a format string. This must be a string +/// literal. The power of the formatting string is in the `{}`s contained. +/// +/// Additional parameters passed to `format!` replace the `{}`s within the +/// formatting string in the order given unless named or positional parameters +/// are used, see [`std::fmt`][fmt] for more information. +/// +/// A common use for `format!` is concatenation and interpolation of strings. +/// The same convention is used with [`print!`] and [`write!`] macros, +/// depending on the intended destination of the string. /// /// [fmt]: ../std/fmt/index.html +/// [`print!`]: macro.print.html +/// [`write!`]: macro.write.html /// /// # Panics /// diff --git a/src/libcore/macros.rs b/src/libcore/macros.rs index 684b81a27f8..6e652c8b898 100644 --- a/src/libcore/macros.rs +++ b/src/libcore/macros.rs @@ -62,11 +62,13 @@ macro_rules! panic { /// # Custom Messages /// /// This macro has a second form, where a custom panic message can -/// be provided with or without arguments for formatting. +/// be provided with or without arguments for formatting. See [`std::fmt`] +/// for syntax for this form. /// /// [`panic!`]: macro.panic.html /// [`debug_assert!`]: macro.debug_assert.html -/// [testing]: ../book/first-edition/testing.html +/// [testing]: ../book/second-edition/ch11-01-writing-tests.html#checking-results-with-the-assert-macro +/// [`std::fmt`]: ../std/fmt/index.html /// /// # Examples /// @@ -252,13 +254,15 @@ macro_rules! debug_assert { /// On panic, this macro will print the values of the expressions with their /// debug representations. /// -/// Unlike `assert_eq!`, `debug_assert_eq!` statements are only enabled in non +/// Unlike [`assert_eq!`], `debug_assert_eq!` statements are only enabled in non /// optimized builds by default. An optimized build will omit all /// `debug_assert_eq!` statements unless `-C debug-assertions` is passed to the /// compiler. This makes `debug_assert_eq!` useful for checks that are too /// expensive to be present in a release build but may be helpful during /// development. /// +/// [`assert_eq!`]: ../std/macro.assert_eq.html +/// /// # Examples /// /// ``` @@ -277,13 +281,15 @@ macro_rules! debug_assert_eq { /// On panic, this macro will print the values of the expressions with their /// debug representations. /// -/// Unlike `assert_ne!`, `debug_assert_ne!` statements are only enabled in non +/// Unlike [`assert_ne!`], `debug_assert_ne!` statements are only enabled in non /// optimized builds by default. An optimized build will omit all /// `debug_assert_ne!` statements unless `-C debug-assertions` is passed to the /// compiler. This makes `debug_assert_ne!` useful for checks that are too /// expensive to be present in a release build but may be helpful during /// development. /// +/// [`assert_ne!`]: ../std/macro.assert_ne.html +/// /// # Examples /// /// ``` @@ -300,10 +306,9 @@ macro_rules! debug_assert_ne { /// Helper macro for reducing boilerplate code for matching `Result` together /// with converting downstream errors. /// -/// Prefer using `?` syntax to `try!`. `?` is built in to the language and is -/// more succinct than `try!`. It is the standard method for error propagation. +/// The `?` operator was added to replace `try!` and should be used instead. /// -/// `try!` matches the given `Result`. In case of the `Ok` variant, the +/// `try!` matches the given [`Result`]. In case of the `Ok` variant, the /// expression has the value of the wrapped value. /// /// In case of the `Err` variant, it retrieves the inner error. `try!` then @@ -312,7 +317,9 @@ macro_rules! debug_assert_ne { /// error is then immediately returned. /// /// Because of the early return, `try!` can only be used in functions that -/// return `Result`. +/// return [`Result`]. +/// +/// [`Result`]: ../std/result/enum.Result.html /// /// # Examples /// @@ -331,12 +338,19 @@ macro_rules! debug_assert_ne { /// } /// } /// +/// // The prefered method of quick returning Errors +/// fn write_to_file_question() -> Result<(), MyError> { +/// let mut file = File::create("my_best_friends.txt")?; +/// Ok(()) +/// } +/// +/// // The previous method of quick returning Errors /// fn write_to_file_using_try() -> Result<(), MyError> { /// let mut file = try!(File::create("my_best_friends.txt")); /// try!(file.write_all(b"This is a list of my best friends.")); -/// println!("I wrote to the file"); /// Ok(()) /// } +/// /// // This is equivalent to: /// fn write_to_file_using_match() -> Result<(), MyError> { /// let mut file = try!(File::create("my_best_friends.txt")); @@ -344,7 +358,6 @@ macro_rules! debug_assert_ne { /// Ok(v) => v, /// Err(e) => return Err(From::from(e)), /// } -/// println!("I wrote to the file"); /// Ok(()) /// } /// ``` @@ -365,7 +378,7 @@ macro_rules! try { /// formatted according to the specified format string and the result will be passed to the writer. /// The writer may be any value with a `write_fmt` method; generally this comes from an /// implementation of either the [`std::fmt::Write`] or the [`std::io::Write`] trait. The macro -/// returns whatever the 'write_fmt' method returns; commonly a [`std::fmt::Result`], or an +/// returns whatever the `write_fmt` method returns; commonly a [`std::fmt::Result`], or an /// [`io::Result`]. /// /// See [`std::fmt`] for more information on the format string syntax. @@ -470,10 +483,20 @@ macro_rules! writeln { /// * Loops that dynamically terminate. /// * Iterators that dynamically terminate. /// +/// If the determination that the code is unreachable proves incorrect, the +/// program immediately terminates with a [`panic!`]. The function [`unreachable`], +/// which belongs to the [`std::intrinsics`] module, informs the compilier to +/// optimize the code out of the release version entirely. +/// +/// [`panic!`]: ../std/macro.panic.html +/// [`unreachable`]: ../std/intrinsics/fn.unreachable.html +/// [`std::intrinsics`]: ../std/intrinsics/index.html +/// /// # Panics /// -/// This will always [panic!](macro.panic.html) +/// This will always [`panic!`] /// +/// [`panic!`]: ../std/macro.panic.html /// # Examples /// /// Match arms: @@ -516,13 +539,18 @@ macro_rules! unreachable { }); } -/// A standardized placeholder for marking unfinished code. It panics with the -/// message `"not yet implemented"` when executed. +/// A standardized placeholder for marking unfinished code. +/// +/// It panics with the message `"not yet implemented"` when executed. /// /// This can be useful if you are prototyping and are just looking to have your /// code typecheck, or if you're implementing a trait that requires multiple /// methods, and you're only planning on using one of them. /// +/// # Panics +/// +/// This macro always panics. +/// /// # Examples /// /// Here's an example of some in-progress code. We have a trait `Foo`: diff --git a/src/libstd/macros.rs b/src/libstd/macros.rs index c426bf8086e..8c7f0fec926 100644 --- a/src/libstd/macros.rs +++ b/src/libstd/macros.rs @@ -26,13 +26,33 @@ macro_rules! __rust_unstable_column { /// The entry point for panic of Rust threads. /// +/// This allows a program to to terminate immediately and provide feedback +/// to the caller of the program. `panic!` should be used when a program reaches +/// an unrecoverable problem. +/// +/// This macro is the perfect way to assert conditions in example code and in +/// tests. `panic!` is closely tied with the `unwrap` method of both [`Option`] +/// and [`Result`][runwrap] enums. Both implementations call `panic!` when they are set +/// to None or Err variants. +/// /// This macro is used to inject panic into a Rust thread, causing the thread to /// panic entirely. Each thread's panic can be reaped as the `Box` type, /// and the single-argument form of the `panic!` macro will be the value which /// is transmitted. /// +/// [`Result`] enum is often a better solution for recovering from errors than +/// using the `panic!` macro. This macro should be used to avoid proceeding using +/// incorrect values, such as from external sources. Detailed information about +/// error handling is found in the [book]. +/// /// The multi-argument form of this macro panics with a string and has the -/// `format!` syntax for building a string. +/// [`format!`] syntax for building a string. +/// +/// [runwrap]: ../std/result/enum.Result.html#method.unwrap +/// [`Option`]: ../std/option/enum.Option.html#method.unwrap +/// [`Result`]: ../std/result/enum.Result.html +/// [`format!`]: ../std/macro.format.html +/// [book]: ../book/second-edition/ch09-01-unrecoverable-errors-with-panic.html /// /// # Current implementation /// @@ -78,15 +98,19 @@ macro_rules! panic { /// Macro for printing to the standard output. /// -/// Equivalent to the `println!` macro except that a newline is not printed at +/// Equivalent to the [`println!`] macro except that a newline is not printed at /// the end of the message. /// /// Note that stdout is frequently line-buffered by default so it may be -/// necessary to use `io::stdout().flush()` to ensure the output is emitted +/// necessary to use [`io::stdout().flush()`][flush] to ensure the output is emitted /// immediately. /// /// Use `print!` only for the primary output of your program. Use -/// `eprint!` instead to print error and progress messages. +/// [`eprint!`] instead to print error and progress messages. +/// +/// [`println!`]: ../std/macro.println.html +/// [flush]: ../std/io/trait.Write.html#tymethod.flush +/// [`eprint!`]: ../std/macro.eprint.html /// /// # Panics /// @@ -118,16 +142,20 @@ macro_rules! print { ($($arg:tt)*) => ($crate::io::_print(format_args!($($arg)*))); } -/// Macro for printing to the standard output, with a newline. On all -/// platforms, the newline is the LINE FEED character (`\n`/`U+000A`) alone +/// Macro for printing to the standard output, with a newline. +/// +/// On all platforms, the newline is the LINE FEED character (`\n`/`U+000A`) alone /// (no additional CARRIAGE RETURN (`\r`/`U+000D`). /// -/// Use the `format!` syntax to write data to the standard output. -/// See `std::fmt` for more information. +/// Use the [`format!`] syntax to write data to the standard output. +/// See [`std::fmt`] for more information. /// /// Use `println!` only for the primary output of your program. Use -/// `eprintln!` instead to print error and progress messages. +/// [`eprintln!`] instead to print error and progress messages. /// +/// [`format!`]: ../std/macro.format.html +/// [`std::fmt`]: ../std/fmt/index.html +/// [`eprintln!`]: ..std/macro.eprint.html /// # Panics /// /// Panics if writing to `io::stdout` fails. @@ -149,16 +177,25 @@ macro_rules! println { /// Macro for printing to the standard error. /// -/// Equivalent to the `print!` macro, except that output goes to -/// `io::stderr` instead of `io::stdout`. See `print!` for +/// Equivalent to the [`print!`] macro, except that output goes to +/// [`io::stderr`] instead of `io::stdout`. See [`print!`] for /// example usage. /// /// Use `eprint!` only for error and progress messages. Use `print!` /// instead for the primary output of your program. /// +/// [`io::stderr`]: ../std/io/struct.Stderr.html +/// [`print!`]: ../std/macro.print.html +/// /// # Panics /// /// Panics if writing to `io::stderr` fails. +/// +/// # Examples +/// +/// ``` +/// eprint("Error: Could not complete task"); +/// ``` #[macro_export] #[stable(feature = "eprint", since = "1.19.0")] #[allow_internal_unstable] @@ -168,16 +205,25 @@ macro_rules! eprint { /// Macro for printing to the standard error, with a newline. /// -/// Equivalent to the `println!` macro, except that output goes to -/// `io::stderr` instead of `io::stdout`. See `println!` for +/// Equivalent to the [`println!`] macro, except that output goes to +/// [`io::stderr`] instead of `io::stdout`. See [`println!`] for /// example usage. /// /// Use `eprintln!` only for error and progress messages. Use `println!` /// instead for the primary output of your program. /// +/// [`io::stderr`]: ../std/io/struct.Stderr.html +/// [`println!`]: ../std/macro.println.html +/// /// # Panics /// /// Panics if writing to `io::stderr` fails. +/// +/// # Examples +/// +/// ``` +/// eprint("Error: Could not complete task"); +/// ``` #[macro_export] #[stable(feature = "eprint", since = "1.19.0")] macro_rules! eprintln { @@ -267,13 +313,23 @@ pub mod builtin { /// The core macro for formatted string creation & output. /// + /// This macro functions by taking a formatting string literal containing + /// `{}` for each additional argument passed. `format_args!` prepares the + /// additional parameters to ensure the output can be interpreted as a string + /// and canonicalizes the arguments into a single type. Any value that implements + /// the [`Display`] trait can be passed to `format_args!`, as can any + /// [`Debug`] implementation be passed to a `{:?}` within the formatting string. + /// /// This macro produces a value of type [`fmt::Arguments`]. This value can be - /// passed to the functions in [`std::fmt`] for performing useful functions. + /// passed to the macros within [`std::fmt`] for performing useful redirection. /// All other formatting macros ([`format!`], [`write!`], [`println!`], etc) are - /// proxied through this one. + /// proxied through this one. `format_args!`, unlike its derived macros, avoids + /// heap allocations. /// /// For more information, see the documentation in [`std::fmt`]. /// + /// [`Display`]: ../std/fmt/trait.Display.html + /// [`Debug`]: ../std/fmt/trait.Debug.html /// [`fmt::Arguments`]: ../std/fmt/struct.Arguments.html /// [`std::fmt`]: ../std/fmt/index.html /// [`format!`]: ../std/macro.format.html @@ -301,9 +357,11 @@ pub mod builtin { /// compile time, yielding an expression of type `&'static str`. /// /// If the environment variable is not defined, then a compilation error - /// will be emitted. To not emit a compile error, use the `option_env!` + /// will be emitted. To not emit a compile error, use the [`option_env!`] /// macro instead. /// + /// [`option_env!`]: ../std/macro.option_env.html + /// /// # Examples /// /// ``` @@ -319,11 +377,14 @@ pub mod builtin { /// If the named environment variable is present at compile time, this will /// expand into an expression of type `Option<&'static str>` whose value is /// `Some` of the value of the environment variable. If the environment - /// variable is not present, then this will expand to `None`. + /// variable is not present, then this will expand to `None`. See + /// [`Option`][option] for more information on this type. /// /// A compile time error is never emitted when using this macro regardless /// of whether the environment variable is present or not. /// + /// [option]: ../std/option/enum.Option.html + /// /// # Examples /// /// ``` @@ -385,10 +446,16 @@ pub mod builtin { /// A macro which expands to the line number on which it was invoked. /// + /// With [`column!`] and [`file!`], these macros provide debugging information for + /// developers about the location within the source. + /// /// The expanded expression has type `u32`, and the returned line is not /// the invocation of the `line!()` macro itself, but rather the first macro /// invocation leading up to the invocation of the `line!()` macro. /// + /// [`column!`]: macro.column.html + /// [`file!`]: macro.file.html + /// /// # Examples /// /// ``` @@ -401,9 +468,15 @@ pub mod builtin { /// A macro which expands to the column number on which it was invoked. /// + /// With [`line!`] and [`file!`], these macros provide debugging information for + /// developers about the location within the source. + /// /// The expanded expression has type `u32`, and the returned column is not - /// the invocation of the `column!()` macro itself, but rather the first macro - /// invocation leading up to the invocation of the `column!()` macro. + /// the invocation of the `column!` macro itself, but rather the first macro + /// invocation leading up to the invocation of the `column!` macro. + /// + /// [`line!`]: macro.line.html + /// [`file!`]: macro.file.html /// /// # Examples /// @@ -417,11 +490,18 @@ pub mod builtin { /// A macro which expands to the file name from which it was invoked. /// + /// With [`line!`] and [`column!`], these macros provide debugging information for + /// developers about the location within the source. + /// + /// /// The expanded expression has type `&'static str`, and the returned file - /// is not the invocation of the `file!()` macro itself, but rather the - /// first macro invocation leading up to the invocation of the `file!()` + /// is not the invocation of the `file!` macro itself, but rather the + /// first macro invocation leading up to the invocation of the `file!` /// macro. /// + /// [`line!`]: macro.line.html + /// [`column!`]: macro.column.html + /// /// # Examples /// /// ```