API docs: macros. Part of #29329 Standard Library Documentation Checklist.

This commit is contained in:
Andy Gauge 2017-08-29 10:17:33 -07:00
parent faf477a8c2
commit b9b654924e
3 changed files with 165 additions and 42 deletions

View file

@ -8,12 +8,12 @@
// option. This file may not be copied, modified, or distributed // option. This file may not be copied, modified, or distributed
// except according to those terms. // 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. /// `vec!` allows `Vec`s to be defined with the same syntax as array expressions.
/// There are two forms of this macro: /// 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]; /// let v = vec![1, 2, 3];
@ -22,7 +22,7 @@
/// assert_eq!(v[2], 3); /// 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]; /// let v = vec![1; 3];
@ -30,14 +30,17 @@
/// ``` /// ```
/// ///
/// Note that unlike array expressions this syntax supports all elements /// 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. /// 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 /// using this with types having a nonstandard `Clone` implementation. For
/// example, `vec![Rc::new(1); 5]` will create a vector of five references /// 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 /// to the same boxed integer value, not five references pointing to independently
/// boxed integers. /// boxed integers.
///
/// [`Vec`]: ../std/vec/struct.Vec.html
/// [`Clone`]: ../std/clone/trait.Clone.html
#[cfg(not(test))] #[cfg(not(test))]
#[macro_export] #[macro_export]
#[stable(feature = "rust1", since = "1.0.0")] #[stable(feature = "rust1", since = "1.0.0")]
@ -67,10 +70,22 @@ macro_rules! vec {
($($x:expr,)*) => (vec![$($x),*]) ($($x:expr,)*) => (vec![$($x),*])
} }
/// Use the syntax described in `std::fmt` to create a value of type `String`. /// Creates a `String` using interpolation of runtime expressions.
/// See [`std::fmt`][fmt] for more information. ///
/// 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 /// [fmt]: ../std/fmt/index.html
/// [`print!`]: macro.print.html
/// [`write!`]: macro.write.html
/// ///
/// # Panics /// # Panics
/// ///

View file

