]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/diagnostics/plugin.rs
std: Add a new top-level thread_local module
[rust.git] / src / libsyntax / diagnostics / plugin.rs
1 // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 use std::cell::RefCell;
12 use std::collections::HashMap;
13 use ast;
14 use ast::{Ident, Name, TokenTree};
15 use codemap::Span;
16 use ext::base::{ExtCtxt, MacExpr, MacResult, MacItems};
17 use ext::build::AstBuilder;
18 use parse::token;
19 use ptr::P;
20
21 thread_local!(static REGISTERED_DIAGNOSTICS: RefCell<HashMap<Name, Option<Name>>> = {
22     RefCell::new(HashMap::new())
23 })
24 thread_local!(static USED_DIAGNOSTICS: RefCell<HashMap<Name, Span>> = {
25     RefCell::new(HashMap::new())
26 })
27
28 fn with_registered_diagnostics<T>(f: |&mut HashMap<Name, Option<Name>>| -> T) -> T {
29     REGISTERED_DIAGNOSTICS.with(|slot| {
30         f(&mut *slot.borrow_mut())
31     })
32 }
33
34 fn with_used_diagnostics<T>(f: |&mut HashMap<Name, Span>| -> T) -> T {
35     USED_DIAGNOSTICS.with(|slot| {
36         f(&mut *slot.borrow_mut())
37     })
38 }
39
40 pub fn expand_diagnostic_used<'cx>(ecx: &'cx mut ExtCtxt,
41                                    span: Span,
42                                    token_tree: &[TokenTree])
43                                    -> Box<MacResult+'cx> {
44     let code = match token_tree {
45         [ast::TtToken(_, token::Ident(code, _))] => code,
46         _ => unreachable!()
47     };
48     with_registered_diagnostics(|diagnostics| {
49         if !diagnostics.contains_key(&code.name) {
50             ecx.span_err(span, format!(
51                 "unknown diagnostic code {}; add to librustc/diagnostics.rs",
52                 token::get_ident(code).get()
53             ).as_slice());
54         }
55         ()
56     });
57     with_used_diagnostics(|diagnostics| {
58         match diagnostics.insert(code.name, span) {
59             Some(previous_span) => {
60                 ecx.span_warn(span, format!(
61                     "diagnostic code {} already used", token::get_ident(code).get()
62                 ).as_slice());
63                 ecx.span_note(previous_span, "previous invocation");
64             },
65             None => ()
66         }
67         ()
68     });
69     MacExpr::new(quote_expr!(ecx, ()))
70 }
71
72 pub fn expand_register_diagnostic<'cx>(ecx: &'cx mut ExtCtxt,
73                                        span: Span,
74                                        token_tree: &[TokenTree])
75                                        -> Box<MacResult+'cx> {
76     let (code, description) = match token_tree {
77         [ast::TtToken(_, token::Ident(ref code, _))] => {
78             (code, None)
79         },
80         [ast::TtToken(_, token::Ident(ref code, _)),
81          ast::TtToken(_, token::Comma),
82          ast::TtToken(_, token::Literal(token::StrRaw(description, _), None))] => {
83             (code, Some(description))
84         }
85         _ => unreachable!()
86     };
87     with_registered_diagnostics(|diagnostics| {
88         if diagnostics.insert(code.name, description).is_some() {
89             ecx.span_err(span, format!(
90                 "diagnostic code {} already registered", token::get_ident(*code).get()
91             ).as_slice());
92         }
93     });
94     let sym = Ident::new(token::gensym((
95         "__register_diagnostic_".to_string() + token::get_ident(*code).get()
96     ).as_slice()));
97     MacItems::new(vec![quote_item!(ecx, mod $sym {}).unwrap()].into_iter())
98 }
99
100 pub fn expand_build_diagnostic_array<'cx>(ecx: &'cx mut ExtCtxt,
101                                           span: Span,
102                                           token_tree: &[TokenTree])
103                                           -> Box<MacResult+'cx> {
104     let name = match token_tree {
105         [ast::TtToken(_, token::Ident(ref name, _))] => name,
106         _ => unreachable!()
107     };
108
109     let (count, expr) = with_used_diagnostics(|diagnostics_in_use| {
110         with_registered_diagnostics(|diagnostics| {
111             let descriptions: Vec<P<ast::Expr>> = diagnostics
112                 .iter().filter_map(|(code, description)| {
113                 if !diagnostics_in_use.contains_key(code) {
114                     ecx.span_warn(span, format!(
115                         "diagnostic code {} never used", token::get_name(*code).get()
116                     ).as_slice());
117                 }
118                 description.map(|description| {
119                     ecx.expr_tuple(span, vec![
120                         ecx.expr_str(span, token::get_name(*code)),
121                         ecx.expr_str(span, token::get_name(description))
122                     ])
123                 })
124             }).collect();
125             (descriptions.len(), ecx.expr_vec(span, descriptions))
126         })
127     });
128     MacItems::new(vec![quote_item!(ecx,
129         pub static $name: [(&'static str, &'static str), ..$count] = $expr;
130     ).unwrap()].into_iter())
131 }