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