@@ -10,6 +10,7 @@ use crate::{
10
10
11
11
pub struct SourceCode {
12
12
source_code : syn:: Member ,
13
+ is_option : bool ,
13
14
}
14
15
15
16
impl SourceCode {
@@ -27,6 +28,19 @@ impl SourceCode {
27
28
for ( i, field) in fields. iter ( ) . enumerate ( ) {
28
29
for attr in & field. attrs {
29
30
if attr. path ( ) . is_ident ( "source_code" ) {
31
+ let is_option = if let syn:: Type :: Path ( syn:: TypePath {
32
+ path : syn:: Path { segments, .. } ,
33
+ ..
34
+ } ) = & field. ty
35
+ {
36
+ segments
37
+ . last ( )
38
+ . map ( |seg| seg. ident == "Option" )
39
+ . unwrap_or ( false )
40
+ } else {
41
+ false
42
+ } ;
43
+
30
44
let source_code = if let Some ( ident) = field. ident . clone ( ) {
31
45
syn:: Member :: Named ( ident)
32
46
} else {
@@ -35,7 +49,10 @@ impl SourceCode {
35
49
span : field. span ( ) ,
36
50
} )
37
51
} ;
38
- return Ok ( Some ( SourceCode { source_code } ) ) ;
52
+ return Ok ( Some ( SourceCode {
53
+ source_code,
54
+ is_option,
55
+ } ) ) ;
39
56
}
40
57
}
41
58
}
@@ -45,11 +62,21 @@ impl SourceCode {
45
62
pub ( crate ) fn gen_struct ( & self , fields : & syn:: Fields ) -> Option < TokenStream > {
46
63
let ( display_pat, _display_members) = display_pat_members ( fields) ;
47
64
let src = & self . source_code ;
65
+ let ret = if self . is_option {
66
+ quote ! {
67
+ self . #src. as_ref( ) . map( |s| s as _)
68
+ }
69
+ } else {
70
+ quote ! {
71
+ Some ( & self . #src)
72
+ }
73
+ } ;
74
+
48
75
Some ( quote ! {
49
76
#[ allow( unused_variables) ]
50
77
fn source_code( & self ) -> std:: option:: Option <& dyn miette:: SourceCode > {
51
78
let Self #display_pat = self ;
52
- Some ( & self . #src )
79
+ #ret
53
80
}
54
81
} )
55
82
}
@@ -68,10 +95,19 @@ impl SourceCode {
68
95
}
69
96
} ;
70
97
let variant_name = ident. clone ( ) ;
98
+ let ret = if source_code. is_option {
99
+ quote ! {
100
+ #field. as_ref( ) . map( |s| s as _)
101
+ }
102
+ } else {
103
+ quote ! {
104
+ std:: option:: Option :: Some ( #field)
105
+ }
106
+ } ;
71
107
match & fields {
72
108
syn:: Fields :: Unit => None ,
73
109
_ => Some ( quote ! {
74
- Self :: #variant_name #display_pat => std :: option :: Option :: Some ( #field ) ,
110
+ Self :: #variant_name #display_pat => #ret ,
75
111
} ) ,
76
112
}
77
113
} )
0 commit comments