#let #if #else #1303

guard

Macro implementation of RFC 1303: a guard-let-else statement a la Swift

16 releases

Uses old Rust 2015

0.5.2 Jun 4, 2023
0.5.1 Apr 11, 2021
0.5.0 Dec 26, 2018
0.3.4 Mar 22, 2018
0.1.1 Nov 27, 2015

#1 in #if

Download history 1052/week @ 2023-11-20 514/week @ 2023-11-27 1636/week @ 2023-12-04 1428/week @ 2023-12-11 741/week @ 2023-12-18 466/week @ 2023-12-25 644/week @ 2024-01-01 1119/week @ 2024-01-08 1175/week @ 2024-01-15 1117/week @ 2024-01-22 838/week @ 2024-01-29 1335/week @ 2024-02-05 1380/week @ 2024-02-12 1409/week @ 2024-02-19 1380/week @ 2024-02-26 846/week @ 2024-03-04

5,021 downloads per month
Used in 4 crates

MIT/Apache

30KB
348 lines

guard

Travis CI

This feature has finally been officially added to Rust. This crate should be considered deprecated once #![feature(let_else)] is stabilized.

This crate exports a macro which implements most of RFC 3137 (originally RFC 1303), a "let-else" or "guard" expression as you can find in Swift.

The syntax decided upon in the RFC is let PAT = EXPR else { BODY } (where BODY must diverge). This macro understands mostly what has been implemented in the compiler, with a few limitations detailed below, as well as a variation proposed in the first RFC with the else clause in the middle.

The crate also implements a variant guard_unwrap that panics if the match fails.

Examples

#[macro_use] extern crate guard;
use std::env;

fn main() {
    // read configuration from a certain environment variable
    // do nothing if the variable is missing
    guard!(let Ok(foo) = env::var("FOO") else { return });

    println!("FOO = {}", foo);
}

Cargo features

  • nightly was historically required to avoid warnings when compiling with a nightly compiler. It now does nothing and is kept around only for backwards-compatibility purposes.
  • debug enables trace_macros for debugging. Requires a nightly compiler (but not this crate's nightly feature).

How it works

It's difficult to implement this behavior as a macro, because a let statement must be created in the enclosing scope. Besides that, it is desirable to avoid the necessity of repeating the identifiers bound by the pattern. The strategy used here is to scan the pattern for identifiers, and use that to construct a top-level let statement which internally uses a match to apply the pattern. This scanning is almost possible -- see limitations #1 and #2 below.

This strategy also means that PAT needs to be input to the macro as an unparsed sequence of token trees. There are two ways to take an unbounded sequence of token trees as input without causing ambiguity errors: put the token trees at the end (my current choice) or enclose them in brackets. Originally, this choice resulted in a backwards invocation syntax. Since version 0.2.0, more convenient syntaxes are supported by adopting a two-pass parsing strategy: the macro essentially takes its entire input as a sequence of tokens, splits on = and else, then parses the results again.

There are a number of subtleties in the expansion to avoid various warning and pitfalls; see the macro source for more details.

Limitations

  1. Expressions in the pattern are not supported. This is a limitation of the current Rust macro system -- I'd like to say "parse an identifier in this position, but if that fails try parsing an expression" but this is is impossible; I can only test for specific identifiers. It's easy to get around this restriction: use a pattern guard (as in match) instead.
  2. Empty, un-namespaced enum variants and structs cause the expansion to fail, because the macro thinks they are identifiers. It's possible to get around this as well, though an open PR is aiming to take away the easiest workaround:
    • For empty enum variants, use Empty(..) until #29383 turns into an error, after that include the enum name as in Enum::Empty. (For now you will get a warning.)
    • For unit-like structs, use Empty(..) until #29383 turns into an error, after that namespace it as in namespace::Empty, or use Empty{} (requires #![feature(braced_empty_structs)]). (For now you will get a warning.)
    • Of course you can also use a path to reference the variant or struct, though this may be impossible (if it's local to a function/block) or inconvenient (if it was imported from another module or crate).
  3. PAT cannot be irrefutable. This is the same behavior as if let and match, and it's useless to write a guard with an irrefutable pattern anyway (you can just use let), so this shouldn't be an issue. This is slightly more annoying than it could be due to limitation #1. Nonetheless, if #14252 is ever fixed, irrefutable patterns could be allowed by inserting a no-op pattern guard into the expansion.

Differences with the rustc implementation

  • Parentheses around or-patterns are not necessary
  • Cannot use a ref binding to a non-copy value (you'll get a borrowck error)

No runtime deps

Features