]> git.lizzy.rs Git - rust.git/blob - src/librustc/metadata/tyencode.rs
return &mut T from the arenas, not &T
[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
19 use middle::subst;
20 use middle::subst::VecPerParamSpace;
21 use middle::ty::ParamTy;
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 use rbml::io::SeekableMemWriter;
31
32 macro_rules! mywrite( ($($arg:tt)*) => ({ write!($($arg)*); }) )
33
34 pub struct ctxt<'a, 'tcx: 'a> {
35     pub diag: &'a SpanHandler,
36     // Def -> str Callback:
37     pub ds: fn(DefId) -> String,
38     // The type context.
39     pub tcx: &'a ty::ctxt<'tcx>,
40     pub abbrevs: &'a abbrev_map
41 }
42
43 // Compact string representation for ty.t values. API ty_str & parse_from_str.
44 // Extra parameters are for converting to/from def_ids in the string rep.
45 // Whatever format you choose should not contain pipe characters.
46 pub struct ty_abbrev {
47     s: String
48 }
49
50 pub type abbrev_map = RefCell<HashMap<ty::t, ty_abbrev>>;
51
52 pub fn enc_ty(w: &mut SeekableMemWriter, 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
76 fn enc_mutability(w: &mut SeekableMemWriter, mt: ast::Mutability) {
77     match mt {
78         MutImmutable => (),
79         MutMutable => mywrite!(w, "m"),
80     }
81 }
82
83 fn enc_mt(w: &mut SeekableMemWriter, cx: &ctxt, mt: ty::mt) {
84     enc_mutability(w, mt.mutbl);
85     enc_ty(w, cx, mt.ty);
86 }
87
88 fn enc_opt<T>(w: &mut SeekableMemWriter, t: Option<T>, enc_f: |&mut SeekableMemWriter, T|) {
89     match t {
90         None => mywrite!(w, "n"),
91         Some(v) => {
92             mywrite!(w, "s");
93             enc_f(w, v);
94         }
95     }
96 }
97
98 fn enc_vec_per_param_space<T>(w: &mut SeekableMemWriter,
99                               cx: &ctxt,
100                               v: &VecPerParamSpace<T>,
101                               op: |&mut SeekableMemWriter, &ctxt, &T|) {
102     for &space in subst::ParamSpace::all().iter() {
103         mywrite!(w, "[");
104         for t in v.get_slice(space).iter() {
105             op(w, cx, t);
106         }
107         mywrite!(w, "]");
108     }
109 }
110
111 pub fn enc_substs(w: &mut SeekableMemWriter, cx: &ctxt, substs: &subst::Substs) {
112     enc_region_substs(w, cx, &substs.regions);
113     enc_vec_per_param_space(w, cx, &substs.types,
114                             |w, cx, &ty| enc_ty(w, cx, ty));
115 }
116
117 fn enc_region_substs(w: &mut SeekableMemWriter, cx: &ctxt, substs: &subst::RegionSubsts) {
118     match *substs {
119         subst::ErasedRegions => {
120             mywrite!(w, "e");
121         }
122         subst::NonerasedRegions(ref regions) => {
123             mywrite!(w, "n");
124             enc_vec_per_param_space(w, cx, regions,
125                                     |w, cx, &r| enc_region(w, cx, r));
126         }
127     }
128 }
129
130 pub fn enc_region(w: &mut SeekableMemWriter, cx: &ctxt, r: ty::Region) {
131     match r {
132         ty::ReLateBound(id, br) => {
133             mywrite!(w, "b[{}|", id);
134             enc_bound_region(w, cx, br);
135             mywrite!(w, "]");
136         }
137         ty::ReEarlyBound(node_id, space, index, name) => {
138             mywrite!(w, "B[{}|{}|{}|{}]",
139                      node_id,
140                      space.to_uint(),
141                      index,
142                      token::get_name(name));
143         }
144         ty::ReFree(ref fr) => {
145             mywrite!(w, "f[{}|", fr.scope_id);
146             enc_bound_region(w, cx, fr.bound_region);
147             mywrite!(w, "]");
148         }
149         ty::ReScope(nid) => {
150             mywrite!(w, "s{}|", nid);
151         }
152         ty::ReStatic => {
153             mywrite!(w, "t");
154         }
155         ty::ReEmpty => {
156             mywrite!(w, "e");
157         }
158         ty::ReInfer(_) => {
159             // these should not crop up after typeck
160             cx.diag.handler().bug("cannot encode region variables");
161         }
162     }
163 }
164
165 fn enc_bound_region(w: &mut SeekableMemWriter, cx: &ctxt, br: ty::BoundRegion) {
166     match br {
167         ty::BrAnon(idx) => {
168             mywrite!(w, "a{}|", idx);
169         }
170         ty::BrNamed(d, name) => {
171             mywrite!(w, "[{}|{}]",
172                      (cx.ds)(d),
173                      token::get_name(name));
174         }
175         ty::BrFresh(id) => {
176             mywrite!(w, "f{}|", id);
177         }
178         ty::BrEnv => {
179             mywrite!(w, "e|");
180         }
181     }
182 }
183
184 pub fn enc_trait_ref(w: &mut SeekableMemWriter, cx: &ctxt, s: &ty::TraitRef) {
185     mywrite!(w, "{}|", (cx.ds)(s.def_id));
186     enc_substs(w, cx, &s.substs);
187 }
188
189 pub fn enc_trait_store(w: &mut SeekableMemWriter, cx: &ctxt, s: ty::TraitStore) {
190     match s {
191         ty::UniqTraitStore => mywrite!(w, "~"),
192         ty::RegionTraitStore(re, m) => {
193             mywrite!(w, "&");
194             enc_region(w, cx, re);
195             enc_mutability(w, m);
196         }
197     }
198 }
199
200 fn enc_sty(w: &mut SeekableMemWriter, cx: &ctxt, st: &ty::sty) {
201     match *st {
202         ty::ty_nil => mywrite!(w, "n"),
203         ty::ty_bot => mywrite!(w, "z"),
204         ty::ty_bool => mywrite!(w, "b"),
205         ty::ty_char => mywrite!(w, "c"),
206         ty::ty_int(t) => {
207             match t {
208                 TyI => mywrite!(w, "i"),
209                 TyI8 => mywrite!(w, "MB"),
210                 TyI16 => mywrite!(w, "MW"),
211                 TyI32 => mywrite!(w, "ML"),
212                 TyI64 => mywrite!(w, "MD")
213             }
214         }
215         ty::ty_uint(t) => {
216             match t {
217                 TyU => mywrite!(w, "u"),
218                 TyU8 => mywrite!(w, "Mb"),
219                 TyU16 => mywrite!(w, "Mw"),
220                 TyU32 => mywrite!(w, "Ml"),
221                 TyU64 => mywrite!(w, "Md")
222             }
223         }
224         ty::ty_float(t) => {
225             match t {
226                 TyF32 => mywrite!(w, "Mf"),
227                 TyF64 => mywrite!(w, "MF"),
228             }
229         }
230         ty::ty_enum(def, ref substs) => {
231             mywrite!(w, "t[{}|", (cx.ds)(def));
232             enc_substs(w, cx, substs);
233             mywrite!(w, "]");
234         }
235         ty::ty_trait(box ty::TyTrait {
236                 def_id,
237                 ref substs,
238                 ref bounds
239             }) => {
240             mywrite!(w, "x[{}|", (cx.ds)(def_id));
241             enc_substs(w, cx, substs);
242             enc_existential_bounds(w, cx, bounds);
243             mywrite!(w, "]");
244         }
245         ty::ty_tup(ref ts) => {
246             mywrite!(w, "T[");
247             for t in ts.iter() { enc_ty(w, cx, *t); }
248             mywrite!(w, "]");
249         }
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(t, sz) => {
258             mywrite!(w, "V");
259             enc_ty(w, cx, t);
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_unboxed_closure(def, region) => {
289             mywrite!(w, "k{}", (cx.ds)(def));
290             enc_region(w, cx, region);
291         }
292         ty::ty_err => {
293             mywrite!(w, "e");
294         }
295         ty::ty_open(_) => {
296             cx.diag.handler().bug("unexpected type in enc_sty (ty_open)");
297         }
298     }
299 }
300
301 fn enc_fn_style(w: &mut SeekableMemWriter, p: FnStyle) {
302     match p {
303         NormalFn => mywrite!(w, "n"),
304         UnsafeFn => mywrite!(w, "u"),
305     }
306 }
307
308 fn enc_abi(w: &mut SeekableMemWriter, abi: Abi) {
309     mywrite!(w, "[");
310     mywrite!(w, "{}", abi.name());
311     mywrite!(w, "]")
312 }
313
314 fn enc_onceness(w: &mut SeekableMemWriter, o: Onceness) {
315     match o {
316         Once => mywrite!(w, "o"),
317         Many => mywrite!(w, "m")
318     }
319 }
320
321 pub fn enc_bare_fn_ty(w: &mut SeekableMemWriter, cx: &ctxt, ft: &ty::BareFnTy) {
322     enc_fn_style(w, ft.fn_style);
323     enc_abi(w, ft.abi);
324     enc_fn_sig(w, cx, &ft.sig);
325 }
326
327 pub fn enc_closure_ty(w: &mut SeekableMemWriter, cx: &ctxt, ft: &ty::ClosureTy) {
328     enc_fn_style(w, ft.fn_style);
329     enc_onceness(w, ft.onceness);
330     enc_trait_store(w, cx, ft.store);
331     enc_existential_bounds(w, cx, &ft.bounds);
332     enc_fn_sig(w, cx, &ft.sig);
333     enc_abi(w, ft.abi);
334 }
335
336 fn enc_fn_sig(w: &mut SeekableMemWriter, cx: &ctxt, fsig: &ty::FnSig) {
337     mywrite!(w, "[{}|", fsig.binder_id);
338     for ty in fsig.inputs.iter() {
339         enc_ty(w, cx, *ty);
340     }
341     mywrite!(w, "]");
342     if fsig.variadic {
343         mywrite!(w, "V");
344     } else {
345         mywrite!(w, "N");
346     }
347     enc_ty(w, cx, fsig.output);
348 }
349
350 pub fn enc_builtin_bounds(w: &mut SeekableMemWriter, _cx: &ctxt, bs: &ty::BuiltinBounds) {
351     for bound in bs.iter() {
352         match bound {
353             ty::BoundSend => mywrite!(w, "S"),
354             ty::BoundSized => mywrite!(w, "Z"),
355             ty::BoundCopy => mywrite!(w, "P"),
356             ty::BoundSync => mywrite!(w, "T"),
357         }
358     }
359
360     mywrite!(w, ".");
361 }
362
363 pub fn enc_existential_bounds(w: &mut SeekableMemWriter, cx: &ctxt, bs: &ty::ExistentialBounds) {
364     enc_region(w, cx, bs.region_bound);
365     enc_builtin_bounds(w, cx, &bs.builtin_bounds);
366 }
367
368 pub fn enc_bounds(w: &mut SeekableMemWriter, cx: &ctxt, bs: &ty::ParamBounds) {
369     enc_builtin_bounds(w, cx, &bs.builtin_bounds);
370
371     for &r in bs.region_bounds.iter() {
372         mywrite!(w, "R");
373         enc_region(w, cx, r);
374     }
375
376     for tp in bs.trait_bounds.iter() {
377         mywrite!(w, "I");
378         enc_trait_ref(w, cx, &**tp);
379     }
380
381     mywrite!(w, ".");
382 }
383
384 pub fn enc_type_param_def(w: &mut SeekableMemWriter, cx: &ctxt, v: &ty::TypeParameterDef) {
385     mywrite!(w, "{}:{}|{}|{}|",
386              token::get_name(v.name), (cx.ds)(v.def_id),
387              v.space.to_uint(), v.index);
388     enc_opt(w, v.associated_with, |w, did| mywrite!(w, "{}", (cx.ds)(did)));
389     mywrite!(w, "|");
390     enc_bounds(w, cx, &v.bounds);
391     enc_opt(w, v.default, |w, t| enc_ty(w, cx, t));
392 }