]> git.lizzy.rs Git - rust.git/blob - src/librustc/metadata/tyencode.rs
auto merge of #14789 : aochagavia/rust/prelude, r=alexcrichton
[rust.git] / src / librustc / metadata / tyencode.rs
1 // Copyright 2012-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 // Type encoding
12
13 #![allow(unused_must_use)] // as with encoding, everything is a no-fail MemWriter
14 #![allow(non_camel_case_types)]
15
16 use std::cell::RefCell;
17 use std::collections::HashMap;
18 use std::io::MemWriter;
19
20 use middle::subst;
21 use middle::ty::param_ty;
22 use middle::ty;
23
24 use syntax::abi::Abi;
25 use syntax::ast;
26 use syntax::ast::*;
27 use syntax::diagnostic::SpanHandler;
28 use syntax::parse::token;
29
30 macro_rules! mywrite( ($($arg:tt)*) => ({ write!($($arg)*); }) )
31
32 pub struct ctxt<'a> {
33     pub diag: &'a SpanHandler,
34     // Def -> str Callback:
35     pub ds: fn(DefId) -> String,
36     // The type context.
37     pub tcx: &'a ty::ctxt,
38     pub abbrevs: &'a abbrev_map
39 }
40
41 // Compact string representation for ty.t values. API ty_str & parse_from_str.
42 // Extra parameters are for converting to/from def_ids in the string rep.
43 // Whatever format you choose should not contain pipe characters.
44 pub struct ty_abbrev {
45     s: String
46 }
47
48 pub type abbrev_map = RefCell<HashMap<ty::t, ty_abbrev>>;
49
50 pub fn enc_ty(w: &mut MemWriter, cx: &ctxt, t: ty::t) {
51     match cx.abbrevs.borrow_mut().find(&t) {
52         Some(a) => { w.write(a.s.as_bytes()); return; }
53         None => {}
54     }
55     let pos = w.tell().unwrap();
56     enc_sty(w, cx, &ty::get(t).sty);
57     let end = w.tell().unwrap();
58     let len = end - pos;
59     fn estimate_sz(u: u64) -> u64 {
60         let mut n = u;
61         let mut len = 0;
62         while n != 0 { len += 1; n = n >> 4; }
63         return len;
64     }
65     let abbrev_len = 3 + estimate_sz(pos) + estimate_sz(len);
66     if abbrev_len < len {
67         // I.e. it's actually an abbreviation.
68         cx.abbrevs.borrow_mut().insert(t, ty_abbrev {
69             s: format!("\\#{:x}:{:x}\\#", pos, len)
70         });
71     }
72 }
73
74 fn enc_mutability(w: &mut MemWriter, mt: ast::Mutability) {
75     match mt {
76         MutImmutable => (),
77         MutMutable => mywrite!(w, "m"),
78     }
79 }
80
81 fn enc_mt(w: &mut MemWriter, cx: &ctxt, mt: ty::mt) {
82     enc_mutability(w, mt.mutbl);
83     enc_ty(w, cx, mt.ty);
84 }
85
86 fn enc_opt<T>(w: &mut MemWriter, t: Option<T>, enc_f: |&mut MemWriter, T|) {
87     match t {
88         None => mywrite!(w, "n"),
89         Some(v) => {
90             mywrite!(w, "s");
91             enc_f(w, v);
92         }
93     }
94 }
95
96 pub fn enc_substs(w: &mut MemWriter, cx: &ctxt, substs: &subst::Substs) {
97     enc_region_substs(w, cx, &substs.regions);
98     enc_opt(w, substs.self_ty, |w, t| enc_ty(w, cx, t));
99     mywrite!(w, "[");
100     for t in substs.tps.iter() { enc_ty(w, cx, *t); }
101     mywrite!(w, "]");
102 }
103
104 fn enc_region_substs(w: &mut MemWriter, cx: &ctxt, substs: &subst::RegionSubsts) {
105     match *substs {
106         subst::ErasedRegions => {
107             mywrite!(w, "e");
108         }
109         subst::NonerasedRegions(ref regions) => {
110             mywrite!(w, "n");
111             for &r in regions.iter() {
112                 enc_region(w, cx, r);
113             }
114             mywrite!(w, ".");
115         }
116     }
117 }
118
119 fn enc_region(w: &mut MemWriter, cx: &ctxt, r: ty::Region) {
120     match r {
121         ty::ReLateBound(id, br) => {
122             mywrite!(w, "b[{}|", id);
123             enc_bound_region(w, cx, br);
124             mywrite!(w, "]");
125         }
126         ty::ReEarlyBound(node_id, index, name) => {
127             mywrite!(w, "B[{}|{}|{}]",
128                      node_id,
129                      index,
130                      token::get_name(name));
131         }
132         ty::ReFree(ref fr) => {
133             mywrite!(w, "f[{}|", fr.scope_id);
134             enc_bound_region(w, cx, fr.bound_region);
135             mywrite!(w, "]");
136         }
137         ty::ReScope(nid) => {
138             mywrite!(w, "s{}|", nid);
139         }
140         ty::ReStatic => {
141             mywrite!(w, "t");
142         }
143         ty::ReEmpty => {
144             mywrite!(w, "e");
145         }
146         ty::ReInfer(_) => {
147             // these should not crop up after typeck
148             cx.diag.handler().bug("cannot encode region variables");
149         }
150     }
151 }
152
153 fn enc_bound_region(w: &mut MemWriter, cx: &ctxt, br: ty::BoundRegion) {
154     match br {
155         ty::BrAnon(idx) => {
156             mywrite!(w, "a{}|", idx);
157         }
158         ty::BrNamed(d, name) => {
159             mywrite!(w, "[{}|{}]",
160                      (cx.ds)(d),
161                      token::get_name(name));
162         }
163         ty::BrFresh(id) => {
164             mywrite!(w, "f{}|", id);
165         }
166     }
167 }
168
169 pub fn enc_trait_ref(w: &mut MemWriter, cx: &ctxt, s: &ty::TraitRef) {
170     mywrite!(w, "{}|", (cx.ds)(s.def_id));
171     enc_substs(w, cx, &s.substs);
172 }
173
174 pub fn enc_trait_store(w: &mut MemWriter, cx: &ctxt, s: ty::TraitStore) {
175     match s {
176         ty::UniqTraitStore => mywrite!(w, "~"),
177         ty::RegionTraitStore(re, m) => {
178             mywrite!(w, "&");
179             enc_region(w, cx, re);
180             enc_mutability(w, m);
181         }
182     }
183 }
184
185 fn enc_sty(w: &mut MemWriter, cx: &ctxt, st: &ty::sty) {
186     match *st {
187         ty::ty_nil => mywrite!(w, "n"),
188         ty::ty_bot => mywrite!(w, "z"),
189         ty::ty_bool => mywrite!(w, "b"),
190         ty::ty_char => mywrite!(w, "c"),
191         ty::ty_int(t) => {
192             match t {
193                 TyI => mywrite!(w, "i"),
194                 TyI8 => mywrite!(w, "MB"),
195                 TyI16 => mywrite!(w, "MW"),
196                 TyI32 => mywrite!(w, "ML"),
197                 TyI64 => mywrite!(w, "MD")
198             }
199         }
200         ty::ty_uint(t) => {
201             match t {
202                 TyU => mywrite!(w, "u"),
203                 TyU8 => mywrite!(w, "Mb"),
204                 TyU16 => mywrite!(w, "Mw"),
205                 TyU32 => mywrite!(w, "Ml"),
206                 TyU64 => mywrite!(w, "Md")
207             }
208         }
209         ty::ty_float(t) => {
210             match t {
211                 TyF32 => mywrite!(w, "Mf"),
212                 TyF64 => mywrite!(w, "MF"),
213                 TyF128 => mywrite!(w, "MQ")
214             }
215         }
216         ty::ty_enum(def, ref substs) => {
217             mywrite!(w, "t[{}|", (cx.ds)(def));
218             enc_substs(w, cx, substs);
219             mywrite!(w, "]");
220         }
221         ty::ty_trait(box ty::TyTrait {
222                 def_id,
223                 ref substs,
224                 store,
225                 bounds
226             }) => {
227             mywrite!(w, "x[{}|", (cx.ds)(def_id));
228             enc_substs(w, cx, substs);
229             enc_trait_store(w, cx, store);
230             let bounds = ty::ParamBounds {builtin_bounds: bounds,
231                                           trait_bounds: Vec::new()};
232             enc_bounds(w, cx, &bounds);
233             mywrite!(w, "]");
234         }
235         ty::ty_tup(ref ts) => {
236             mywrite!(w, "T[");
237             for t in ts.iter() { enc_ty(w, cx, *t); }
238             mywrite!(w, "]");
239         }
240         ty::ty_box(typ) => { mywrite!(w, "@"); enc_ty(w, cx, typ); }
241         ty::ty_uniq(typ) => { mywrite!(w, "~"); enc_ty(w, cx, typ); }
242         ty::ty_ptr(mt) => { mywrite!(w, "*"); enc_mt(w, cx, mt); }
243         ty::ty_rptr(r, mt) => {
244             mywrite!(w, "&");
245             enc_region(w, cx, r);
246             enc_mt(w, cx, mt);
247         }
248         ty::ty_vec(mt, sz) => {
249             mywrite!(w, "V");
250             enc_mt(w, cx, mt);
251             mywrite!(w, "/");
252             match sz {
253                 Some(n) => mywrite!(w, "{}|", n),
254                 None => mywrite!(w, "|"),
255             }
256         }
257         ty::ty_str => {
258             mywrite!(w, "v");
259         }
260         ty::ty_closure(ref f) => {
261             mywrite!(w, "f");
262             enc_closure_ty(w, cx, *f);
263         }
264         ty::ty_bare_fn(ref f) => {
265             mywrite!(w, "F");
266             enc_bare_fn_ty(w, cx, f);
267         }
268         ty::ty_infer(_) => {
269             cx.diag.handler().bug("cannot encode inference variable types");
270         }
271         ty::ty_param(param_ty {idx: id, def_id: did}) => {
272             mywrite!(w, "p{}|{}", (cx.ds)(did), id);
273         }
274         ty::ty_self(did) => {
275             mywrite!(w, "s{}|", (cx.ds)(did));
276         }
277         ty::ty_struct(def, ref substs) => {
278             mywrite!(w, "a[{}|", (cx.ds)(def));
279             enc_substs(w, cx, substs);
280             mywrite!(w, "]");
281         }
282         ty::ty_err => fail!("shouldn't encode error type")
283     }
284 }
285
286 fn enc_fn_style(w: &mut MemWriter, p: FnStyle) {
287     match p {
288         NormalFn => mywrite!(w, "n"),
289         UnsafeFn => mywrite!(w, "u"),
290     }
291 }
292
293 fn enc_abi(w: &mut MemWriter, abi: Abi) {
294     mywrite!(w, "[");
295     mywrite!(w, "{}", abi.name());
296     mywrite!(w, "]")
297 }
298
299 fn enc_onceness(w: &mut MemWriter, o: Onceness) {
300     match o {
301         Once => mywrite!(w, "o"),
302         Many => mywrite!(w, "m")
303     }
304 }
305
306 pub fn enc_bare_fn_ty(w: &mut MemWriter, cx: &ctxt, ft: &ty::BareFnTy) {
307     enc_fn_style(w, ft.fn_style);
308     enc_abi(w, ft.abi);
309     enc_fn_sig(w, cx, &ft.sig);
310 }
311
312 fn enc_closure_ty(w: &mut MemWriter, cx: &ctxt, ft: &ty::ClosureTy) {
313     enc_fn_style(w, ft.fn_style);
314     enc_onceness(w, ft.onceness);
315     enc_trait_store(w, cx, ft.store);
316     let bounds = ty::ParamBounds {builtin_bounds: ft.bounds,
317                                   trait_bounds: Vec::new()};
318     enc_bounds(w, cx, &bounds);
319     enc_fn_sig(w, cx, &ft.sig);
320 }
321
322 fn enc_fn_sig(w: &mut MemWriter, cx: &ctxt, fsig: &ty::FnSig) {
323     mywrite!(w, "[{}|", fsig.binder_id);
324     for ty in fsig.inputs.iter() {
325         enc_ty(w, cx, *ty);
326     }
327     mywrite!(w, "]");
328     if fsig.variadic {
329         mywrite!(w, "V");
330     } else {
331         mywrite!(w, "N");
332     }
333     enc_ty(w, cx, fsig.output);
334 }
335
336 fn enc_bounds(w: &mut MemWriter, cx: &ctxt, bs: &ty::ParamBounds) {
337     for bound in bs.builtin_bounds.iter() {
338         match bound {
339             ty::BoundSend => mywrite!(w, "S"),
340             ty::BoundStatic => mywrite!(w, "O"),
341             ty::BoundSized => mywrite!(w, "Z"),
342             ty::BoundCopy => mywrite!(w, "P"),
343             ty::BoundShare => mywrite!(w, "T"),
344         }
345     }
346
347     for tp in bs.trait_bounds.iter() {
348         mywrite!(w, "I");
349         enc_trait_ref(w, cx, &**tp);
350     }
351
352     mywrite!(w, ".");
353 }
354
355 pub fn enc_type_param_def(w: &mut MemWriter, cx: &ctxt, v: &ty::TypeParameterDef) {
356     mywrite!(w, "{}:{}|", token::get_ident(v.ident), (cx.ds)(v.def_id));
357     enc_bounds(w, cx, &*v.bounds);
358     enc_opt(w, v.default, |w, t| enc_ty(w, cx, t));
359 }