Debian Codegraph @

src/lib.rs

raw symbols SCIP
1 //! Fallible pattern matching with a function-like syntax
2 //!
3 //! # Basic Usage
4 //!
5 //! ## Macros
6 //!
7 //! [`try_match!`] returns [`Result`]: `Ok(bindings)` on success or
8 //! `Err(input)` on failure:
9 //!
10 //! ```rust
11 //! # use try_match::try_match;
12 //! # #[derive(Copy, Clone, Debug, PartialEq)]
13 //! # enum Enum<T> { Var1(T), Var2 }
14 //! # use Enum::{Var1, Var2};
15 //! assert_eq!(try_match!(Var1(42), Var1(x)), Ok(42));
16 //! assert_eq!(try_match!(Var1(42), Var1(x) if x < 20), Err(Var1(42)));
17 //! ```
18 //!
19 //! [`match_ok!`] returns [`Option`]: `Some(bindings)` on success or
20 //! `None` on failure:
21 //!
22 //! ```rust
23 //! # use try_match::match_ok;
24 //! # #[derive(Copy, Clone, Debug, PartialEq)]
25 //! # enum Enum<T> { Var1(T), Var2 }
26 //! # use Enum::{Var1, Var2};
27 //! assert_eq!(match_ok!(Var1(42), Var1(x)), Some(42));
28 //! assert_eq!(match_ok!(Var1(42), Var1(x) if x < 20), None);
29 //! ```
30 //!
31 //! [`match_or_default!`] returns a default value on failure:
32 //!
33 //! ```rust
34 //! # use try_match::match_or_default;
35 //! # #[derive(Copy, Clone, Debug, PartialEq)]
36 //! # enum Enum<T> { Var1(T), Var2 }
37 //! # use Enum::{Var1, Var2};
38 //! assert_eq!(match_or_default!(Var1(42), Var1(x)), 42);
39 //! assert_eq!(match_or_default!(Var1(42), Var1(x) if x < 20), 0);
40 //! ```
41 //!
42 //! [`unwrap_match!`] panics on failure:
43 //!
44 //! ```rust
45 //! # use try_match::unwrap_match;
46 //! # #[derive(Copy, Clone, Debug, PartialEq)]
47 //! # enum Enum<T> { Var1(T), Var2 }
48 //! # use Enum::{Var1, Var2};
49 //! assert_eq!(unwrap_match!(Var1(42), Var1(x)), 42);
50 //! ```
51 //!
52 //! ```rust,should_panic
53 //! # use try_match::unwrap_match;
54 //! # #[derive(Copy, Clone, Debug, PartialEq)]
55 //! # enum Enum<T> { Var1(T), Var2 }
56 //! # use Enum::{Var1, Var2};
57 //! unwrap_match!(Var1(42), Var1(x) if x < 20);
58 //! ```
59 //!
60 //! ## Implicit Mapping
61 //!
62 //! *Requires `implicit_map` Cargo feature (enabled by default)*
63 //!
64 //! ```
65 //! use try_match::unwrap_match;
66 //!
67 //! #[derive(Debug, PartialEq)]
68 //! enum Enum<T> { Var1(T), Var2 }
69 //! use Enum::{Var1, Var2};
70 //!
71 //! // `()` if there are no bound variables
72 //! assert_eq!(unwrap_match!(Var1(42), Var1(_)), ());
73 //!
74 //! // The bound variable if there is exactly one bound variable
75 //! assert_eq!(unwrap_match!(Var1(42), Var1(x)), 42);
76 //!
77 //! // An anonymous struct if there are multiple bound variables
78 //! let vars = unwrap_match!(Var1((12, 34)), Var1((a, b)));
79 //! assert_eq!((vars.a, vars.b), (12, 34));
80 //! ```
81 //!
82 //! It produces a tuple if you name the bound variables like `_0`, `_1`, `_2`,
83 //! ...:
84 //!
85 //! ```
86 //! # use try_match::unwrap_match;
87 //! # #[derive(Debug, PartialEq)] enum Enum<T> { Var1(T), Var2 }
88 //! # use Enum::{Var1, Var2};
89 //! let (a, b) = unwrap_match!(Var1((12, 34)), Var1((_0, _1)));
90 //! assert_eq!((a, b), (12, 34));
91 //! ```
92 //!
93 //! It's an error to specify non-contiguous binding indices:
94 //!
95 //! ```compile_fail
96 //! # use try_match::unwrap_match;
97 //! # #[derive(Debug, PartialEq)] enum Enum<T> { Var1(T), Var2 }
98 //! # use Enum::{Var1, Var2};
99 //! unwrap_match!(Var1((12, 34)), Var1((_0, _2)));
100 //! ```
101 //!
102 //! ## Explicit Mapping
103 //!
104 //! An optional `=>` clause specifies an explicit output mapping:
105 //!
106 //! ```
107 //! # use try_match::unwrap_match;
108 //! # #[derive(Copy, Clone, Debug, PartialEq)]
109 //! # enum Enum<T> { Var1(T), Var2 }
110 //! # use Enum::{Var1, Var2};
111 //! // The right-hand side of `=>` if successful
112 //! assert_eq!(unwrap_match!(Var1(42), Var1(x) => x + 1), 43);
113 //! assert_eq!(unwrap_match!(Var2::<u32>, Var2 => "yay"), "yay");
114 //! ```
115 //!
116 //! ## Partial Application
117 //!
118 //! Omit the scrutinee expression to produce a closure:
119 //!
120 //! ```rust
121 //! # use try_match::try_match;
122 //! # #[derive(Debug, PartialEq)] enum Enum<T> { Var1(T), Var2 }
123 //! # use Enum::{Var1, Var2};
124 //! let _: Result<i32, _> = try_match!(Var1(42), Var1(x));
125 //! let _: fn(Enum<i32>) -> Result<i32, _> = try_match!( , Var1(x));
126 //!
127 //! assert_eq!(try_match!(Var1(42), Var1(x)), Ok(42));
128 //! // ^^^^^^^^ -------
129 //! assert_eq!(try_match!(, Var1(x))(Var1(42)), Ok(42));
130 //! // ------- ^^^^^^^^
131 //!
132 //! // Equivalent to:
133 //! assert_eq!((|x| try_match!(x, Var1(x)))(Var1(42)), Ok(42));
134 //! // ------- ^^^^^^^^
135 //! ```
136 //!
137 //! ```rust
138 //! # use try_match::try_match;
139 //! # #[derive(Debug, PartialEq)] enum Enum<T> { Var1(T), Var2 }
140 //! # use Enum::{Var1, Var2};
141 //! let array = [Var1(42), Var2, Var1(10)];
142 //! let filtered: Result<Vec<_>, _> = array
143 //! .iter()
144 //! .map(try_match!(, &Var1(_0) if _0 > 20))
145 //! .collect();
146 //!
147 //! // `Var2` is the first value that doesn't match
148 //! assert_eq!(filtered, Err(&Var2));
149 //! ```
150 //!
151 //! *Note:* Since this mode is implemented by a closure,
152 //! [the default binding mode][] ([RFC 2005][]), ownership, and control flow
153 //! may work differently.
154 //!
155 //! <details><summary>Examples (click to show)</summary>
156 //!
157 //! ```rust
158 //! # use try_match::try_match;
159 //! try_match!(&Some(42), Some(_0));
160 //! try_match!(&Some(42), &Some(ref _0));
161 //! ```
162 //!
163 //! ```rust,compile_fail
164 //! # use try_match::try_match;
165 //! try_match!(, Some(_0))(&Some(42));
166 //! // ERROR: expected enum `Option`, found reference
167 //! ```
168 //!
169 //! ```rust
170 //! # use try_match::try_match;
171 //! use std::rc::Rc;
172 //!
173 //! // `rc2` is conditionally dropped
174 //! let rc1 = Rc::new(());
175 //! let rc2 = Rc::clone(&rc1);
176 //! try_match!(None::<()>, Some(_) => drop(rc2));
177 //! assert_eq!(Rc::strong_count(&rc1), 2);
178 //!
179 //! // `rc2` is unconditionally moved into a closure and dropped
180 //! let rc1 = Rc::new(());
181 //! let rc2 = Rc::clone(&rc1);
182 //! try_match!(, Some(_) => drop(rc2))(None::<()>);
183 //! assert_eq!(Rc::strong_count(&rc1), 1);
184 //! ```
185 //!
186 //! ```rust
187 //! # use try_match::try_match;
188 //! fn func_uncurried() {
189 //! try_match!((), () => return);
190 //! unreachable!();
191 //! }
192 //!
193 //! fn func_curried() -> i32 {
194 //! try_match!(, () => return Ok(()))(());
195 //! 42 // reachable
196 //! }
197 //!
198 //! func_uncurried();
199 //! func_curried();
200 //! ```
201 //!
202 //! </details>
203 //!
204 //! [the default binding mode]: https://doc.rust-lang.org/1.69.0/reference/patterns.html#binding-modes
205 //! [RFC 2005]: https://rust-lang.github.io/rfcs/2005-match-ergonomics.html
206 //!
207 //! # Unstable Features
208 //!
209 //! *Requires `unstable` Cargo feature, exempt from semver guarantees.*
210 //!
211 //! No unstable features are defined in this version.
212 //!
213 //! # Quirks
214 //!
215 //! ## Macros Inside Patterns
216 //!
217 //! When using implicit mapping, bind variables defined inside macros are
218 //! not recognized because, at the point of `try_match`'s macro expansion,
219 //! these macros are not expanded yet.
220 //!
221 //! ## Input Ownership
222 //!
223 //! [`try_match!`] moves a value out of the place represented by the input
224 //! expression to return it on failure. Make sure to pass a reference if this is
225 //! not desired.
226 //!
227 //! ```compile_fail
228 //! # use try_match::try_match;
229 //! #[derive(Debug)] struct UncopyValue;
230 //! let array = [Some(UncopyValue), None];
231 //! // ERROR: Can't move out of `array[0]`
232 //! let _: &UncopyValue = try_match!(array[0], Some(ref x)).unwrap();
233 //! ```
234 //!
235 //! ```
236 //! # use try_match::try_match;
237 //! # #[derive(Debug)] struct UncopyValue;
238 //! # let array = [Some(UncopyValue), None];
239 //! let _: &UncopyValue = try_match!(&array[0], Some(x)).unwrap();
240 //! ```
241 //!
242 //! [`match_ok!`], [`match_or_default!`], and [`unwrap_match!`] do not have this
243 //! issue:
244 //!
245 //! ```rust
246 //! # use try_match::*;
247 //! # #[derive(Debug)] struct UncopyValue;
248 //! impl Default for &UncopyValue {
249 //! // ...
250 //! # fn default() -> Self { &UncopyValue }
251 //! }
252 //!
253 //! let array = [Some(UncopyValue), None];
254 //! let _: &UncopyValue = match_ok!(array[0], Some(ref x)).unwrap();
255 //! let _: &UncopyValue = match_or_default!(array[0], Some(ref x));
256 //! let _: &UncopyValue = unwrap_match!(array[0], Some(ref x));
257 //! ```
258 //!
259 //! ## Binding/Constant Disambiguation
260 //!
261 //! An identifier in a pattern is either a variable binding or a constant
262 //! pattern, and these cannot be distinguished syntactically. To address this
263 //! problem, the implicit mapper employs heuristics based on the standard naming
264 //! conventions ([RFC 430][]).
265 //!
266 //! ```rust
267 //! # use try_match::try_match;
268 //! const ZERO: i32 = 0;
269 //!
270 //! // Binding: `zero` matches regex /^_?[a-z0-9]/
271 //! assert_eq!(try_match!(42, zero), Ok(42));
272 //!
273 //! // Constant: `ZERO` matches regex /^_?[A-Z]/
274 //! assert_eq!(try_match!(42, ZERO), Err(42));
275 //!
276 //! // Binding: Only a binding can have a subpattern
277 //! assert_eq!(try_match!(42, THE_ANSWER @ _), Ok(42));
278 //! ```
279 //!
280 //! ```rust,compile_fail
281 //! # use try_match::try_match;
282 //! // ERROR: ambiguous identifier pattern
283 //! assert_eq!(try_match!(42, 你好), Ok(42));
284 //! ```
285 //!
286 //! [RFC 430]: https://rust-lang.github.io/rfcs/0430-finalizing-naming-conventions.html
287 #![no_std]
288 #![forbid(unsafe_code)]
289 #![cfg_attr(feature = "_doc_cfg", feature(doc_cfg))]
290
291 /// Try to match `$in` against a given pattern `$p`. Produces `Ok($out)` if
292 /// successful; `Err($in)` otherwise.
293 ///
294 /// ```rust,ignore
295 /// try_match!($( $in:expr )?, $p:pat $( if $guard:expr )? $( => $out:expr )? $( , )?)
296 /// ```
297 ///
298 /// `=> $out` can be left out, in which case it's implied based on the number of
299 /// bound variables in `$p`:
300 ///
301 /// - If there are no bound variables, it is implied to be `()`.
302 /// - If there is exactly one bound variable `var`, it is implied to be `var`.
303 /// - If there are multiple bound variables `var1, var2, ...`, it is implied to
304 /// be `AnonymousType { var1, var2 }`.
305 ///
306 /// `AnonymousType` implements `Clone`, `Copy`, and `Debug`.
307 ///
308 /// `$in` can be left out to produce a closure ([partial
309 /// application](crate#partial-application)).
310 ///
311 /// See [the crate-level documentation](crate#basic-usage) for examples.
312 #[macro_export]
313 macro_rules! try_match {
314 ($in:expr, $p:pat $(if $guard:expr)? => $out:expr $(,)?) => {
315 match $in {
316 $p $(if $guard)? => ::core::result::Result::Ok($out),
317 in_value => ::core::result::Result::Err(in_value),
318 }
319 };
320
321 ($in:expr, $p:pat $(if $guard:expr)? $(,)?) => {
322 $crate::implicit_try_match!(
323 ($in),
324 $p $(if $guard)?,
325 { ::core::result::Result::Ok }
326 { in_value => ::core::result::Result::Err(in_value) }
327 )
328 };
329
330 // Partial application
331 (, $($pattern_and_rest:tt)*) => {
332 |scrutinee| $crate::try_match!(scrutinee, $($pattern_and_rest)*)
333 }
334 }
335
336 /// Try to match `$in` against a given pattern `$p`. Produces `Some($out)` if
337 /// successful; `None` otherwise.
338 ///
339 /// ```rust,ignore
340 /// match_ok!($( $in:expr )?, $p:pat $( if $guard:expr )? $( => $out:expr )? $( , )?)
341 /// ```
342 ///
343 /// `=> $out` can be left out, in which case it's implied in the same way as
344 /// [`try_match!`].
345 ///
346 /// `$in` can be left out to produce a closure ([partial
347 /// application](crate#partial-application)).
348 ///
349 /// See [the crate-level documentation](crate#basic-usage) for examples.
350 #[macro_export]
351 macro_rules! match_ok {
352 ($in:expr, $p:pat $(if $guard:expr)? => $out:expr $(,)?) => {
353 match $in {
354 $p $(if $guard)? => ::core::option::Option::Some($out),
355 _ => ::core::option::Option::None,
356 }
357 };
358
359 ($in:expr, $p:pat $(if $guard:expr)? $(,)?) => {
360 $crate::implicit_try_match!(
361 ($in),
362 $p $(if $guard)?,
363 { ::core::option::Option::Some }
364 { _ => ::core::option::Option::None }
365 )
366 };
367
368 // Partial application
369 (, $($pattern_and_rest:tt)*) => {
370 |scrutinee| $crate::match_ok!(scrutinee, $($pattern_and_rest)*)
371 }
372 }
373
374 /// Try to match `$in` against a given pattern `$p`. Produces `$out` if
375 /// successful; [`Default::default()`] otherwise.
376 ///
377 /// ```rust,ignore
378 /// match_or_default!($( $in:expr )?, $p:pat $( if $guard:expr )? $( => $out:expr )? $( , )?)
379 /// ```
380 ///
381 /// `=> $out` can be left out, in which case it's implied in the same way as
382 /// [`try_match!`].
383 ///
384 /// `$in` can be left out to produce a closure ([partial
385 /// application](crate#partial-application)).
386 ///
387 /// See [the crate-level documentation](crate#basic-usage) for examples.
388 #[macro_export]
389 macro_rules! match_or_default {
390 ($in:expr, $p:pat $(if $guard:expr)? => $out:expr $(,)?) => {
391 match $in {
392 $p $(if $guard)? => $out,
393 _ => ::core::default::Default::default(),
394 }
395 };
396
397 ($in:expr, $p:pat $(if $guard:expr)? $(,)?) => {
398 $crate::implicit_try_match!(
399 ($in),
400 $p $(if $guard)?,
401 { }
402 { _ => ::core::default::Default::default() }
403 )
404 };
405
406 // Partial application
407 (, $($pattern_and_rest:tt)*) => {
408 |scrutinee| $crate::match_or_default!(scrutinee, $($pattern_and_rest)*)
409 }
410 }
411
412 /// Try to match `$in` against a given pattern `$p`. Panics on failure.
413 ///
414 /// ```rust,ignore
415 /// unwrap_match!(
416 /// $( $in:expr )?,
417 /// $p:pat $( if $guard:expr )? $( => $out:expr )?
418 /// // An optional panic message to replace the default one;
419 /// // removes the `$in: Debug` requirement
420 /// $( , $( $( $panic_args:tt )+ $( , )? )? )?
421 /// )
422 /// ```
423 ///
424 /// `=> $out` can be left out, in which case it's implied in the same way as
425 /// [`try_match!`].
426 ///
427 /// `$in` can be left out to produce a closure ([partial
428 /// application](crate#partial-application)).
429 ///
430 /// See [the crate-level documentation](crate#basic-usage) for examples.
431 #[macro_export]
432 macro_rules! unwrap_match {
433 ($($in:expr)?, $p:pat $(if $guard:expr)? $( => $out:expr)?) => {
434 // Add a trailing comma
435 $crate::unwrap_match!($($in)?, $p $(if $guard)? $( => $out)? ,)
436 };
437
438 ($in:expr, $p:pat $(if $guard:expr)? => $out:expr, $($panic_arg:tt)*) => {
439 match $in {
440 $p $(if $guard)? => $out,
441 ref in_val => $crate::unwrap_failed!(
442 { in_val }
443 { $p $(if $guard)? }
444 { $($panic_arg)* }
445 ),
446 }
447 };
448
449 ($in:expr, $p:pat $(if $guard:expr)?, $($panic_arg:tt)*) => {
450 $crate::implicit_try_match!(
451 ($in),
452 $p $(if $guard)?,
453 {}
454 { ref in_val => $crate::unwrap_failed!(
455 { in_val }
456 { $p $(if $guard)? }
457 { $($panic_arg)* }
458 ) }
459 )
460 };
461
462 // Partial application
463 (, $($pattern_and_rest:tt)* ) => {
464 |scrutinee| $crate::unwrap_match!(scrutinee, $($pattern_and_rest)*)
465 }
466 }
467
468 #[cfg(feature = "implicit_map")]
469 #[macro_export]
470 #[doc(hidden)]
471 macro_rules! implicit_try_match {
472 ($in:expr, $($p:tt)*) => {
473 $crate::implicit_try_match_inner!($in, $($p)*)
474 };
475 }
476
477 #[cfg(not(feature = "implicit_map"))]
478 #[macro_export]
479 #[doc(hidden)]
480 macro_rules! implicit_try_match {
481 ($($_:tt)*) => {
482 compile_error!(
483 "can't use the implicit mapping form of `try_match!` because \
484 the feature `implicit_map` is disabled"
485 )
486 };
487 }
488
489 #[macro_export]
490 #[doc(hidden)]
491 macro_rules! unwrap_failed {
492 (
493 { $in_val:tt } { $($pat:tt)* } { $(,)? }
494 ) => {
495 $crate::unwrap_failed($in_val, $crate::stringify!($($pat)*))
496 };
497 (
498 $in_val:tt $pat:tt { $($arg:tt)* }
499 ) => {
500 $crate::panic!($($arg)*)
501 };
502 }
503
504 // used by `unwrap_failed!`
505 #[doc(hidden)]
506 pub use core::{panic, stringify};
507
508 #[cold]
509 #[track_caller]
510 #[doc(hidden)]
511 pub fn unwrap_failed(in_val: &(impl core::fmt::Debug + ?Sized), pattern: &str) -> ! {
512 panic!(
513 "assertion failed: '{:?}' does not match '{}'",
514 in_val, pattern
515 );
516 }
517
518 /// Pattern: `$p:pat`
519 ///
520 /// The produced expression evaluates to `Ok(_)` using bound variables on a
521 /// successful match on the given value.
522 ///
523 /// - If there are no bound variables, it generates `()`.
524 /// - If there is exactly one bound variables `var`, it generates `var`.
525 /// - If there are multiple bound variables `var1, var2, ...`, it generates
526 /// `SomeType { var1, var2 }`.
527 ///
528 /// Otherwise, the expression evaluates to `Err($in)`.
529 #[cfg(feature = "implicit_map")]
530 #[doc(hidden)]
531 pub use try_match_inner::implicit_try_match_inner;