├── .gitignore ├── Cargo.toml ├── LICENSE ├── README.md ├── examples └── example.rs └── src └── lib.rs /.gitignore: -------------------------------------------------------------------------------- 1 | target 2 | Cargo.lock 3 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "error_def" 3 | version = "0.3.16" 4 | authors = ["Andrew Cann "] 5 | description = "A Rust syntax extension for generating error-handling boilerplate code." 6 | documentation = "https://github.com/canndrew/error_def" 7 | homepage = "https://github.com/canndrew/error_def" 8 | repository = "https://github.com/canndrew/error_def" 9 | readme = "README.md" 10 | keywords = ["error", "boilerplate", "syntax"] 11 | license = "GPL-2.0" 12 | 13 | [lib] 14 | name = "error_def" 15 | plugin = true 16 | 17 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 2, June 1991 3 | 4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc., 5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | Preamble 10 | 11 | The licenses for most software are designed to take away your 12 | freedom to share and change it. By contrast, the GNU General Public 13 | License is intended to guarantee your freedom to share and change free 14 | software--to make sure the software is free for all its users. This 15 | General Public License applies to most of the Free Software 16 | Foundation's software and to any other program whose authors commit to 17 | using it. (Some other Free Software Foundation software is covered by 18 | the GNU Lesser General Public License instead.) You can apply it to 19 | your programs, too. 20 | 21 | When we speak of free software, we are referring to freedom, not 22 | price. Our General Public Licenses are designed to make sure that you 23 | have the freedom to distribute copies of free software (and charge for 24 | this service if you wish), that you receive source code or can get it 25 | if you want it, that you can change the software or use pieces of it 26 | in new free programs; and that you know you can do these things. 27 | 28 | To protect your rights, we need to make restrictions that forbid 29 | anyone to deny you these rights or to ask you to surrender the rights. 30 | These restrictions translate to certain responsibilities for you if you 31 | distribute copies of the software, or if you modify it. 32 | 33 | For example, if you distribute copies of such a program, whether 34 | gratis or for a fee, you must give the recipients all the rights that 35 | you have. You must make sure that they, too, receive or can get the 36 | source code. And you must show them these terms so they know their 37 | rights. 38 | 39 | We protect your rights with two steps: (1) copyright the software, and 40 | (2) offer you this license which gives you legal permission to copy, 41 | distribute and/or modify the software. 42 | 43 | Also, for each author's protection and ours, we want to make certain 44 | that everyone understands that there is no warranty for this free 45 | software. If the software is modified by someone else and passed on, we 46 | want its recipients to know that what they have is not the original, so 47 | that any problems introduced by others will not reflect on the original 48 | authors' reputations. 49 | 50 | Finally, any free program is threatened constantly by software 51 | patents. We wish to avoid the danger that redistributors of a free 52 | program will individually obtain patent licenses, in effect making the 53 | program proprietary. To prevent this, we have made it clear that any 54 | patent must be licensed for everyone's free use or not licensed at all. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | GNU GENERAL PUBLIC LICENSE 60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 61 | 62 | 0. This License applies to any program or other work which contains 63 | a notice placed by the copyright holder saying it may be distributed 64 | under the terms of this General Public License. The "Program", below, 65 | refers to any such program or work, and a "work based on the Program" 66 | means either the Program or any derivative work under copyright law: 67 | that is to say, a work containing the Program or a portion of it, 68 | either verbatim or with modifications and/or translated into another 69 | language. (Hereinafter, translation is included without limitation in 70 | the term "modification".) Each licensee is addressed as "you". 71 | 72 | Activities other than copying, distribution and modification are not 73 | covered by this License; they are outside its scope. The act of 74 | running the Program is not restricted, and the output from the Program 75 | is covered only if its contents constitute a work based on the 76 | Program (independent of having been made by running the Program). 77 | Whether that is true depends on what the Program does. 78 | 79 | 1. You may copy and distribute verbatim copies of the Program's 80 | source code as you receive it, in any medium, provided that you 81 | conspicuously and appropriately publish on each copy an appropriate 82 | copyright notice and disclaimer of warranty; keep intact all the 83 | notices that refer to this License and to the absence of any warranty; 84 | and give any other recipients of the Program a copy of this License 85 | along with the Program. 86 | 87 | You may charge a fee for the physical act of transferring a copy, and 88 | you may at your option offer warranty protection in exchange for a fee. 89 | 90 | 2. You may modify your copy or copies of the Program or any portion 91 | of it, thus forming a work based on the Program, and copy and 92 | distribute such modifications or work under the terms of Section 1 93 | above, provided that you also meet all of these conditions: 94 | 95 | a) You must cause the modified files to carry prominent notices 96 | stating that you changed the files and the date of any change. 97 | 98 | b) You must cause any work that you distribute or publish, that in 99 | whole or in part contains or is derived from the Program or any 100 | part thereof, to be licensed as a whole at no charge to all third 101 | parties under the terms of this License. 102 | 103 | c) If the modified program normally reads commands interactively 104 | when run, you must cause it, when started running for such 105 | interactive use in the most ordinary way, to print or display an 106 | announcement including an appropriate copyright notice and a 107 | notice that there is no warranty (or else, saying that you provide 108 | a warranty) and that users may redistribute the program under 109 | these conditions, and telling the user how to view a copy of this 110 | License. (Exception: if the Program itself is interactive but 111 | does not normally print such an announcement, your work based on 112 | the Program is not required to print an announcement.) 113 | 114 | These requirements apply to the modified work as a whole. If 115 | identifiable sections of that work are not derived from the Program, 116 | and can be reasonably considered independent and separate works in 117 | themselves, then this License, and its terms, do not apply to those 118 | sections when you distribute them as separate works. But when you 119 | distribute the same sections as part of a whole which is a work based 120 | on the Program, the distribution of the whole must be on the terms of 121 | this License, whose permissions for other licensees extend to the 122 | entire whole, and thus to each and every part regardless of who wrote it. 123 | 124 | Thus, it is not the intent of this section to claim rights or contest 125 | your rights to work written entirely by you; rather, the intent is to 126 | exercise the right to control the distribution of derivative or 127 | collective works based on the Program. 128 | 129 | In addition, mere aggregation of another work not based on the Program 130 | with the Program (or with a work based on the Program) on a volume of 131 | a storage or distribution medium does not bring the other work under 132 | the scope of this License. 133 | 134 | 3. You may copy and distribute the Program (or a work based on it, 135 | under Section 2) in object code or executable form under the terms of 136 | Sections 1 and 2 above provided that you also do one of the following: 137 | 138 | a) Accompany it with the complete corresponding machine-readable 139 | source code, which must be distributed under the terms of Sections 140 | 1 and 2 above on a medium customarily used for software interchange; or, 141 | 142 | b) Accompany it with a written offer, valid for at least three 143 | years, to give any third party, for a charge no more than your 144 | cost of physically performing source distribution, a complete 145 | machine-readable copy of the corresponding source code, to be 146 | distributed under the terms of Sections 1 and 2 above on a medium 147 | customarily used for software interchange; or, 148 | 149 | c) Accompany it with the information you received as to the offer 150 | to distribute corresponding source code. (This alternative is 151 | allowed only for noncommercial distribution and only if you 152 | received the program in object code or executable form with such 153 | an offer, in accord with Subsection b above.) 154 | 155 | The source code for a work means the preferred form of the work for 156 | making modifications to it. For an executable work, complete source 157 | code means all the source code for all modules it contains, plus any 158 | associated interface definition files, plus the scripts used to 159 | control compilation and installation of the executable. However, as a 160 | special exception, the source code distributed need not include 161 | anything that is normally distributed (in either source or binary 162 | form) with the major components (compiler, kernel, and so on) of the 163 | operating system on which the executable runs, unless that component 164 | itself accompanies the executable. 165 | 166 | If distribution of executable or object code is made by offering 167 | access to copy from a designated place, then offering equivalent 168 | access to copy the source code from the same place counts as 169 | distribution of the source code, even though third parties are not 170 | compelled to copy the source along with the object code. 171 | 172 | 4. You may not copy, modify, sublicense, or distribute the Program 173 | except as expressly provided under this License. Any attempt 174 | otherwise to copy, modify, sublicense or distribute the Program is 175 | void, and will automatically terminate your rights under this License. 176 | However, parties who have received copies, or rights, from you under 177 | this License will not have their licenses terminated so long as such 178 | parties remain in full compliance. 179 | 180 | 5. You are not required to accept this License, since you have not 181 | signed it. However, nothing else grants you permission to modify or 182 | distribute the Program or its derivative works. These actions are 183 | prohibited by law if you do not accept this License. Therefore, by 184 | modifying or distributing the Program (or any work based on the 185 | Program), you indicate your acceptance of this License to do so, and 186 | all its terms and conditions for copying, distributing or modifying 187 | the Program or works based on it. 188 | 189 | 6. Each time you redistribute the Program (or any work based on the 190 | Program), the recipient automatically receives a license from the 191 | original licensor to copy, distribute or modify the Program subject to 192 | these terms and conditions. You may not impose any further 193 | restrictions on the recipients' exercise of the rights granted herein. 194 | You are not responsible for enforcing compliance by third parties to 195 | this License. 196 | 197 | 7. If, as a consequence of a court judgment or allegation of patent 198 | infringement or for any other reason (not limited to patent issues), 199 | conditions are imposed on you (whether by court order, agreement or 200 | otherwise) that contradict the conditions of this License, they do not 201 | excuse you from the conditions of this License. If you cannot 202 | distribute so as to satisfy simultaneously your obligations under this 203 | License and any other pertinent obligations, then as a consequence you 204 | may not distribute the Program at all. For example, if a patent 205 | license would not permit royalty-free redistribution of the Program by 206 | all those who receive copies directly or indirectly through you, then 207 | the only way you could satisfy both it and this License would be to 208 | refrain entirely from distribution of the Program. 209 | 210 | If any portion of this section is held invalid or unenforceable under 211 | any particular circumstance, the balance of the section is intended to 212 | apply and the section as a whole is intended to apply in other 213 | circumstances. 214 | 215 | It is not the purpose of this section to induce you to infringe any 216 | patents or other property right claims or to contest validity of any 217 | such claims; this section has the sole purpose of protecting the 218 | integrity of the free software distribution system, which is 219 | implemented by public license practices. Many people have made 220 | generous contributions to the wide range of software distributed 221 | through that system in reliance on consistent application of that 222 | system; it is up to the author/donor to decide if he or she is willing 223 | to distribute software through any other system and a licensee cannot 224 | impose that choice. 225 | 226 | This section is intended to make thoroughly clear what is believed to 227 | be a consequence of the rest of this License. 228 | 229 | 8. If the distribution and/or use of the Program is restricted in 230 | certain countries either by patents or by copyrighted interfaces, the 231 | original copyright holder who places the Program under this License 232 | may add an explicit geographical distribution limitation excluding 233 | those countries, so that distribution is permitted only in or among 234 | countries not thus excluded. In such case, this License incorporates 235 | the limitation as if written in the body of this License. 236 | 237 | 9. The Free Software Foundation may publish revised and/or new versions 238 | of the General Public License from time to time. Such new versions will 239 | be similar in spirit to the present version, but may differ in detail to 240 | address new problems or concerns. 241 | 242 | Each version is given a distinguishing version number. If the Program 243 | specifies a version number of this License which applies to it and "any 244 | later version", you have the option of following the terms and conditions 245 | either of that version or of any later version published by the Free 246 | Software Foundation. If the Program does not specify a version number of 247 | this License, you may choose any version ever published by the Free Software 248 | Foundation. 249 | 250 | 10. If you wish to incorporate parts of the Program into other free 251 | programs whose distribution conditions are different, write to the author 252 | to ask for permission. For software which is copyrighted by the Free 253 | Software Foundation, write to the Free Software Foundation; we sometimes 254 | make exceptions for this. Our decision will be guided by the two goals 255 | of preserving the free status of all derivatives of our free software and 256 | of promoting the sharing and reuse of software generally. 257 | 258 | NO WARRANTY 259 | 260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY 261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN 262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES 263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED 264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS 266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE 267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, 268 | REPAIR OR CORRECTION. 269 | 270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR 272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, 273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING 274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED 275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY 276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER 277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE 278 | POSSIBILITY OF SUCH DAMAGES. 279 | 280 | END OF TERMS AND CONDITIONS 281 | 282 | How to Apply These Terms to Your New Programs 283 | 284 | If you develop a new program, and you want it to be of the greatest 285 | possible use to the public, the best way to achieve this is to make it 286 | free software which everyone can redistribute and change under these terms. 287 | 288 | To do so, attach the following notices to the program. It is safest 289 | to attach them to the start of each source file to most effectively 290 | convey the exclusion of warranty; and each file should have at least 291 | the "copyright" line and a pointer to where the full notice is found. 292 | 293 | 294 | Copyright (C) 295 | 296 | This program is free software; you can redistribute it and/or modify 297 | it under the terms of the GNU General Public License as published by 298 | the Free Software Foundation; either version 2 of the License, or 299 | (at your option) any later version. 300 | 301 | This program is distributed in the hope that it will be useful, 302 | but WITHOUT ANY WARRANTY; without even the implied warranty of 303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 304 | GNU General Public License for more details. 305 | 306 | You should have received a copy of the GNU General Public License along 307 | with this program; if not, write to the Free Software Foundation, Inc., 308 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 309 | 310 | Also add information on how to contact you by electronic and paper mail. 311 | 312 | If the program is interactive, make it output a short notice like this 313 | when it starts in an interactive mode: 314 | 315 | Gnomovision version 69, Copyright (C) year name of author 316 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 317 | This is free software, and you are welcome to redistribute it 318 | under certain conditions; type `show c' for details. 319 | 320 | The hypothetical commands `show w' and `show c' should show the appropriate 321 | parts of the General Public License. Of course, the commands you use may 322 | be called something other than `show w' and `show c'; they could even be 323 | mouse-clicks or menu items--whatever suits your program. 324 | 325 | You should also get your employer (if you work as a programmer) or your 326 | school, if any, to sign a "copyright disclaimer" for the program, if 327 | necessary. Here is a sample; alter the names: 328 | 329 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program 330 | `Gnomovision' (which makes passes at compilers) written by James Hacker. 331 | 332 | , 1 April 1989 333 | Ty Coon, President of Vice 334 | 335 | This General Public License does not permit incorporating your program into 336 | proprietary programs. If your program is a subroutine library, you may 337 | consider it more useful to permit linking proprietary applications with the 338 | library. If this is what you want to do, use the GNU Lesser General 339 | Public License instead of this License. 340 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | ## error_def: A Rust syntax extension for generating error-handling boilerplate code. 3 | 4 | **Note: This library is deprecated. It's too much effort to keep it up-to-date 5 | with the upstream changes to libsyntax and there are better alternatives out 6 | there now which also run on stable. Personally, I've switched to using 7 | `failure`.** 8 | 9 | **Quick Example:** The following code: 10 | 11 | ```rust 12 | error_def! ExampleError { 13 | AVariant 14 | => "Unit-like variant", 15 | AVariantWithALongDescription 16 | => "Unit-like variant" ("A more verbose description"), 17 | AVariantWithArgs { flim: u32, flam: u32 } 18 | => "Variant with args" ("This is a format string. flim is {}. flam is {}.", flim, flam), 19 | AVariantWithACause { blah: bool, #[from] cause: io::Error } 20 | => "Variant with a cause" ("self.cause() would return Some({})", cause) 21 | AVariantWithJustACause { #[from] blah: io::Error } 22 | => "This variant can be made `From` an `io::Error`" 23 | } 24 | 25 | ``` 26 | 27 | Expands (roughly) to: 28 | 29 | ```rust 30 | pub enum ExampleError { 31 | /// Unit-like variant 32 | AVariant, 33 | 34 | /// Unit-like variant 35 | AVariantWithALongDescription, 36 | 37 | /// Variant with args 38 | AVariantWithArgs { 39 | flim: u32, 40 | flam: u32, 41 | }, 42 | 43 | /// Variant with a cause 44 | AVariantWithACause { 45 | blah: bool, 46 | cause: io::Error, 47 | }, 48 | 49 | /// This variant can be made `From` an `io::Error` 50 | AVariantWithJustACause { 51 | blah: io::Error, 52 | }, 53 | } 54 | 55 | impl fmt::Debug for ExampleError { 56 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result<(), fmt::Error> { 57 | match self { 58 | &ExampleError::AVariant 59 | => write!(f, "AVariant /* {} */", self), 60 | &ExampleError::AVariantWithALongDescription 61 | => write!(f, "AVariantWithALongDescription /* {} */", self), 62 | &ExampleError::AVariantWithArgs { ref flim, ref flam } 63 | => write!(f, "AVariantWithArgs {{ flim: {:?}, flam: {:?} }} /* {} */", flim, flim, self), 64 | &ExampleError::AVariantWithACause { ref blah, ref cause } 65 | => write!(f, "AVariantWithACause {{ blah: {:?}, cause: {:?} }} /* {} */", blah, cause, self), 66 | &ExampleError::AVariantWithJustACause { ref blah } 67 | => write!(f, "AVariantWithJustACause {{ blah: {:?} }} /* {} */", blah, self), 68 | } 69 | } 70 | } 71 | 72 | impl fmt::Display for ExampleError { 73 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result<(), fmt::Error> { 74 | match self { 75 | &ExampleError::AVariant => { 76 | try!(write!(f, "Unit-like variant.")); 77 | Ok(()) 78 | }, 79 | &ExampleError::AVariantWithALongDescription => { 80 | try!(write!(f, "Unit-like variant")); 81 | try!(write!(f, "A more verbose description")); 82 | Ok(()) 83 | }, 84 | &ExampleError::AVariantWithArgs { ref flim, ref flam } => { 85 | try!(write!(f, "Variant with args")); 86 | try!(write!(f, "This is a format string. flim is {}. flam is {}.", flim, flam)); 87 | Ok(()) 88 | }, 89 | &ExampleError::AVariantWithACause { ref cause, .. } => { 90 | try!(write!(f, "Variant with a cause")); 91 | try!(write!(f, "self.cause() would return Some({})", cause)); 92 | Ok(()) 93 | }, 94 | &ExampleError::AVariantWithJustACause { .. } => { 95 | try!(write!(f, "This variant can be made `From` an `io::Error`")); 96 | Ok(()) 97 | }, 98 | } 99 | } 100 | } 101 | 102 | impl Error for ExampleError { 103 | fn description(&self) -> &str { 104 | match self { 105 | &ExampleError::AVariant => "Unit-like variant", 106 | &ExampleError::AVariantWithALongDescription { .. } => "Unit-like variant", 107 | &ExampleError::AVariantWithArgs { .. } => "Variant with args", 108 | &ExampleError::AVariantWithACause { .. } => "Variant with a cause", 109 | &ExampleError::AVariantWithJustACause { .. } => "This variant can be made `From` an `io::Error`", 110 | } 111 | } 112 | 113 | fn cause(&self) -> Option<&Error> { 114 | match self { 115 | &ExampleError::AVariant => None, 116 | &ExampleError::AVariantWithALongDescription { .. } => None, 117 | &ExampleError::AVariantWithArgs { .. } => None, 118 | &ExampleError::AVariantWithACause { ref cause, .. } => Some(cause as &Error), 119 | &ExampleError::AVariantWithJustACause { ref blah, .. } => Some(blah as &Error), 120 | } 121 | } 122 | } 123 | 124 | impl From for ExampleError { 125 | fn from(e: io::Error) -> ExampleError { 126 | ExampleError::AVariantWithJustACause { blah: e } 127 | } 128 | } 129 | 130 | ``` 131 | 132 | **Explanation:** `error_def` defines an `enum` where each variant is paired 133 | with a description of the variant. 134 | 135 | ```rust 136 | error_def! SomeError { 137 | AVariant => "A description", 138 | AnotherVariant => "Another description", 139 | } 140 | ``` 141 | 142 | This description is added as a doc-comment to the variant and is returned by 143 | calls to `Error::description`. 144 | 145 | ```rust 146 | assert!(SomeError::AVariant.description() == "A description") 147 | ``` 148 | 149 | Variants can be struct-like. 150 | 151 | ```rust 152 | error_def! SomeError { 153 | AVariant { an_i32: i32 } => "I'm a variant", 154 | } 155 | ``` 156 | 157 | Variants can also have an optional long-description which consists of a format 158 | string and a sequence of arguments. The long description is placed in 159 | parenthesis after the short-description. If the variant is a struct, the 160 | arguments to the format string can refer to it's members. 161 | 162 | ```rust 163 | error_def! SomeError { 164 | Io { cause: io::Error } 165 | => "I/O error occured!" ("Error: {}", cause), 166 | } 167 | ``` 168 | 169 | `error_def!` uses the short and long descriptions to provide `impl`s of 170 | `fmt::Display` and `fmt::Debug`. In the above case, `SomeError::Io` would be 171 | formatted as 172 | 173 | `I/O error occured. Error: <`*`insert fmt::Display(cause) here`*`>` 174 | 175 | For `fmt::Display` and 176 | 177 | `SomeError::Io { cause: <`*`insert fmt::Debug(cause) here`*`> } /* I/O error occured. Error: <`*`insert fmt::Display(cause) here`*`> */` 178 | 179 | For `fmt::Debug`. 180 | 181 | Members of a struct-variant can be marked with an optional `#[from]` pseudo-attribute. 182 | 183 | ```rust 184 | error_def! SomeError { 185 | Io { 186 | foo: u32, 187 | #[from] cause: io::Error, 188 | } => "Io error" 189 | } 190 | ``` 191 | 192 | This causes the member to be returned by calls to `Error::cause`. In the above 193 | example, calling `Error::cause` on a `SomeError::Io` will return an 194 | `Option<&Error>` where the `&Error` points to an `io::Error`. 195 | 196 | If a struct variant has only one member and it is marked `#[from]` then `From` 197 | will be implemented to cast the type of that member to the type of the error. 198 | 199 | For example, if we define an error like this: 200 | 201 | ```rust 202 | error_def! SomeError { 203 | Io { #[from] cause: io::Error } => "I/O error", 204 | } 205 | ``` 206 | 207 | Then `error_def!` will define an `impl`: 208 | 209 | ```rust 210 | impl std::convert::From for SomeError { 211 | fn from(e: io::Error) -> SomeError { 212 | SomeError::Io { 213 | cause: e, 214 | } 215 | } 216 | } 217 | ``` 218 | 219 | -------------------------------------------------------------------------------- /examples/example.rs: -------------------------------------------------------------------------------- 1 | #![feature(plugin)] 2 | #![plugin(error_def)] 3 | #![allow(dead_code)] 4 | 5 | use std::io; 6 | 7 | error_def! ExampleError { 8 | AVariant => "Unit-like variant", 9 | AVariantWithALongDescription => "Unit-like variant" ("A more verbose description"), 10 | AVariantWithArgs { 11 | flim: u32, 12 | flam: u32, 13 | } => "Variant with args" ("This is a format string. flim is {}. flam is {}.", flim, flam), 14 | AVariantWithACause { 15 | blah: bool, 16 | #[from] cause: io::Error, 17 | } => "Variant with a cause" ("self.cause() would return Some({})", cause), 18 | AVariantWithJustACause { 19 | #[from] blah: io::Error, 20 | } => "This variant can be made `From` an `io::Error`" 21 | } 22 | 23 | /* Expands (roughly) to 24 | 25 | enum ExampleError { 26 | AVariant, 27 | AVariantWithALongDescription, 28 | AVariantWithArgs { 29 | flim: u32, 30 | flam: u32, 31 | }, 32 | AVariantWithACause { 33 | blah: bool, 34 | cause: io::Error, 35 | }, 36 | AVariantWithJustACause { 37 | blah: io::Error, 38 | }, 39 | } 40 | 41 | impl fmt::Debug for ExampleError { 42 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result<(), fmt::Error> { 43 | match self { 44 | &ExampleError::AVariant => write!(f, "AVariant /* {} */", self), 45 | &ExampleError::AVariantWithALongDescription => write!(f, "AVariantWithALongDescription /* {} */", self), 46 | &ExampleError::AVariantWithArgs { ref flim, ref flam } => write!(f, "AVariantWithArgs {{ flim: {:?}, flam: {:?} }} /* {} */", flim, flim, self), 47 | &ExampleError::AVariantWithACause { ref blah, ref cause } => write!(f, "AVariantWithACause {{ blah: {:?}, cause: {:?} }} /* {} */", blah, cause, self), 48 | &ExampleError::AVariantWithJustACause { ref blah } => write!(f, "AVariantWithJustACause {{ blah: {:?} }} /* {} */", blah, self), 49 | } 50 | } 51 | } 52 | 53 | impl fmt::Display for ExampleError { 54 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result<(), fmt::Error> { 55 | match self { 56 | &ExampleError::AVariant => { 57 | try!(write!(f, "Unit-like variant.")); 58 | Ok(()) 59 | }, 60 | &ExampleError::AVariantWithALongDescription => { 61 | try!(write!(f, "Unit-like variant")); 62 | try!(write!(f, "A more verbose description")); 63 | Ok(()) 64 | }, 65 | &ExampleError::AVariantWithArgs { ref flim, ref flam } => { 66 | try!(write!(f, "Variant with args")); 67 | try!(write!(f, "This is a format string. flim is {}. flam is {}.", flim, flam)); 68 | Ok(()) 69 | }, 70 | &ExampleError::AVariantWithACause { ref cause, .. } => { 71 | try!(write!(f, "Variant with a cause")); 72 | try!(write!(f, "self.cause() would return Some({})", cause)); 73 | Ok(()) 74 | }, 75 | &ExampleError::AVariantWithJustACause { .. } => { 76 | try!(write!(f, "This variant can be made `From` an `io::Error`")); 77 | Ok(()) 78 | }, 79 | } 80 | } 81 | } 82 | 83 | impl Error for ExampleError { 84 | fn description(&self) -> &str { 85 | match self { 86 | &ExampleError::AVariant => "Unit-like variant", 87 | &ExampleError::AVariantWithALongDescription { .. } => "Unit-like variant", 88 | &ExampleError::AVariantWithArgs { .. } => "Variant with args", 89 | &ExampleError::AVariantWithACause { .. } => "Variant with a cause", 90 | &ExampleError::AVariantWithJustACause { .. } => "This variant can be made `From` an `io::Error`", 91 | } 92 | } 93 | 94 | fn cause(&self) -> Option<&Error> { 95 | match self { 96 | &ExampleError::AVariant => None, 97 | &ExampleError::AVariantWithALongDescription { .. } => None, 98 | &ExampleError::AVariantWithArgs { .. } => None, 99 | &ExampleError::AVariantWithACause { ref cause, .. } => Some(cause as &Error), 100 | &ExampleError::AVariantWithJustACause { ref blah, .. } => Some(blah as &Error), 101 | } 102 | } 103 | } 104 | 105 | impl From for ExampleError { 106 | fn from(e: io::Error) -> ExampleError { 107 | ExampleError::AVariantWithJustACause { blah: e } 108 | } 109 | } 110 | 111 | */ 112 | 113 | #[test] 114 | fn test() { 115 | use std::error::Error; 116 | 117 | let e = ExampleError::AVariant; 118 | assert_eq!(&format!("{:?}", e), "ExampleError::AVariant /* Unit-like variant */"); 119 | assert_eq!(&format!("{}", e), "Unit-like variant"); 120 | assert_eq!(e.description(), "Unit-like variant"); 121 | assert!(e.cause().is_none()); 122 | 123 | let e = ExampleError::AVariantWithALongDescription; 124 | assert_eq!(&format!("{:?}", e), "ExampleError::AVariantWithALongDescription /* Unit-like variant. A more verbose description */"); 125 | assert_eq!(&format!("{}", e), "Unit-like variant. A more verbose description"); 126 | assert_eq!(e.description(), "Unit-like variant"); 127 | assert!(e.cause().is_none()); 128 | 129 | let e = ExampleError::AVariantWithArgs { flim: 123u32, flam: 456u32 }; 130 | assert_eq!(&format!("{:?}", e), "ExampleError::AVariantWithArgs { flim: 123, flam: 456 } /* Variant with args. This is a format string. flim is 123. flam is 456. */"); 131 | assert_eq!(&format!("{}", e), "Variant with args. This is a format string. flim is 123. flam is 456."); 132 | assert_eq!(e.description(), "Variant with args"); 133 | assert!(e.cause().is_none()); 134 | 135 | let e = ExampleError::AVariantWithACause { blah: true, cause: io::Error::new(io::ErrorKind::PermissionDenied, "Yo you can't do that!") }; 136 | assert_eq!(&format!("{:?}", e), "ExampleError::AVariantWithACause { blah: true, cause: Error { repr: Custom(Custom { kind: PermissionDenied, error: StringError(\"Yo you can\\\'t do that!\") }) } } /* Variant with a cause. self.cause() would return Some(Yo you can't do that!) */"); 137 | assert_eq!(&format!("{}", e), "Variant with a cause. self.cause() would return Some(Yo you can't do that!)"); 138 | assert_eq!(e.description(), "Variant with a cause"); 139 | assert_eq!(e.cause().unwrap().description(), "Yo you can't do that!"); 140 | 141 | let e = ExampleError::from(io::Error::new(io::ErrorKind::PermissionDenied, "You still can't do that!")); 142 | match e { 143 | ExampleError::AVariantWithJustACause { .. } => (), 144 | _ => panic!("wtf?"), 145 | }; 146 | assert_eq!(&format!("{:?}", e), "ExampleError::AVariantWithJustACause { blah: Error { repr: Custom(Custom { kind: PermissionDenied, error: StringError(\"You still can\\\'t do that!\") }) } } /* This variant can be made `From` an `io::Error` */"); 147 | assert_eq!(&format!("{}", e), "This variant can be made `From` an `io::Error`"); 148 | assert_eq!(e.description(), "This variant can be made `From` an `io::Error`"); 149 | assert_eq!(e.cause().unwrap().description(), "You still can't do that!"); 150 | } 151 | 152 | fn main() { 153 | } 154 | 155 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | #![feature(quote)] 2 | #![feature(plugin_registrar)] 3 | #![feature(rustc_private)] 4 | #![allow(unused_imports)] 5 | 6 | extern crate syntax; 7 | extern crate rustc_plugin; 8 | 9 | use syntax::codemap::{Span, DUMMY_SP, dummy_spanned}; 10 | use syntax::tokenstream::TokenTree; 11 | use syntax::ext::base::{ExtCtxt, MacResult, DummyResult, SyntaxExtension, MacEager}; 12 | use syntax::parse::token::{Token, DelimToken}; 13 | use syntax::symbol::Symbol; 14 | use syntax::parse; 15 | use syntax::util::small_vector::SmallVector; 16 | use syntax::ast::{self, Variant_, Visibility, VariantData, Variant, LitKind, StructField, Name, 17 | Expr, DUMMY_NODE_ID}; 18 | use syntax::ptr::P; 19 | use syntax::attr::{mk_sugared_doc_attr, mk_attr_id}; 20 | use syntax::ext::quote::rt::ToTokens; 21 | 22 | use rustc_plugin::Registry; 23 | 24 | struct LongDescription { 25 | format_str: Name, 26 | format_args: Vec> 27 | } 28 | 29 | struct VariantDef { 30 | variant: P, 31 | short_description: Name, 32 | from_idx: Option, 33 | long_description: Option, 34 | } 35 | 36 | fn expand_error_def<'c>( 37 | cx: &'c mut ExtCtxt, 38 | sp: Span, 39 | type_name: ast::Ident, 40 | tokens: Vec 41 | ) -> Box { 42 | let mut parser = parse::stream_to_parser(cx.parse_sess(), tokens.into_iter().collect()); 43 | 44 | let mut items: Vec> = Vec::new(); 45 | let mut variants: Vec = Vec::new(); 46 | 47 | // Parse the token tree and populate our list of variants. 48 | loop { 49 | let variant_name = if parser.check(&Token::Eof) { 50 | break 51 | } else { 52 | match parser.parse_ident() { 53 | Ok(ident) => ident, 54 | Err(mut e) => { 55 | e.emit(); 56 | return DummyResult::any(sp); 57 | }, 58 | } 59 | }; 60 | 61 | let (from_idx, members): (Option, Option>) = if parser.eat(&Token::FatArrow) { 62 | // It's a unit-like variant. (ie. not a struct variant) 63 | (None, None) 64 | } else if parser.eat(&Token::OpenDelim(DelimToken::Brace)) { 65 | // It's a struct variant 66 | let mut members: Vec = Vec::new(); 67 | let mut from_memb_idx: Option = None; 68 | 69 | // Parse the list of struct members. 70 | loop { 71 | 72 | // Parse the list of attributes on this struct member 73 | let mut attrs = match parser.parse_outer_attributes() { 74 | Ok(attrs) => attrs, 75 | Err(mut e) => { 76 | e.emit(); 77 | return DummyResult::any(sp); 78 | }, 79 | }; 80 | 81 | // Find whether this member is marked #[from]. And if it is, find the index of the 82 | // #[from] attribute so we can remove it. 83 | 84 | let mut from_attr_idx: Option<(usize, Span)> = None; 85 | for (i, attr) in attrs.iter().enumerate() { 86 | if attr.path == "from" { 87 | match from_attr_idx { 88 | Some(_) => { 89 | cx.span_err(attr.span, "Field marked #[from] twice"); 90 | return DummyResult::any(sp); 91 | }, 92 | None => from_attr_idx = Some((i, attr.span)), 93 | }; 94 | }; 95 | }; 96 | match from_attr_idx { 97 | // This member is marked #[from]. Record this. 98 | Some((i, attr_span)) => { 99 | attrs.swap_remove(i); 100 | match from_memb_idx { 101 | Some(_) => { 102 | cx.span_err(attr_span, "Multiple fields marked #[from]"); 103 | return DummyResult::any(sp); 104 | }, 105 | None => from_memb_idx = Some(members.len()), 106 | }; 107 | }, 108 | None => (), 109 | }; 110 | 111 | // Parse the name and type of the member. 112 | let sf = match parser.parse_single_struct_field(DUMMY_SP, 113 | Visibility::Inherited, 114 | attrs) { 115 | Ok(sf) => sf, 116 | Err(mut e) => { 117 | e.emit(); 118 | return DummyResult::any(sp); 119 | }, 120 | }; 121 | if sf.ident.is_none() { 122 | cx.span_err(sp, "Expected a named field"); 123 | return DummyResult::any(sp); 124 | } 125 | members.push(sf); 126 | if parser.token == Token::CloseDelim(DelimToken::Brace) { 127 | let _ = parser.bump(); 128 | break; 129 | } 130 | 131 | }; 132 | 133 | if let Err(mut e) = parser.expect(&Token::FatArrow) { 134 | e.emit(); 135 | return DummyResult::any(sp); 136 | }; 137 | 138 | (from_memb_idx, Some(members)) 139 | } else { 140 | match parser.expect_one_of(&[Token::FatArrow, Token::OpenDelim(DelimToken::Brace)], &[]) { 141 | Ok(..) => unreachable!(), 142 | Err(mut e) => { 143 | e.emit(); 144 | return DummyResult::any(sp); 145 | }, 146 | } 147 | }; 148 | 149 | // Parse the short description. 150 | let short_desc = match parser.parse_str() { 151 | Ok((sd, _)) => sd, 152 | Err(mut e) => { 153 | e.emit(); 154 | return DummyResult::any(sp); 155 | }, 156 | }; 157 | 158 | // Parse the long description if it exists. 159 | let long_desc = if parser.token == Token::OpenDelim(DelimToken::Paren) { 160 | let _ = parser.bump(); 161 | 162 | let format_str = match parser.parse_str() { 163 | Ok((fs, _)) => fs, 164 | Err(mut e) => { 165 | e.emit(); 166 | return DummyResult::any(sp); 167 | }, 168 | }; 169 | 170 | let mut format_args: Vec> = Vec::new(); 171 | loop { 172 | if parser.eat(&Token::CloseDelim(DelimToken::Paren)) { 173 | break 174 | } else if let Err(mut e) = parser.expect(&Token::Comma) { 175 | e.emit(); 176 | return DummyResult::any(sp); 177 | }; 178 | let ex = match parser.parse_expr() { 179 | Ok(ex) => ex, 180 | Err(mut e) => { 181 | e.emit(); 182 | return DummyResult::any(sp); 183 | }, 184 | }; 185 | format_args.push(ex); 186 | }; 187 | 188 | Some(LongDescription { 189 | format_str: format_str, 190 | format_args: format_args, 191 | }) 192 | } else { 193 | None 194 | }; 195 | 196 | let comment_str = format!("/// {}.", short_desc); 197 | let comment = Symbol::intern(&comment_str[..]); 198 | 199 | // Build our variant definition out of the information we've parsed. 200 | variants.push(VariantDef { 201 | variant: P(dummy_spanned(Variant_ { 202 | name: variant_name, 203 | attrs: vec![mk_sugared_doc_attr(mk_attr_id(), comment, DUMMY_SP)], 204 | data: match members { 205 | None => VariantData::Unit(DUMMY_NODE_ID), 206 | Some(members) => VariantData::Struct(members, DUMMY_NODE_ID), 207 | }, 208 | disr_expr: None, 209 | })), 210 | short_description: short_desc, 211 | from_idx: from_idx, 212 | long_description: long_desc, 213 | }); 214 | 215 | if let Err(mut e) = parser.expect_one_of(&[Token::Comma], &[Token::Eof]) { 216 | e.emit(); 217 | return DummyResult::any(sp); 218 | } 219 | } 220 | 221 | // Helper wrappers for missing ToTokens impls 222 | 223 | struct StructFieldWrapper(StructField); 224 | impl ToTokens for StructFieldWrapper { 225 | fn to_tokens(&self, cx: &ExtCtxt) -> Vec { 226 | let StructFieldWrapper(ref struct_field) = *self; 227 | let StructField { 228 | ref ty, 229 | ref ident, 230 | ref attrs, 231 | .. 232 | } = *struct_field; 233 | 234 | quote_tokens!(cx, $attrs $ident: $ty,) 235 | } 236 | } 237 | 238 | struct VariantWrapper(Variant); 239 | impl ToTokens for VariantWrapper { 240 | fn to_tokens(&self, cx: &ExtCtxt) -> Vec { 241 | let VariantWrapper(ref variant) = *self; 242 | let Variant_ { 243 | ref attrs, 244 | ref name, 245 | ref data, 246 | .. 247 | } = variant.node; 248 | 249 | match *data { 250 | VariantData::Unit(..) => quote_tokens!(cx, $attrs $name,), 251 | VariantData::Struct(ref members, _) => { 252 | let members_wrapped: Vec<_> = members.iter().map(|m| StructFieldWrapper(m.clone())).collect(); 253 | quote_tokens!(cx, $attrs $name { 254 | $members_wrapped 255 | },) 256 | }, 257 | _ => unreachable!(), 258 | } 259 | } 260 | } 261 | 262 | 263 | // Add the enum 264 | 265 | let mut variants_wrapped = Vec::new(); 266 | for v in &variants { 267 | let variant = VariantWrapper((*v.variant).clone()); 268 | variants_wrapped.push(variant); 269 | } 270 | 271 | let the_enum = quote_item!(cx, pub enum $type_name { 272 | $variants_wrapped 273 | }); 274 | 275 | items.push(the_enum.unwrap()); 276 | 277 | // Add Debug impl 278 | 279 | let mut debug_impl_arms = Vec::new(); 280 | for v in &variants { 281 | let VariantDef { 282 | ref variant, 283 | .. 284 | } = *v; 285 | let Variant_ { 286 | ref name, 287 | ref data, 288 | .. 289 | } = variant.node; 290 | 291 | let full_name = Symbol::intern(&format!("{}::{}", type_name, name)); 292 | let full_name = dummy_spanned(ast::LitKind::Str(full_name, ast::StrStyle::Cooked)); 293 | let debug_impl_arm = match *data { 294 | VariantData::Unit(..) => { 295 | quote_tokens!(cx, $type_name::$name => { 296 | write!(f, $full_name)?; 297 | write!(f, " /* {} */", self)?; 298 | }) 299 | }, 300 | VariantData::Struct(ref members, ..) => { 301 | let mut ms = Vec::new(); 302 | let mut body = quote_tokens!(cx, f.debug_struct($full_name)); 303 | for member in members { 304 | let StructField { 305 | ref ident, 306 | .. 307 | } = *member; 308 | let ident = ident.as_ref().unwrap(); 309 | ms.extend(quote_tokens!(cx, ref $ident,)); 310 | let ident_lit = dummy_spanned(ast::LitKind::Str(ident.name, ast::StrStyle::Cooked)); 311 | body.extend(quote_tokens!(cx, .field($ident_lit, $ident))); 312 | } 313 | body.extend(quote_tokens!(cx, .finish()?)); 314 | 315 | quote_tokens!(cx, $type_name::$name { $ms } => { 316 | $body; 317 | write!(f, " /* {} */", self)?; 318 | }) 319 | }, 320 | _ => unreachable!(), 321 | }; 322 | debug_impl_arms.push(debug_impl_arm); 323 | } 324 | 325 | let debug_impl = quote_item!(cx, impl ::std::fmt::Debug for $type_name { 326 | fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { 327 | match *self { 328 | $debug_impl_arms 329 | } 330 | Ok(()) 331 | } 332 | }); 333 | 334 | items.push(debug_impl.unwrap()); 335 | 336 | // Add Display impl 337 | 338 | let mut display_impl_arms = Vec::new(); 339 | for v in &variants { 340 | let VariantDef { 341 | ref variant, 342 | ref short_description, 343 | ref long_description, 344 | .. 345 | } = *v; 346 | let Variant_ { 347 | ref name, 348 | ref data, 349 | .. 350 | } = variant.node; 351 | 352 | let short = dummy_spanned(ast::LitKind::Str(short_description.clone(), ast::StrStyle::Cooked)); 353 | let print_short = quote_stmt!(cx, write!(f, $short)?;); 354 | let mut body = quote_tokens!(cx, $print_short); 355 | if let Some(LongDescription { ref format_str, ref format_args }) = *long_description { 356 | let long_fmt = format!(". {}", format_str); 357 | let long_fmt = Symbol::intern(&long_fmt[..]); 358 | let long = dummy_spanned(ast::LitKind::Str(long_fmt, ast::StrStyle::Cooked)); 359 | let mut args = Vec::new(); 360 | for arg in format_args { 361 | args.extend(quote_tokens!(cx, $arg,)); 362 | } 363 | let print_long = quote_stmt!(cx, write!(f, $long, $args)?;); 364 | body.extend(quote_tokens!(cx, $print_long)); 365 | } 366 | 367 | let display_impl_arm = match *data { 368 | VariantData::Unit(..) => { 369 | quote_tokens!(cx, $type_name::$name => { 370 | $body 371 | }) 372 | }, 373 | VariantData::Struct(ref members, ..) => { 374 | let mut ms = Vec::new(); 375 | for member in members { 376 | let StructField { 377 | ref ident, 378 | .. 379 | } = *member; 380 | ms.extend(quote_tokens!(cx, ref $ident,)); 381 | } 382 | quote_tokens!(cx, $type_name::$name { $ms } => { 383 | $body 384 | }) 385 | }, 386 | _ => unreachable!(), 387 | }; 388 | display_impl_arms.push(display_impl_arm); 389 | } 390 | 391 | let display_impl = quote_item!(cx, impl ::std::fmt::Display for $type_name { 392 | fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { 393 | #[allow(unused)] 394 | match *self { 395 | $display_impl_arms 396 | } 397 | Ok(()) 398 | } 399 | }); 400 | 401 | items.push(display_impl.unwrap()); 402 | 403 | // Add Error impl 404 | 405 | let mut description_impl_arms = Vec::new(); 406 | for v in &variants { 407 | let VariantDef { 408 | ref variant, 409 | ref short_description, 410 | .. 411 | } = *v; 412 | let Variant_ { 413 | ref name, 414 | ref data, 415 | .. 416 | } = variant.node; 417 | 418 | let short = dummy_spanned(ast::LitKind::Str(short_description.clone(), ast::StrStyle::Cooked)); 419 | 420 | let description_impl_arm = match *data { 421 | VariantData::Unit(..) => { 422 | quote_tokens!(cx, $type_name::$name => { 423 | $short 424 | }) 425 | }, 426 | VariantData::Struct(..) => { 427 | quote_tokens!(cx, $type_name::$name { .. } => { 428 | $short 429 | }) 430 | }, 431 | _ => unreachable!(), 432 | }; 433 | description_impl_arms.push(description_impl_arm); 434 | } 435 | 436 | let mut cause_impl_arms = Vec::new(); 437 | for v in &variants { 438 | let VariantDef { 439 | ref variant, 440 | ref from_idx, 441 | .. 442 | } = *v; 443 | let Variant_ { 444 | ref name, 445 | ref data, 446 | .. 447 | } = variant.node; 448 | 449 | let cause_impl_arm = match *data { 450 | VariantData::Unit(..) => { 451 | quote_tokens!(cx, $type_name::$name => None,) 452 | }, 453 | VariantData::Struct(ref members, ..) => { 454 | let mut ms = Vec::new(); 455 | for member in members { 456 | let StructField { 457 | ref ident, 458 | .. 459 | } = *member; 460 | ms.extend(quote_tokens!(cx, ref $ident,)); 461 | } 462 | let expr = match *from_idx { 463 | None => quote_expr!(cx, None), 464 | Some(idx) => { 465 | let StructField { 466 | ref ident, 467 | .. 468 | } = members[idx]; 469 | quote_expr!(cx, Some($ident)) 470 | }, 471 | }; 472 | quote_tokens!(cx, $type_name::$name { $ms } => $expr,) 473 | }, 474 | _ => unreachable!(), 475 | }; 476 | cause_impl_arms.push(cause_impl_arm); 477 | } 478 | 479 | let error_impl = quote_item!(cx, impl ::std::error::Error for $type_name { 480 | fn description(&self) -> &str { 481 | match *self { 482 | $description_impl_arms 483 | } 484 | } 485 | 486 | fn cause(&self) -> Option<&::std::error::Error> { 487 | #[allow(unused)] 488 | match *self { 489 | $cause_impl_arms 490 | } 491 | } 492 | }); 493 | 494 | items.push(error_impl.unwrap()); 495 | 496 | // Add `From` impls 497 | for v in &variants { 498 | let VariantDef { 499 | ref variant, 500 | ref from_idx, 501 | .. 502 | } = *v; 503 | let Variant_ { 504 | ref name, 505 | ref data, 506 | .. 507 | } = variant.node; 508 | 509 | if let Some(idx) = *from_idx { 510 | let members = match *data { 511 | VariantData::Struct(ref members, ..) => members, 512 | _ => unreachable!(), 513 | }; 514 | if members.len() != 1 { 515 | continue; 516 | } 517 | let StructField { 518 | ref ty, 519 | ref ident, 520 | .. 521 | } = members[idx]; 522 | let from_impl = quote_item!(cx, impl ::std::convert::From<$ty> for $type_name { 523 | fn from(val: $ty) -> $type_name { 524 | $type_name::$name { $ident: val } 525 | } 526 | }); 527 | items.push(from_impl.unwrap()); 528 | } 529 | } 530 | 531 | MacEager::items((SmallVector::many(items))) 532 | } 533 | 534 | #[plugin_registrar] 535 | pub fn plugin_registrar(reg: &mut Registry) { 536 | reg.register_syntax_extension( 537 | Symbol::intern("error_def"), 538 | SyntaxExtension::IdentTT(Box::new(expand_error_def), None, false) 539 | ); 540 | } 541 | 542 | --------------------------------------------------------------------------------