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