]> git.lizzy.rs Git - rust.git/blob - src/libsyntax_ext/deriving/mod.rs
Hygienize `librustc_resolve`.
[rust.git] / src / libsyntax_ext / deriving / mod.rs
1 // Copyright 2012-2015 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 //! The compiler code necessary to implement the `#[derive]` extensions.
12
13 use std::rc::Rc;
14 use syntax::ast;
15 use syntax::ext::base::{Annotatable, ExtCtxt, SyntaxExtension, Resolver};
16 use syntax::ext::build::AstBuilder;
17 use syntax::ext::hygiene::{Mark, SyntaxContext};
18 use syntax::ptr::P;
19 use syntax::symbol::Symbol;
20 use syntax_pos::Span;
21
22 macro_rules! pathvec {
23     ($($x:ident)::+) => (
24         vec![ $( stringify!($x) ),+ ]
25     )
26 }
27
28 macro_rules! path_local {
29     ($x:ident) => (
30         ::deriving::generic::ty::Path::new_local(stringify!($x))
31     )
32 }
33
34 macro_rules! pathvec_std {
35     ($cx:expr, $first:ident :: $($rest:ident)::+) => ({
36         let mut v = pathvec![$($rest)::+];
37         if let Some(s) = $cx.crate_root {
38             v.insert(0, s);
39         }
40         v
41     })
42 }
43
44 macro_rules! path_std {
45     ($($x:tt)*) => (
46         ::deriving::generic::ty::Path::new( pathvec_std!( $($x)* ) )
47     )
48 }
49
50 pub mod bounds;
51 pub mod clone;
52 pub mod encodable;
53 pub mod decodable;
54 pub mod hash;
55 pub mod debug;
56 pub mod default;
57 pub mod custom;
58
59 #[path="cmp/partial_eq.rs"]
60 pub mod partial_eq;
61 #[path="cmp/eq.rs"]
62 pub mod eq;
63 #[path="cmp/partial_ord.rs"]
64 pub mod partial_ord;
65 #[path="cmp/ord.rs"]
66 pub mod ord;
67
68
69 pub mod generic;
70
71 macro_rules! derive_traits {
72     ($( $name:expr => $func:path, )+) => {
73         pub fn is_builtin_trait(name: ast::Name) -> bool {
74             match &*name.as_str() {
75                 $( $name )|+ => true,
76                 _ => false,
77             }
78         }
79
80         pub fn register_builtin_derives(resolver: &mut Resolver) {
81             $(
82                 resolver.add_builtin(
83                     ast::Ident::with_empty_ctxt(Symbol::intern($name)),
84                     Rc::new(SyntaxExtension::BuiltinDerive($func))
85                 );
86             )*
87         }
88     }
89 }
90
91 derive_traits! {
92     "Clone" => clone::expand_deriving_clone,
93
94     "Hash" => hash::expand_deriving_hash,
95
96     "RustcEncodable" => encodable::expand_deriving_rustc_encodable,
97
98     "RustcDecodable" => decodable::expand_deriving_rustc_decodable,
99
100     "PartialEq" => partial_eq::expand_deriving_partial_eq,
101     "Eq" => eq::expand_deriving_eq,
102     "PartialOrd" => partial_ord::expand_deriving_partial_ord,
103     "Ord" => ord::expand_deriving_ord,
104
105     "Debug" => debug::expand_deriving_debug,
106
107     "Default" => default::expand_deriving_default,
108
109     "Send" => bounds::expand_deriving_unsafe_bound,
110     "Sync" => bounds::expand_deriving_unsafe_bound,
111     "Copy" => bounds::expand_deriving_copy,
112
113     // deprecated
114     "Encodable" => encodable::expand_deriving_encodable,
115     "Decodable" => decodable::expand_deriving_decodable,
116 }
117
118 #[inline] // because `name` is a compile-time constant
119 fn warn_if_deprecated(ecx: &mut ExtCtxt, sp: Span, name: &str) {
120     if let Some(replacement) = match name {
121         "Encodable" => Some("RustcEncodable"),
122         "Decodable" => Some("RustcDecodable"),
123         _ => None,
124     } {
125         ecx.span_warn(sp,
126                       &format!("derive({}) is deprecated in favor of derive({})",
127                                name,
128                                replacement));
129     }
130 }
131
132 /// Construct a name for the inner type parameter that can't collide with any type parameters of
133 /// the item. This is achieved by starting with a base and then concatenating the names of all
134 /// other type parameters.
135 // FIXME(aburka): use real hygiene when that becomes possible
136 fn hygienic_type_parameter(item: &Annotatable, base: &str) -> String {
137     let mut typaram = String::from(base);
138     if let Annotatable::Item(ref item) = *item {
139         match item.node {
140             ast::ItemKind::Struct(_, ast::Generics { ref ty_params, .. }) |
141             ast::ItemKind::Enum(_, ast::Generics { ref ty_params, .. }) => {
142                 for ty in ty_params.iter() {
143                     typaram.push_str(&ty.ident.name.as_str());
144                 }
145             }
146
147             _ => {}
148         }
149     }
150
151     typaram
152 }
153
154 /// Constructs an expression that calls an intrinsic
155 fn call_intrinsic(cx: &ExtCtxt,
156                   mut span: Span,
157                   intrinsic: &str,
158                   args: Vec<P<ast::Expr>>)
159                   -> P<ast::Expr> {
160     if cx.current_expansion.mark.expn_info().unwrap().callee.allow_internal_unstable {
161         span.ctxt = cx.backtrace();
162     } else { // Avoid instability errors with user defined curstom derives, cc #36316
163         let mut info = cx.current_expansion.mark.expn_info().unwrap();
164         info.callee.allow_internal_unstable = true;
165         let mark = Mark::fresh(Mark::root());
166         mark.set_expn_info(info);
167         span.ctxt = SyntaxContext::empty().apply_mark(mark);
168     }
169     let path = cx.std_path(&["intrinsics", intrinsic]);
170     let call = cx.expr_call_global(span, path, args);
171
172     cx.expr_block(P(ast::Block {
173         stmts: vec![cx.stmt_expr(call)],
174         id: ast::DUMMY_NODE_ID,
175         rules: ast::BlockCheckMode::Unsafe(ast::CompilerGenerated),
176         span: span,
177     }))
178 }