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