]> git.lizzy.rs Git - rust.git/blob - src/libsyntax_ext/proc_macro_impl.rs
Simplify SaveHandler trait
[rust.git] / src / libsyntax_ext / proc_macro_impl.rs
1 use crate::proc_macro_server;
2
3 use errors::FatalError;
4 use syntax::source_map::Span;
5 use syntax::ext::base::{self, *};
6 use syntax::tokenstream::TokenStream;
7
8 pub const EXEC_STRATEGY: proc_macro::bridge::server::SameThread =
9     proc_macro::bridge::server::SameThread;
10
11 pub struct AttrProcMacro {
12     pub client: proc_macro::bridge::client::Client<
13         fn(proc_macro::TokenStream, proc_macro::TokenStream) -> proc_macro::TokenStream,
14     >,
15 }
16
17 impl base::AttrProcMacro for AttrProcMacro {
18     fn expand<'cx>(&self,
19                    ecx: &'cx mut ExtCtxt<'_>,
20                    span: Span,
21                    annotation: TokenStream,
22                    annotated: TokenStream)
23                    -> TokenStream {
24         let server = proc_macro_server::Rustc::new(ecx);
25         match self.client.run(&EXEC_STRATEGY, server, annotation, annotated) {
26             Ok(stream) => stream,
27             Err(e) => {
28                 let msg = "custom attribute panicked";
29                 let mut err = ecx.struct_span_fatal(span, msg);
30                 if let Some(s) = e.as_str() {
31                     err.help(&format!("message: {}", s));
32                 }
33
34                 err.emit();
35                 FatalError.raise();
36             }
37         }
38     }
39 }
40
41 pub struct BangProcMacro {
42     pub client: proc_macro::bridge::client::Client<
43         fn(proc_macro::TokenStream) -> proc_macro::TokenStream,
44     >,
45 }
46
47 impl base::ProcMacro for BangProcMacro {
48     fn expand<'cx>(&self,
49                    ecx: &'cx mut ExtCtxt<'_>,
50                    span: Span,
51                    input: TokenStream)
52                    -> TokenStream {
53         let server = proc_macro_server::Rustc::new(ecx);
54         match self.client.run(&EXEC_STRATEGY, server, input) {
55             Ok(stream) => stream,
56             Err(e) => {
57                 let msg = "proc macro panicked";
58                 let mut err = ecx.struct_span_fatal(span, msg);
59                 if let Some(s) = e.as_str() {
60                     err.help(&format!("message: {}", s));
61                 }
62
63                 err.emit();
64                 FatalError.raise();
65             }
66         }
67     }
68 }