@ -62,11 +62,13 @@ macro_rules! panic {
/// # Custom Messages /// # Custom Messages
/// ///
/// This macro has a second form, where a custom panic message can /// 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 /// [`panic!`]: macro.panic.html
/// [`debug_assert!`]: macro.debug_assert.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 /// # Examples
/// ///
@ -252,13 +254,15 @@ macro_rules! debug_assert {
/// On panic, this macro will print the values of the expressions with their /// On panic, this macro will print the values of the expressions with their
/// debug representations. /// 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 /// optimized builds by default. An optimized build will omit all
/// `debug_assert_eq!` statements unless `-C debug-assertions` is passed to the /// `debug_assert_eq!` statements unless `-C debug-assertions` is passed to the
/// compiler. This makes `debug_assert_eq!` useful for checks that are too /// 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 /// expensive to be present in a release build but may be helpful during
/// development. /// development.
/// ///
/// [`assert_eq!`]: ../std/macro.assert_eq.html
///
/// # Examples /// # Examples
/// ///
/// ``` /// ```
@ -277,13 +281,15 @@ macro_rules! debug_assert_eq {
/// On panic, this macro will print the values of the expressions with their /// On panic, this macro will print the values of the expressions with their
/// debug representations. /// 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 /// optimized builds by default. An optimized build will omit all
/// `debug_assert_ne!` statements unless `-C debug-assertions` is passed to the /// `debug_assert_ne!` statements unless `-C debug-assertions` is passed to the
/// compiler. This makes `debug_assert_ne!` useful for checks that are too /// 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 /// expensive to be present in a release build but may be helpful during
/// development. /// development.
/// ///
/// [`assert_ne!`]: ../std/macro.assert_ne.html
///
/// # Examples /// # Examples
/// ///
/// ``` /// ```
@ -300,10 +306,9 @@ macro_rules! debug_assert_ne {
/// Helper macro for reducing boilerplate code for matching `Result` together /// Helper macro for reducing boilerplate code for matching `Result` together
/// with converting downstream errors. /// with converting downstream errors.
/// ///
/// Prefer using `?` syntax to `try!`. `?` is built in to the language and is /// The `?` operator was added to replace `try!` and should be used instead.
/// more succinct than `try!`. It is the standard method for error propagation.
/// ///
/// `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. /// expression has the value of the wrapped value.
/// ///
/// In case of the `Err` variant, it retrieves the inner error. `try!` then /// 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. /// error is then immediately returned.
/// ///
/// Because of the early return, `try!` can only be used in functions that /// Because of the early return, `try!` can only be used in functions that
/// return `Result`. /// return [`Result`].
///
/// [`Result`]: ../std/result/enum.Result.html
/// ///
/// # Examples /// # 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> { /// fn write_to_file_using_try() -> Result<(), MyError> {
/// let mut file = try!(File::create("my_best_friends.txt")); /// let mut file = try!(File::create("my_best_friends.txt"));
/// try!(file.write_all(b"This is a list of my best friends.")); /// try!(file.write_all(b"This is a list of my best friends."));
/// println!("I wrote to the file");
/// Ok(()) /// Ok(())
/// } /// }
///
/// // This is equivalent to: /// // This is equivalent to:
/// fn write_to_file_using_match() -> Result<(), MyError> { /// fn write_to_file_using_match() -> Result<(), MyError> {
/// let mut file = try!(File::create("my_best_friends.txt")); /// let mut file = try!(File::create("my_best_friends.txt"));
@ -344,7 +358,6 @@ macro_rules! debug_assert_ne {
/// Ok(v) => v, /// Ok(v) => v,
/// Err(e) => return Err(From::from(e)), /// Err(e) => return Err(From::from(e)),
/// } /// }
/// println!("I wrote to the file");
/// Ok(()) /// Ok(())
/// } /// }
/// ``` /// ```
@ -365,7 +378,7 @@ macro_rules! try {
/// formatted according to the specified format string and the result will be passed to the writer. /// 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 /// 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 /// 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`]. /// [`io::Result`].
/// ///
/// See [`std::fmt`] for more information on the format string syntax. /// See [`std::fmt`] for more information on the format string syntax.
@ -470,10 +483,20 @@ macro_rules! writeln {
/// * Loops that dynamically terminate. /// * Loops that dynamically terminate.
/// * Iterators 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 /// # Panics
/// ///
/// This will always [panic!](macro.panic.html) /// This will always [`panic!`]
/// ///
/// [`panic!`]: ../std/macro.panic.html
/// # Examples /// # Examples
/// ///
/// Match arms: /// Match arms:
@ -516,13 +539,18 @@ macro_rules! unreachable {
}); });
} }
/// A standardized placeholder for marking unfinished code. It panics with the /// A standardized placeholder for marking unfinished code.
/// message `"not yet implemented"` when executed. ///
/// 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 /// 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 /// code typecheck, or if you're implementing a trait that requires multiple
/// methods, and you're only planning on using one of them. /// methods, and you're only planning on using one of them.
/// ///
/// # Panics
///
/// This macro always panics.
///
/// # Examples /// # Examples
/// ///
/// Here's an example of some in-progress code. We have a trait `Foo`: /// Here's an example of some in-progress code. We have a trait `Foo`:

View file

@ -26,13 +26,33 @@ macro_rules! __rust_unstable_column {
/// The entry point for panic of Rust threads. /// 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 /// 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<Any>` type, /// panic entirely. Each thread's panic can be reaped as the `Box<Any>` type,
/// and the single-argument form of the `panic!` macro will be the value which /// and the single-argument form of the `panic!` macro will be the value which
/// is transmitted. /// 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 /// 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 /// # Current implementation
/// ///
@ -78,15 +98,19 @@ macro_rules! panic {
/// Macro for printing to the standard output. /// 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. /// the end of the message.
/// ///
/// Note that stdout is frequently line-buffered by default so it may be /// 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. /// immediately.
/// ///
/// Use `print!` only for the primary output of your program. Use /// 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 /// # Panics
/// ///
@ -118,16 +142,20 @@ macro_rules! print {
($($arg:tt)*) => ($crate::io::_print(format_args!($($arg)*))); ($($arg:tt)*) => ($crate::io::_print(format_args!($($arg)*)));
} }
/// Macro for printing to the standard output, with a newline. On all /// Macro for printing to the standard output, with a newline.
/// platforms, the newline is the LINE FEED character (`\n`/`U+000A`) alone ///
/// On all platforms, the newline is the LINE FEED character (`\n`/`U+000A`) alone
/// (no additional CARRIAGE RETURN (`\r`/`U+000D`). /// (no additional CARRIAGE RETURN (`\r`/`U+000D`).
/// ///
/// Use the `format!` syntax to write data to the standard output. /// Use the [`format!`] syntax to write data to the standard output.
/// See `std::fmt` for more information. /// See [`std::fmt`] for more information.
/// ///
/// Use `println!` only for the primary output of your program. Use /// 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
/// ///
/// Panics if writing to `io::stdout` fails. /// Panics if writing to `io::stdout` fails.
@ -149,16 +177,25 @@ macro_rules! println {
/// Macro for printing to the standard error. /// Macro for printing to the standard error.
/// ///
/// Equivalent to the `print!` macro, except that output goes to /// Equivalent to the [`print!`] macro, except that output goes to
/// `io::stderr` instead of `io::stdout`. See `print!` for /// [`io::stderr`] instead of `io::stdout`. See [`print!`] for
/// example usage. /// example usage.
/// ///
/// Use `eprint!` only for error and progress messages. Use `print!` /// Use `eprint!` only for error and progress messages. Use `print!`
/// instead for the primary output of your program. /// instead for the primary output of your program.
/// ///
/// [`io::stderr`]: ../std/io/struct.Stderr.html
/// [`print!`]: ../std/macro.print.html
///
/// # Panics /// # Panics
/// ///
/// Panics if writing to `io::stderr` fails. /// Panics if writing to `io::stderr` fails.
///
/// # Examples
///
/// ```
/// eprint("Error: Could not complete task");
/// ```
#[macro_export] #[macro_export]
#[stable(feature = "eprint", since = "1.19.0")] #[stable(feature = "eprint", since = "1.19.0")]
#[allow_internal_unstable] #[allow_internal_unstable]
@ -168,16 +205,25 @@ macro_rules! eprint {
/// Macro for printing to the standard error, with a newline. /// Macro for printing to the standard error, with a newline.
/// ///
/// Equivalent to the `println!` macro, except that output goes to /// Equivalent to the [`println!`] macro, except that output goes to
/// `io::stderr` instead of `io::stdout`. See `println!` for /// [`io::stderr`] instead of `io::stdout`. See [`println!`] for
/// example usage. /// example usage.
/// ///
/// Use `eprintln!` only for error and progress messages. Use `println!` /// Use `eprintln!` only for error and progress messages. Use `println!`
/// instead for the primary output of your program. /// instead for the primary output of your program.
/// ///
/// [`io::stderr`]: ../std/io/struct.Stderr.html
/// [`println!`]: ../std/macro.println.html
///
/// # Panics /// # Panics
/// ///
/// Panics if writing to `io::stderr` fails. /// Panics if writing to `io::stderr` fails.
///
/// # Examples
///
/// ```
/// eprint("Error: Could not complete task");
/// ```
#[macro_export] #[macro_export]
#[stable(feature = "eprint", since = "1.19.0")] #[stable(feature = "eprint", since = "1.19.0")]
macro_rules! eprintln { macro_rules! eprintln {
@ -267,13 +313,23 @@ pub mod builtin {
/// The core macro for formatted string creation & output. /// 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 /// 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 /// 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`]. /// 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 /// [`fmt::Arguments`]: ../std/fmt/struct.Arguments.html
/// [`std::fmt`]: ../std/fmt/index.html /// [`std::fmt`]: ../std/fmt/index.html
/// [`format!`]: ../std/macro.format.html /// [`format!`]: ../std/macro.format.html
@ -301,9 +357,11 @@ pub mod builtin {
/// compile time, yielding an expression of type `&'static str`. /// compile time, yielding an expression of type `&'static str`.
/// ///
/// If the environment variable is not defined, then a compilation error /// 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. /// macro instead.
/// ///
/// [`option_env!`]: ../std/macro.option_env.html
///
/// # Examples /// # Examples
/// ///
/// ``` /// ```
@ -319,11 +377,14 @@ pub mod builtin {
/// If the named environment variable is present at compile time, this will /// If the named environment variable is present at compile time, this will
/// expand into an expression of type `Option<&'static str>` whose value is /// expand into an expression of type `Option<&'static str>` whose value is
/// `Some` of the value of the environment variable. If the environment /// `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<T>`][option] for more information on this type.
/// ///
/// A compile time error is never emitted when using this macro regardless /// A compile time error is never emitted when using this macro regardless
/// of whether the environment variable is present or not. /// of whether the environment variable is present or not.
/// ///
/// [option]: ../std/option/enum.Option.html
///
/// # Examples /// # Examples
/// ///
/// ``` /// ```
@ -385,10 +446,16 @@ pub mod builtin {
/// A macro which expands to the line number on which it was invoked. /// 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 expanded expression has type `u32`, and the returned line is not
/// the invocation of the `line!()` macro itself, but rather the first macro /// the invocation of the `line!()` macro itself, but rather the first macro
/// invocation leading up to the invocation of the `line!()` macro. /// invocation leading up to the invocation of the `line!()` macro.
/// ///
/// [`column!`]: macro.column.html
/// [`file!`]: macro.file.html
///
/// # Examples /// # Examples
/// ///
/// ``` /// ```
@ -401,9 +468,15 @@ pub mod builtin {
/// A macro which expands to the column number on which it was invoked. /// 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 expanded expression has type `u32`, and the returned column is not
/// the invocation of the `column!()` macro itself, but rather the first macro /// the invocation of the `column!` macro itself, but rather the first macro
/// invocation leading up to the invocation of the `column!()` macro. /// invocation leading up to the invocation of the `column!` macro.
///
/// [`line!`]: macro.line.html
/// [`file!`]: macro.file.html
/// ///
/// # Examples /// # Examples
/// ///
@ -417,11 +490,18 @@ pub mod builtin {
/// A macro which expands to the file name from which it was invoked. /// 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 /// The expanded expression has type `&'static str`, and the returned file
/// is not the invocation of the `file!()` macro itself, but rather the /// is not the invocation of the `file!` macro itself, but rather the
/// first macro invocation leading up to the invocation of the `file!()` /// first macro invocation leading up to the invocation of the `file!`
/// macro. /// macro.
/// ///
/// [`line!`]: macro.line.html
/// [`column!`]: macro.column.html
///
/// # Examples /// # Examples
/// ///
/// ``` /// ```