parse_display/lib.rs
1//! This crate provides derive macro `Display` and `FromStr`.
2//! These macros use common helper attributes to specify the format.
3//!
4//! See [`#[derive(Display)]`](derive@Display) for details.
5//!
6//! ## Examples
7//!
8//! ```rust
9//! use parse_display::{Display, FromStr};
10//!
11//! #[derive(Display, FromStr, PartialEq, Debug)]
12//! #[display("{a}-{b}")]
13//! struct X {
14//! a: u32,
15//! b: u32,
16//! }
17//! assert_eq!(X { a:10, b:20 }.to_string(), "10-20");
18//! assert_eq!("10-20".parse(), Ok(X { a:10, b:20 }));
19//!
20//!
21//! #[derive(Display, FromStr, PartialEq, Debug)]
22//! #[display(style = "snake_case")]
23//! enum Y {
24//! VarA,
25//! VarB,
26//! }
27//! assert_eq!(Y::VarA.to_string(), "var_a");
28//! assert_eq!("var_a".parse(), Ok(Y::VarA));
29//! ```
30#![cfg_attr(not(feature = "std"), no_std)]
31#![cfg_attr(feature = "docs", feature(doc_cfg))]
32
33use core::convert::Infallible;
34use core::fmt::{Display, Formatter, Result};
35
36#[cfg(test)]
37mod tests;
38
39#[doc(hidden)]
40pub mod helpers;
41
42#[cfg(feature = "std")]
43mod helpers_std;
44
45#[cfg(feature = "std")]
46mod from_str_regex;
47
48#[cfg(feature = "std")]
49pub use from_str_regex::FromStrRegex;
50
51// #[include_doc("display.md", start)]
52/// Derive [`Display`].
53///
54/// ## Helper attributes
55///
56/// `#[derive(Display)]` and `#[derive(FromStr)]` use common helper attributes.
57///
58/// - `#[derive(Display)]` use `#[display]`.
59/// - `#[derive(FromStr)]` use both `#[display]` and `#[from_str]`, with `#[from_str]` having priority.
60///
61/// Helper attributes can be written in the following positions.
62///
63/// | attribute | `#[display]` | `#[from_str]` | struct | enum | variant | field |
64/// | ------------------------------------------------------------- | ------------ | ------------- | ------ | ---- | ------- | ----- |
65/// | [`#[display("...")]`](#display) | ✔ | | ✔ | ✔ | ✔ | ✔ |
66/// | [`#[display(style = "...")]`](#displaystyle--) | ✔ | | | ✔ | ✔ | |
67/// | [`#[display(with = ...)]`](#displaywith---from_strwith--) | ✔ | ✔ | | | | ✔ |
68/// | [`#[display(opt)]`](#displayopt) | | | | | | ✔ |
69/// | [`#[display(bound(...))]`](#displaybound-from_strbound) | ✔ | ✔ | ✔ | ✔ | ✔ | ✔ |
70/// | [`#[display(crate = ...)]`](#displaycrate--) | ✔ | | ✔ | ✔ | | |
71/// | [`#[display(dump)]`](#displaydump-from_strdump) | ✔ | ✔ | ✔ | ✔ | | |
72/// | [`#[from_str(regex = "...")]`](#from_strregex--) | | ✔ | ✔ | ✔ | ✔ | ✔ |
73/// | [`#[from_str(regex_infer)]`](#from_strregex_infer) | | ✔ | ✔ | ✔ | ✔ | ✔ |
74/// | [`#[from_str(new = ...)]`](#from_strnew--) | | ✔ | ✔ | | ✔ | |
75/// | [`#[from_str(ignore)]`](#from_strignore) | | ✔ | | | ✔ | |
76/// | [`#[from_str(default)]`](#from_strdefault) | | ✔ | ✔ | | | ✔ |
77///
78/// ## `#[display("...")]`
79///
80/// Specifies the format using a syntax similar to [`std::format!()`].
81///
82/// However, unlike `std::format!()`, `{}` has the following meaning.
83///
84/// | format | struct | enum | variant | field | description |
85/// | --------------------- | ------ | ---- | ------- | ----- | ----------------------------------------------------------------------------------- |
86/// | [`{a}`, `{b}`, `{1}`] | ✔ | ✔ | ✔ | ✔ | Use a field with the specified name. |
87/// | [`{}`] | | ✔ | ✔ | | Use a variant name of enum. |
88/// | [`{}`,`{:x}`, `{:?}`] | | | | ✔ | Use the field itself. |
89/// | [`{:x}`, `{:?}`] | ✔ | ✔ | | | Use format traits other than [`Display`] for `self`. (e.g. [`LowerHex`], [`Debug`]) |
90/// | [`{a.b.c}`] | ✔ | ✔ | ✔ | ✔ | Use a nested field. |
91///
92/// [`LowerHex`]: std::fmt::LowerHex
93/// [`{a}`, `{b}`, `{1}`]: #struct-format
94/// [`{}`]: #variant-name
95/// [`{}`,`{:x}`, `{:?}`]: #field-format
96/// [`{:x}`, `{:?}`]: #format-parameter
97/// [`{a.b.c}`]: #nested-field
98///
99/// ### Struct format
100///
101/// By writing `#[display("..")]`, you can specify the format used by `Display` and `FromStr`.
102///
103/// ```rust
104/// use parse_display::{Display, FromStr};
105///
106/// #[derive(Display, FromStr, PartialEq, Debug)]
107/// #[display("{a}-{b}")]
108/// struct MyStruct {
109/// a: u32,
110/// b: u32,
111/// }
112/// assert_eq!(MyStruct { a:10, b:20 }.to_string(), "10-20");
113/// assert_eq!("10-20".parse(), Ok(MyStruct { a:10, b:20 }));
114///
115/// #[derive(Display, FromStr, PartialEq, Debug)]
116/// #[display("{0}+{1}")]
117/// struct MyTuple(u32, u32);
118/// assert_eq!(MyTuple(10, 20).to_string(), "10+20");
119/// assert_eq!("10+20".parse(), Ok(MyTuple(10, 20)));
120/// ```
121///
122/// ### Newtype pattern
123///
124/// If the struct has only one field, the format can be omitted.
125/// In this case, the only field is used.
126///
127/// ```rust
128/// use parse_display::{Display, FromStr};
129///
130/// #[derive(Display, FromStr, PartialEq, Debug)]
131/// struct NewType(u32);
132/// assert_eq!(NewType(10).to_string(), "10");
133/// assert_eq!("10".parse(), Ok(NewType(10)));
134/// ```
135///
136/// ### Enum format
137///
138/// In enum, you can specify the format for each variant.
139///
140/// ```rust
141/// use parse_display::{Display, FromStr};
142///
143/// #[derive(Display, FromStr, PartialEq, Debug)]
144/// enum MyEnum {
145/// #[display("aaa")]
146/// VarA,
147/// #[display("bbb")]
148/// VarB,
149/// }
150/// assert_eq!(MyEnum::VarA.to_string(), "aaa");
151/// assert_eq!(MyEnum::VarB.to_string(), "bbb");
152/// assert_eq!("aaa".parse(), Ok(MyEnum::VarA));
153/// assert_eq!("bbb".parse(), Ok(MyEnum::VarB));
154/// ```
155///
156/// In enum format, `{}` means variant name.
157/// Variant name style (e.g. `snake_case`, `camelCase`, ...) can be specified by [`#[from_str(style = "...")]`](#displaystyle--).
158///
159/// ```rust
160/// use parse_display::{Display, FromStr};
161///
162/// #[derive(Display, FromStr, PartialEq, Debug)]
163/// enum MyEnum {
164/// #[display("aaa-{}")]
165/// VarA,
166/// #[display("bbb-{}")]
167/// VarB,
168/// }
169/// assert_eq!(MyEnum::VarA.to_string(), "aaa-VarA");
170/// assert_eq!(MyEnum::VarB.to_string(), "bbb-VarB");
171/// assert_eq!("aaa-VarA".parse(), Ok(MyEnum::VarA));
172/// assert_eq!("bbb-VarB".parse(), Ok(MyEnum::VarB));
173///
174/// #[derive(Display, FromStr, PartialEq, Debug)]
175/// #[display(style = "snake_case")]
176/// enum MyEnumSnake {
177/// #[display("{}")]
178/// VarA,
179/// }
180/// assert_eq!(MyEnumSnake::VarA.to_string(), "var_a");
181/// assert_eq!("var_a".parse(), Ok(MyEnumSnake::VarA));
182/// ```
183///
184/// By writing a format on enum instead of variant, you can specify the format common to multiple variants.
185///
186/// ```rust
187/// use parse_display::{Display, FromStr};
188///
189/// #[derive(Display, FromStr, PartialEq, Debug)]
190/// #[display("xxx-{}")]
191/// enum MyEnum {
192/// VarA,
193/// VarB,
194/// }
195/// assert_eq!(MyEnum::VarA.to_string(), "xxx-VarA");
196/// assert_eq!(MyEnum::VarB.to_string(), "xxx-VarB");
197/// assert_eq!("xxx-VarA".parse(), Ok(MyEnum::VarA));
198/// assert_eq!("xxx-VarB".parse(), Ok(MyEnum::VarB));
199/// ```
200///
201/// ### Unit variants
202///
203/// If all variants has no field, format can be omitted.
204/// In this case, variant name is used.
205///
206/// ```rust
207/// use parse_display::{Display, FromStr};
208///
209/// #[derive(Display, FromStr, PartialEq, Debug)]
210/// enum MyEnum {
211/// VarA,
212/// VarB,
213/// }
214/// assert_eq!(MyEnum::VarA.to_string(), "VarA");
215/// assert_eq!(MyEnum::VarB.to_string(), "VarB");
216/// assert_eq!("VarA".parse(), Ok(MyEnum::VarA));
217/// assert_eq!("VarB".parse(), Ok(MyEnum::VarB));
218/// ```
219///
220/// ### Field format
221///
222/// You can specify the format of the field.
223/// In field format, `{}` means the field itself.
224///
225/// ```rust
226/// use parse_display::{Display, FromStr};
227///
228/// #[derive(Display, FromStr, PartialEq, Debug)]
229/// #[display("{a}, {b}")]
230/// struct MyStruct {
231/// #[display("a is {}")]
232/// a: u32,
233/// #[display("b is {}")]
234/// b: u32,
235/// }
236/// assert_eq!(MyStruct { a:10, b:20 }.to_string(), "a is 10, b is 20");
237/// assert_eq!("a is 10, b is 20".parse(), Ok(MyStruct { a:10, b:20 }));
238///
239/// #[derive(Display, FromStr, PartialEq, Debug)]
240/// #[display("{0}, {1}")]
241/// struct MyTuple(#[display("first is {}")] u32, #[display("next is {}")] u32);
242/// assert_eq!(MyTuple(10, 20).to_string(), "first is 10, next is 20");
243/// assert_eq!("first is 10, next is 20".parse(), Ok(MyTuple(10, 20)));
244///
245/// #[derive(Display, FromStr, PartialEq, Debug)]
246/// enum MyEnum {
247/// #[display("this is A {0}")]
248/// VarA(#[display("___{}___")] u32),
249/// }
250/// assert_eq!(MyEnum::VarA(10).to_string(), "this is A ___10___");
251/// assert_eq!("this is A ___10___".parse(), Ok(MyEnum::VarA(10)));
252/// ```
253///
254/// ### Format parameter
255///
256/// Like `std::format!()`, format parameter can be specified.
257///
258/// ```rust
259/// use parse_display::{Display, FromStr};
260///
261/// #[derive(Display, PartialEq, Debug)]
262/// #[display("{a:>04}")]
263/// struct WithFormatParameter {
264/// a: u32,
265/// }
266/// assert_eq!(WithFormatParameter { a:5 }.to_string(), "0005");
267/// ```
268///
269/// When `{}` is used within `#[display("...")]` set for an enum, and if a format trait is added to `{}` such as `{:?}`, the meaning changes from "variant name" to "a string using a trait other than Display for self."
270///
271/// ```rust
272/// use parse_display::Display;
273///
274/// #[derive(Display, PartialEq, Debug)]
275/// #[display("{}")]
276/// enum X {
277/// A,
278/// }
279/// assert_eq!(X::A.to_string(), "A");
280///
281/// #[derive(Display, PartialEq)]
282/// #[display("{:?}")]
283/// enum Y {
284/// A,
285/// }
286/// impl std::fmt::Debug for Y {
287/// fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
288/// write!(f, "Debug Y")
289/// }
290/// }
291/// assert_eq!(Y::A.to_string(), "Debug Y");
292/// ```
293///
294/// ### Nested field
295///
296/// You can use nested field, e.g. `{x.a}` .
297///
298/// ```rust
299/// use parse_display::{Display, FromStr};
300///
301/// #[derive(PartialEq, Debug, Default)]
302/// struct X {
303/// a: u32,
304/// b: u32,
305/// }
306///
307/// #[derive(FromStr, Display, PartialEq, Debug)]
308/// #[display("{x.a}")]
309/// struct Y {
310/// #[from_str(default)]
311/// x: X,
312/// }
313/// assert_eq!(Y { x: X { a: 10, b: 20 } }.to_string(), "10");
314/// assert_eq!("10".parse(), Ok(Y { x: X { a: 10, b: 0 } }));
315/// ```
316///
317/// When using nested field, you need to use [`#[from_str(default)]`](#from_strdefault) to implement `FromStr`.
318///
319/// ## `#[display(style = "...")]`
320///
321/// By writing `#[display(style = "...")]`, you can specify the variant name style.
322/// The following styles are available.
323///
324/// - `none`
325/// - `lowercase`
326/// - `UPPERCASE`
327/// - `snake_case`
328/// - `SNAKE_CASE`
329/// - `camelCase`
330/// - `CamelCase`
331/// - `kebab-case`
332/// - `KEBAB-CASE`
333/// - `Title Case`
334/// - `Title case`
335/// - `title case`
336/// - `TITLE CASE`
337///
338/// ```rust
339/// use parse_display::{Display, FromStr};
340///
341/// #[derive(Display, FromStr, PartialEq, Debug)]
342/// #[display(style = "snake_case")]
343/// enum MyEnum {
344/// VarA,
345/// VarB,
346/// }
347/// assert_eq!(MyEnum::VarA.to_string(), "var_a");
348/// assert_eq!("var_a".parse(), Ok(MyEnum::VarA));
349///
350/// #[derive(Display, FromStr, PartialEq, Debug)]
351/// enum StyleExample {
352/// #[display(style = "none")]
353/// VarA1,
354/// #[display(style = "none")]
355/// varA2,
356/// #[display(style = "lowercase")]
357/// VarB,
358/// #[display(style = "UPPERCASE")]
359/// VarC,
360/// #[display(style = "snake_case")]
361/// VarD,
362/// #[display(style = "SNAKE_CASE")]
363/// VarE,
364/// #[display(style = "camelCase")]
365/// VarF,
366/// #[display(style = "CamelCase")]
367/// VarG1,
368/// #[display(style = "CamelCase")]
369/// varG2,
370/// #[display(style = "kebab-case")]
371/// VarH,
372/// #[display(style = "KEBAB-CASE")]
373/// VarI,
374/// #[display(style = "Title Case")]
375/// VarJ,
376/// #[display(style = "Title case")]
377/// VarK,
378/// #[display(style = "title case")]
379/// VarL,
380/// #[display(style = "TITLE CASE")]
381/// VarM,
382/// }
383/// assert_eq!(StyleExample::VarA1.to_string(), "VarA1");
384/// assert_eq!(StyleExample::varA2.to_string(), "varA2");
385/// assert_eq!(StyleExample::VarB.to_string(), "varb");
386/// assert_eq!(StyleExample::VarC.to_string(), "VARC");
387/// assert_eq!(StyleExample::VarD.to_string(), "var_d");
388/// assert_eq!(StyleExample::VarE.to_string(), "VAR_E");
389/// assert_eq!(StyleExample::VarF.to_string(), "varF");
390/// assert_eq!(StyleExample::VarG1.to_string(), "VarG1");
391/// assert_eq!(StyleExample::varG2.to_string(), "VarG2");
392/// assert_eq!(StyleExample::VarH.to_string(), "var-h");
393/// assert_eq!(StyleExample::VarI.to_string(), "VAR-I");
394/// assert_eq!(StyleExample::VarJ.to_string(), "Var J");
395/// assert_eq!(StyleExample::VarK.to_string(), "Var k");
396/// assert_eq!(StyleExample::VarL.to_string(), "var l");
397/// assert_eq!(StyleExample::VarM.to_string(), "VAR M");
398/// ```
399///
400/// ## `#[display(opt)]`
401///
402/// When applied to an `Option<T>` field, this attribute makes the field display an empty string for `None` and use `T`'s trait implementations directly (not `Option<T>`'s, but `T`'s `Display`, `FromStr`, etc.) for `Some(T)`.
403///
404/// ```rust
405/// use parse_display::{Display, FromStr};
406///
407/// #[derive(Display, FromStr, PartialEq, Debug)]
408/// struct X {
409/// #[display("a={}", opt)]
410/// a: Option<u32>,
411/// }
412/// assert_eq!(X { a: Some(10) }.to_string(), "a=10");
413/// assert_eq!(X { a: None::<u32> }.to_string(), "");
414/// ```
415///
416/// When the field is `None`, not just the placeholder but the entire format string for that field is omitted from the output. In the example above, when `a` is `None`, the output is `""` rather than `"a="`.
417///
418/// ## `#[display(with = "...")]`, `#[from_str(with = "...")]`
419///
420/// You can customize [`Display`] and [`FromStr`] processing for a field by specifying the values that implements [`DisplayFormat`] and [`FromStrFormat`].
421///
422/// ```rust
423/// use parse_display::{Display, DisplayFormat, FromStr, FromStrFormat};
424///
425/// #[derive(Display, FromStr, PartialEq, Debug)]
426/// pub struct X {
427/// #[display(with = Plus1)]
428/// a: i32,
429/// }
430///
431/// struct Plus1;
432///
433/// impl DisplayFormat<i32> for Plus1 {
434/// fn write(&self, f: &mut std::fmt::Formatter, value: &i32) -> std::fmt::Result {
435/// write!(f, "{}", value + 1)
436/// }
437/// }
438/// impl FromStrFormat<i32> for Plus1 {
439/// type Err = <i32 as std::str::FromStr>::Err;
440/// fn parse(&self, s: &str) -> std::result::Result<i32, Self::Err> {
441/// Ok(s.parse::<i32>()? - 1)
442/// }
443/// }
444///
445/// assert_eq!(X { a: 1 }.to_string(), "2");
446/// assert_eq!("2".parse(), Ok(X { a: 1 }));
447/// ```
448///
449/// The expression specified for `with = ...` must be lightweight because it is called each time when formatting and parsing.
450///
451/// ## `#[display(bound(...))]`, `#[from_str(bound(...))]`
452///
453/// By default, the type of field used in the format is added to the trait bound.
454///
455/// In Rust prior to 1.59, this behavior causes a compile error if you use fields of non public type in public struct.
456///
457/// ```rust
458/// #![deny(private_in_public)]
459/// use parse_display::Display;
460///
461/// // private type `Inner<T>` in public interface (error E0446)
462/// #[derive(Display)]
463/// pub struct Outer<T>(Inner<T>);
464///
465/// #[derive(Display)]
466/// struct Inner<T>(T);
467/// ```
468///
469/// By writing `#[display(bound(...))]`, you can override the default behavior.
470///
471/// ### Specify trait bound type
472///
473/// By specifying the type, you can specify the type that need to implement `Display` and `FromStr`.
474///
475/// ```rust
476/// use parse_display::{Display, FromStr};
477///
478/// #[derive(Display, FromStr, PartialEq, Debug)]
479/// #[display(bound(T))]
480/// pub struct Outer<T>(Inner<T>);
481///
482/// #[derive(Display, FromStr, PartialEq, Debug)]
483/// struct Inner<T>(T);
484///
485/// assert_eq!(Outer(Inner(10)).to_string(), "10");
486/// assert_eq!("10".parse(), Ok(Outer(Inner(10))));
487/// ```
488///
489/// ### Specify where predicate
490///
491/// You can also specify the where predicate.
492///
493/// ```rust
494/// use parse_display::Display;
495///
496/// #[derive(Display)]
497/// #[display(bound(T : std::fmt::Debug))]
498/// pub struct Outer<T>(Inner<T>);
499///
500/// #[derive(Display)]
501/// #[display("{0:?}")]
502/// struct Inner<T>(T);
503///
504/// assert_eq!(Outer(Inner(10)).to_string(), "10");
505/// ```
506///
507/// ### No trait bounds
508///
509/// You can also remove all trait bounds.
510///
511/// ```rust
512/// use parse_display::Display;
513///
514/// #[derive(Display)]
515/// #[display(bound())]
516/// pub struct Outer<T>(Inner<T>);
517///
518/// #[derive(Display)]
519/// #[display("ABC")]
520/// struct Inner<T>(T);
521///
522/// assert_eq!(Outer(Inner(10)).to_string(), "ABC");
523/// ```
524///
525/// ### Default trait bounds
526///
527/// `..` means default (automatically generated) trait bounds.
528///
529/// The following example specifies `T1` as a trait bound in addition to the default trait bound `T2`.
530///
531/// ```rust
532/// use parse_display::Display;
533///
534/// pub struct Inner<T>(T);
535///
536/// #[derive(Display)]
537/// #[display("{0.0}, {1}", bound(T1, ..))]
538/// pub struct Outer<T1, T2>(Inner<T1>, T2);
539///
540/// assert_eq!(Outer(Inner(10), 20).to_string(), "10, 20");
541/// ```
542///
543/// You can use a different trait bound for `Display` and `FromStr` by specifying both `#[display(bound(...))]` and `#[from_str(bound(...))]`.
544///
545/// ```rust
546/// use parse_display::*;
547/// use std::{fmt::Display, str::FromStr};
548///
549/// #[derive(Display, FromStr, PartialEq, Debug)]
550/// #[display(bound("T : Display"))]
551/// #[from_str(bound("T : FromStr"))]
552/// pub struct Outer<T>(Inner<T>);
553///
554/// #[derive(Display, FromStr, PartialEq, Debug)]
555/// struct Inner<T>(T);
556///
557/// assert_eq!(Outer(Inner(10)).to_string(), "10");
558/// assert_eq!("10".parse(), Ok(Outer(Inner(10))));
559/// ```
560///
561/// ## `#[display(crate = ...)]`
562///
563/// Specify a path to the `parse-display` crate instance.
564///
565/// Used when `::parse_display` is not an instance of `parse-display`, such as when a macro is re-exported or used from another macro.
566///
567/// ## `#[display(dump)]`, `#[from_str(dump)]`
568///
569/// Outputs the generated code as a compile error.
570///
571/// ## `#[from_str(regex = "...")]`
572///
573/// Specify the format of the string to be input with `FromStr`.
574/// `#[display("...")]` is ignored, when this attribute is specified.
575///
576/// ### Capture name
577///
578/// The capture name corresponds to the field name.
579///
580/// ```rust
581/// use parse_display::FromStr;
582///
583/// #[derive(FromStr, PartialEq, Debug)]
584/// #[from_str(regex = "(?<a>[0-9]+)__(?<b>[0-9]+)")]
585/// struct MyStruct {
586/// a: u8,
587/// b: u8,
588/// }
589///
590/// assert_eq!("10__20".parse(), Ok(MyStruct { a: 10, b: 20 }));
591/// ```
592///
593/// ### Field regex
594///
595/// Set `#[display("...")]` to struct and set `#[from_str(regex = "...")]` to field, regex is used in the position where field name is specified in `#[display("...")]`.
596///
597/// ```rust
598/// use parse_display::FromStr;
599///
600/// #[derive(FromStr, PartialEq, Debug)]
601/// #[display("{a}__{b}")]
602/// struct MyStruct {
603/// #[from_str(regex = "[0-9]+")]
604/// a: u8,
605///
606/// #[from_str(regex = "[0-9]+")]
607/// b: u8,
608/// }
609/// assert_eq!("10__20".parse(), Ok(MyStruct { a: 10, b: 20 }));
610/// ```
611///
612/// If `#[from_str(regex = "...")]` is not set to field ,
613/// it operates in the same way as when `#[from_str(regex = "(?s:.*?)")]` is set.
614///
615/// ```rust
616/// use parse_display::FromStr;
617///
618/// #[derive(FromStr, PartialEq, Debug)]
619/// #[display("{a}{b}")]
620/// struct MyStruct {
621/// a: String,
622/// b: String,
623/// }
624/// assert_eq!("abcdef".parse(), Ok(MyStruct { a:"".into(), b:"abcdef".into() }));
625/// ```
626///
627/// ### Field regex with capture
628///
629/// Using a named capture group with an empty name in the field's regex will convert only the string within that group to the field's value.
630///
631/// ```rust
632/// use parse_display::FromStr;
633///
634/// #[derive(FromStr, PartialEq, Debug)]
635/// struct MyStruct {
636/// #[from_str(regex = "a = (?<>[0-9]+)")]
637/// a: u8,
638/// }
639/// assert_eq!("a = 10".parse(), Ok(MyStruct { a: 10 }));
640/// ```
641///
642/// ### Field regex with display format
643///
644/// If both `#[display("...")]` and `#[from_str(regex = "...")]` are specified for a field and the regex does not contain named capture groups, the pattern within the `{}` part of the format specified by `#[display("...")]` will be determined by `#[from_str(regex = "...")]`.
645///
646/// ```rust
647/// use parse_display::FromStr;
648///
649/// #[derive(FromStr, PartialEq, Debug)]
650/// struct X {
651/// #[display("a = {}")]
652/// #[from_str(regex = "[0-9]+")]
653/// a: u8,
654/// }
655/// assert_eq!("a = 10".parse(), Ok(X { a: 10 }));
656/// ```
657///
658/// If the regex does not contain named capture groups, `#[display("...")]` is ignored.
659///
660/// ```rust
661/// use parse_display::FromStr;
662///
663/// #[derive(FromStr, PartialEq, Debug)]
664/// struct Y {
665/// #[display("a = {}")]
666/// #[from_str(regex = "a = (?<>[0-9]+)")]
667/// a: u8,
668/// }
669/// assert_eq!("a = 10".parse(), Ok(Y { a: 10 }));
670/// assert!("a = a = 10".parse::<Y>().is_err());
671/// ```
672///
673/// ### Variant name
674///
675/// In the regex specified for enum or variant, empty name capture means variant name.
676///
677/// ```rust
678/// use parse_display::FromStr;
679///
680/// #[derive(FromStr, PartialEq, Debug)]
681/// #[from_str(regex = "___(?<>)___")]
682/// enum MyEnum {
683/// VarA,
684///
685/// #[from_str(regex = "xxx(?<>)xxx")]
686/// VarB,
687/// }
688/// assert_eq!("___VarA___".parse(), Ok(MyEnum::VarA));
689/// assert_eq!("xxxVarBxxx".parse(), Ok(MyEnum::VarB));
690/// ```
691///
692/// ### Regex nested field
693///
694/// You can use nested field in regex.
695///
696/// ```rust
697/// use parse_display::FromStr;
698///
699/// #[derive(PartialEq, Debug, Default)]
700/// struct X {
701/// a: u32,
702/// }
703///
704/// #[derive(FromStr, PartialEq, Debug)]
705/// #[from_str(regex = "___(?<x.a>[0-9]+)")]
706/// struct Y {
707/// #[from_str(default)]
708/// x: X,
709/// }
710/// assert_eq!("___10".parse(), Ok(Y { x: X { a: 10 } }));
711/// ```
712///
713/// When using nested field, you need to use [`#[from_str(default)]`](#from_strdefault).
714///
715/// ### Regex priority
716///
717/// In addition to `#[from_str(regex = "...")]`,
718/// you can also specify `#[from_str(with = ...)]`, `#[display(with = ...)]`, or `#[from_str(regex_infer)]` to change the regular expression.
719/// If you specify multiple attributes in the same field, the regular expression that is applied is determined by the following priority.
720///
721/// - [`#[from_str(regex = "...")]`](#from_strregex--)
722/// - [`#[from_str(with = ...)]`, `#[display(with = ...)]`)](#displaywith---from_strwith--)
723/// - [`#[from_str(regex_infer)]`](#from_strregex_infer)
724///
725/// ## `#[from_str(regex_infer)]`
726///
727/// By default, fields are matched using the regular expression `(?s:.*?)`.
728///
729/// If you specify `#[from_str(regex_infer)]`,
730/// this behavior is changed and the pattern obtained from the field type's [`FromStrRegex`] is used for matching.
731///
732/// ```rust
733/// use parse_display::FromStr;
734///
735/// #[derive(FromStr, PartialEq, Debug)]
736/// #[display("{a}{b}")]
737/// struct X {
738/// a: u32,
739/// b: String,
740/// }
741///
742/// // `a` matches "" and `b` matches "1a", so it fails to convert to `Y`.
743/// assert!("1a".parse::<X>().is_err());
744///
745/// #[derive(FromStr, PartialEq, Debug)]
746/// #[display("{a}{b}")]
747/// struct Y {
748/// #[from_str(regex_infer)]
749/// a: u32,
750/// b: String,
751/// }
752///
753/// // `a` matches "1" and `b` matches "a", so it can be converted to `Y`.
754/// assert_eq!("1a".parse(), Ok(Y { a: 1, b: "a".into() }));
755/// ```
756///
757/// If `#[from_str(regex_infer)]` is specified for a type or variant rather than a field, this attribute is applied to all fields.
758///
759/// ## `#[from_str(new = ...)]`
760///
761/// If `#[from_str(new = ...)]` is specified, the value will be initialized with the specified expression instead of the constructor.
762///
763/// The expression must return a value that implement [`IntoResult`] (e.g. `Self`, `Option<Self>`, `Result<Self, E>`).
764///
765/// In the expression, you can use a variable with the same name as the field name.
766///
767/// ```rust
768/// use parse_display::FromStr;
769/// #[derive(FromStr, Debug, PartialEq)]
770/// #[from_str(new = Self::new(value))]
771/// struct MyNonZeroUSize {
772/// value: usize,
773/// }
774///
775/// impl MyNonZeroUSize {
776/// fn new(value: usize) -> Option<Self> {
777/// if value == 0 {
778/// None
779/// } else {
780/// Some(Self { value })
781/// }
782/// }
783/// }
784///
785/// assert_eq!("1".parse(), Ok(MyNonZeroUSize { value: 1 }));
786/// assert_eq!("0".parse::<MyNonZeroUSize>().is_err(), true);
787/// ```
788///
789/// In tuple struct, variables are named with a leading underscore and their index. (e.g. `_0`, `_1`).
790///
791/// ```rust
792/// use parse_display::FromStr;
793/// #[derive(FromStr, Debug, PartialEq)]
794/// #[from_str(new = Self::new(_0))]
795/// struct MyNonZeroUSize(usize);
796///
797/// impl MyNonZeroUSize {
798/// fn new(value: usize) -> Option<Self> {
799/// if value == 0 {
800/// None
801/// } else {
802/// Some(Self(value))
803/// }
804/// }
805/// }
806///
807/// assert_eq!("1".parse(), Ok(MyNonZeroUSize(1)));
808/// assert_eq!("0".parse::<MyNonZeroUSize>().is_err(), true);
809/// ```
810///
811/// ## `#[from_str(ignore)]`
812///
813/// Specifying this attribute for a variant will not generate `FromStr` implementation for that variant.
814///
815/// ```rust
816/// use parse_display::FromStr;
817///
818/// #[derive(Debug, Eq, PartialEq)]
819/// struct CanNotFromStr;
820///
821/// #[derive(FromStr, Debug, Eq, PartialEq)]
822/// #[allow(dead_code)]
823/// enum HasIgnore {
824/// #[from_str(ignore)]
825/// A(CanNotFromStr),
826/// #[display("{0}")]
827/// B(u32),
828/// }
829///
830/// assert_eq!("1".parse(), Ok(HasIgnore::B(1)));
831/// ```
832///
833/// ## `#[from_str(default)]`
834///
835/// If this attribute is specified, the default value is used for fields not included in the input.
836///
837/// If an attribute is specified for struct, the struct's default value is used.
838///
839/// ```rust
840/// use parse_display::FromStr;
841///
842/// #[derive(FromStr, PartialEq, Debug)]
843/// #[display("{b}")]
844/// #[from_str(default)]
845/// struct MyStruct {
846/// a: u32,
847/// b: u32,
848/// }
849///
850/// impl Default for MyStruct {
851/// fn default() -> Self {
852/// Self { a:99, b:99 }
853/// }
854/// }
855/// assert_eq!("10".parse(), Ok(MyStruct { a:99, b:10 }));
856/// ```
857///
858/// If an attribute is specified for field, the field type's default value is used.
859///
860/// ```rust
861/// use parse_display::FromStr;
862///
863/// #[derive(FromStr, PartialEq, Debug)]
864/// #[display("{b}")]
865/// struct MyStruct {
866/// #[from_str(default)]
867/// a: u32,
868/// b: u32,
869/// }
870///
871/// impl Default for MyStruct {
872/// fn default() -> Self {
873/// Self { a:99, b:99 }
874/// }
875/// }
876/// assert_eq!("10".parse(), Ok(MyStruct { a:0, b:10 }));
877/// ```
878///
879/// ## Deprecated features
880///
881/// The following deprecated features will be removed in a future version.
882///
883/// | feature | description |
884/// | ------- | ----------- |
885/// | [`#[from_str(default_fields(...))]`](https://docs.rs/parse-display/0.10.0/parse_display/derive.Display.html#from_strdefault_fields) | Sets default values for same-named fields across variants; use `#[from_str(default)]` instead. |
886// #[include_doc("display.md", end)]
887pub use parse_display_derive::Display;
888
889/// Derive [`FromStr`](std::str::FromStr) and [`FromStrRegex`].
890///
891/// `#[derive(Display)]` and `#[derive(FromStr)]` use common helper attributes.
892///
893/// See [`#[derive(Display)]`](derive@Display) for details.
894pub use parse_display_derive::FromStr;
895
896/// Error type used in the implementation of [`FromStr`] generated by `#[derive(FromStr)]`
897#[derive(Debug, Eq, PartialEq)]
898pub struct ParseError(&'static str);
899impl ParseError {
900 pub fn with_message(message: &'static str) -> Self {
901 Self(message)
902 }
903 pub fn new() -> Self {
904 Self::with_message("parse failed.")
905 }
906}
907impl Default for ParseError {
908 fn default() -> Self {
909 Self::new()
910 }
911}
912
913impl Display for ParseError {
914 fn fmt(&self, f: &mut Formatter) -> Result {
915 write!(f, "{}", self.0)
916 }
917}
918impl core::error::Error for ParseError {
919 fn description(&self) -> &str {
920 self.0
921 }
922}
923
924/// Trait implemented by the return value of the expression specified in [`#[from_str(new = ...)]`](macro@Display#from_strnew--).
925pub trait IntoResult<T> {
926 type Err;
927 fn into_result(self) -> core::result::Result<T, Self::Err>;
928}
929
930impl<T> IntoResult<T> for T {
931 type Err = Infallible;
932 fn into_result(self) -> core::result::Result<T, Self::Err> {
933 Ok(self)
934 }
935}
936
937impl<T> IntoResult<T> for Option<T> {
938 type Err = ParseError;
939 fn into_result(self) -> core::result::Result<T, Self::Err> {
940 self.ok_or_else(ParseError::new)
941 }
942}
943
944impl<T, E> IntoResult<T> for core::result::Result<T, E> {
945 type Err = E;
946 fn into_result(self) -> core::result::Result<T, E> {
947 self
948 }
949}
950
951/// Formatting method used in [`#[display(with = ...)]`](macro@Display#displaywith---from_strwith--).
952pub trait DisplayFormat<T: ?Sized> {
953 /// Formatting function used in place of [`Display::fmt`].
954 fn write(&self, f: &mut Formatter, value: &T) -> Result;
955}
956
957/// Regular expression that matches any string. Equivalent to `"(?s:.*?)"`.
958pub const ANY_REGEX: &str = "(?s:.*?)";
959
960/// Parsing method used in [`#[display(with = ...)]` and `#[from_str(with = ...)]`](macro@Display#displaywith---from_strwith--).
961pub trait FromStrFormat<T> {
962 type Err;
963
964 /// Parsing function used in place of [`FromStr::from_str`](core::str::FromStr::from_str).
965 fn parse(&self, s: &str) -> core::result::Result<T, Self::Err>;
966
967 /// Return a regular expression that the input string needs to match.
968 ///
969 /// By default, [`ANY_REGEX`] is returned, which matches any string.
970 ///
971 /// # Examples
972 ///
973 /// ```
974 /// use parse_display::{FromStr, FromStrFormat};
975 ///
976 /// struct Number;
977 /// impl FromStrFormat<String> for Number {
978 /// type Err = <String as std::str::FromStr>::Err;
979 /// fn parse(&self, s: &str) -> std::result::Result<String, Self::Err> {
980 /// s.parse()
981 /// }
982 /// fn regex_pattern(&self) -> String {
983 /// r"[0-9]+".into()
984 /// }
985 /// }
986 ///
987 /// #[derive(FromStr, PartialEq, Debug)]
988 /// #[display("{0}{1}")]
989 /// struct X(String, String);
990 ///
991 /// #[derive(FromStr, PartialEq, Debug)]
992 /// #[display("{0}{1}")]
993 /// struct Y(#[from_str(with = Number)] String, String);
994 ///
995 /// assert_eq!("123abc".parse(), Ok(X("".into(), "123abc".into())));
996 /// assert_eq!("123abc".parse(), Ok(Y("123".into(), "abc".into())));
997 /// ```
998 ///
999 /// If the field type includes type parameters, the regex must be the same regardless of the type parameters.
1000 ///
1001 /// If the regex differs, it will panic in debug mode and result in an incorrect parse in release mode.
1002 ///
1003 /// ```no_run
1004 /// use parse_display::{FromStr, FromStrFormat ,ParseError};
1005 /// use std::any::{type_name, Any};
1006 /// use std::str::FromStr;
1007 ///
1008 /// struct TypeNameFormat;
1009 /// impl<T: Default + Any> FromStrFormat<T> for TypeNameFormat {
1010 /// type Err = ParseError;
1011 /// fn parse(&self, _s: &str) -> core::result::Result<T, Self::Err> {
1012 /// Ok(Default::default())
1013 /// }
1014 /// fn regex_pattern(&self) -> String {
1015 /// type_name::<T>().to_string()
1016 /// }
1017 /// }
1018 ///
1019 /// #[derive(FromStr)]
1020 /// struct X<T: Default + std::any::Any>(#[from_str(with = TypeNameFormat)] T);
1021 /// let _ = X::<u32>::from_str("u32");
1022 /// let _ = X::<u16>::from_str("u16"); // panic on debug mode
1023 /// ```
1024 #[cfg(feature = "std")]
1025 #[allow(deprecated)]
1026 fn regex_pattern(&self) -> String {
1027 self.regex().unwrap_or(ANY_REGEX.into())
1028 }
1029
1030 #[cfg(feature = "std")]
1031 #[deprecated(note = r"use `regex_pattern` instead.
1032In `regex_pattern`, use `ANY_REGEX` instead of `None` for patterns that matches any string.")]
1033 fn regex(&self) -> Option<String> {
1034 None
1035 }
1036}