]> git.lizzy.rs Git - rust.git/blob - src/librustc/metadata/tyencode.rs
Fix misspelled comments.
[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
18 use middle::region;
19 use middle::subst;
20 use middle::subst::VecPerParamSpace;
21 use middle::ty::ParamTy;
22 use middle::ty::{self, Ty};
23 use util::nodemap::FnvHashMap;
24
25 use syntax::abi::Abi;
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(ast::DefId) -> String,
38     // The type context.
39     pub tcx: &'a ty::ctxt<'tcx>,
40     pub abbrevs: &'a abbrev_map<'tcx>
41 }
42
43 // Compact string representation for Ty 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<'tcx> = RefCell<FnvHashMap<Ty<'tcx>, ty_abbrev>>;
51
52 pub fn enc_ty<'a, 'tcx>(w: &mut SeekableMemWriter, cx: &ctxt<'a, 'tcx>, t: Ty<'tcx>) {
53     match cx.abbrevs.borrow_mut().get(&t) {
54         Some(a) => { w.write(a.s.as_bytes()); return; }
55         None => {}
56     }
57     let pos = w.tell().unwrap();
58
59     match t.sty {
60         ty::ty_bool => mywrite!(w, "b"),
61         ty::ty_char => mywrite!(w, "c"),
62         ty::ty_int(t) => {
63             match t {
64                 ast::TyI => mywrite!(w, "i"),
65                 ast::TyI8 => mywrite!(w, "MB"),
66                 ast::TyI16 => mywrite!(w, "MW"),
67                 ast::TyI32 => mywrite!(w, "ML"),
68                 ast::TyI64 => mywrite!(w, "MD")
69             }
70         }
71         ty::ty_uint(t) => {
72             match t {
73                 ast::TyU => mywrite!(w, "u"),
74                 ast::TyU8 => mywrite!(w, "Mb"),
75                 ast::TyU16 => mywrite!(w, "Mw"),
76                 ast::TyU32 => mywrite!(w, "Ml"),
77                 ast::TyU64 => mywrite!(w, "Md")
78             }
79         }
80         ty::ty_float(t) => {
81             match t {
82                 ast::TyF32 => mywrite!(w, "Mf"),
83                 ast::TyF64 => mywrite!(w, "MF"),
84             }
85         }
86         ty::ty_enum(def, substs) => {
87             mywrite!(w, "t[{}|", (cx.ds)(def));
88             enc_substs(w, cx, substs);
89             mywrite!(w, "]");
90         }
91         ty::ty_trait(box ty::TyTrait { ref principal,
92                                        ref bounds }) => {
93             mywrite!(w, "x[");
94             enc_trait_ref(w, cx, &*principal.0);
95             enc_existential_bounds(w, cx, bounds);
96             mywrite!(w, "]");
97         }
98         ty::ty_tup(ref ts) => {
99             mywrite!(w, "T[");
100             for t in ts.iter() { enc_ty(w, cx, *t); }
101             mywrite!(w, "]");
102         }
103         ty::ty_uniq(typ) => { mywrite!(w, "~"); enc_ty(w, cx, typ); }
104         ty::ty_ptr(mt) => { mywrite!(w, "*"); enc_mt(w, cx, mt); }
105         ty::ty_rptr(r, mt) => {
106             mywrite!(w, "&");
107             enc_region(w, cx, *r);
108             enc_mt(w, cx, mt);
109         }
110         ty::ty_vec(t, sz) => {
111             mywrite!(w, "V");
112             enc_ty(w, cx, t);
113             mywrite!(w, "/");
114             match sz {
115                 Some(n) => mywrite!(w, "{}|", n),
116                 None => mywrite!(w, "|"),
117             }
118         }
119         ty::ty_str => {
120             mywrite!(w, "v");
121         }
122         ty::ty_bare_fn(Some(def_id), f) => {
123             mywrite!(w, "F");
124             mywrite!(w, "{}|", (cx.ds)(def_id));
125             enc_bare_fn_ty(w, cx, f);
126         }
127         ty::ty_bare_fn(None, f) => {
128             mywrite!(w, "G");
129             enc_bare_fn_ty(w, cx, f);
130         }
131         ty::ty_infer(_) => {
132             cx.diag.handler().bug("cannot encode inference variable types");
133         }
134         ty::ty_param(ParamTy {space, idx, name}) => {
135             mywrite!(w, "p[{}|{}|{}]", idx, space.to_uint(), token::get_name(name))
136         }
137         ty::ty_struct(def, substs) => {
138             mywrite!(w, "a[{}|", (cx.ds)(def));
139             enc_substs(w, cx, substs);
140             mywrite!(w, "]");
141         }
142         ty::ty_unboxed_closure(def, region, substs) => {
143             mywrite!(w, "k[{}|", (cx.ds)(def));
144             enc_region(w, cx, *region);
145             enc_substs(w, cx, substs);
146             mywrite!(w, "]");
147         }
148         ty::ty_projection(ref data) => {
149             mywrite!(w, "P[");
150             enc_trait_ref(w, cx, &*data.trait_ref);
151             mywrite!(w, "{}]", token::get_name(data.item_name));
152         }
153         ty::ty_err => {
154             mywrite!(w, "e");
155         }
156         ty::ty_open(_) => {
157             cx.diag.handler().bug("unexpected type in enc_sty (ty_open)");
158         }
159     }
160
161     let end = w.tell().unwrap();
162     let len = end - pos;
163     fn estimate_sz(u: u64) -> u64 {
164         let mut n = u;
165         let mut len = 0;
166         while n != 0 { len += 1; n = n >> 4; }
167         return len;
168     }
169     let abbrev_len = 3 + estimate_sz(pos) + estimate_sz(len);
170     if abbrev_len < len {
171         // I.e. it's actually an abbreviation.
172         cx.abbrevs.borrow_mut().insert(t, ty_abbrev {
173             s: format!("#{:x}:{:x}#", pos, len)
174         });
175     }
176 }
177
178 fn enc_mutability(w: &mut SeekableMemWriter, mt: ast::Mutability) {
179     match mt {
180         ast::MutImmutable => (),
181         ast::MutMutable => mywrite!(w, "m"),
182     }
183 }
184
185 fn enc_mt<'a, 'tcx>(w: &mut SeekableMemWriter, cx: &ctxt<'a, 'tcx>,
186                     mt: ty::mt<'tcx>) {
187     enc_mutability(w, mt.mutbl);
188     enc_ty(w, cx, mt.ty);
189 }
190
191 fn enc_opt<T, F>(w: &mut SeekableMemWriter, t: Option<T>, enc_f: F) where
192     F: FnOnce(&mut SeekableMemWriter, T),
193 {
194     match t {
195         None => mywrite!(w, "n"),
196         Some(v) => {
197             mywrite!(w, "s");
198             enc_f(w, v);
199         }
200     }
201 }
202
203 fn enc_vec_per_param_space<'a, 'tcx, T, F>(w: &mut SeekableMemWriter,
204                                            cx: &ctxt<'a, 'tcx>,
205                                            v: &VecPerParamSpace<T>,
206                                            mut op: F) where
207     F: FnMut(&mut SeekableMemWriter, &ctxt<'a, 'tcx>, &T),
208 {
209     for &space in subst::ParamSpace::all().iter() {
210         mywrite!(w, "[");
211         for t in v.get_slice(space).iter() {
212             op(w, cx, t);
213         }
214         mywrite!(w, "]");
215     }
216 }
217
218 pub fn enc_substs<'a, 'tcx>(w: &mut SeekableMemWriter, cx: &ctxt<'a, 'tcx>,
219                             substs: &subst::Substs<'tcx>) {
220     enc_region_substs(w, cx, &substs.regions);
221     enc_vec_per_param_space(w, cx, &substs.types,
222                             |w, cx, &ty| enc_ty(w, cx, ty));
223 }
224
225 fn enc_region_substs(w: &mut SeekableMemWriter, cx: &ctxt, substs: &subst::RegionSubsts) {
226     match *substs {
227         subst::ErasedRegions => {
228             mywrite!(w, "e");
229         }
230         subst::NonerasedRegions(ref regions) => {
231             mywrite!(w, "n");
232             enc_vec_per_param_space(w, cx, regions,
233                                     |w, cx, &r| enc_region(w, cx, r));
234         }
235     }
236 }
237
238 pub fn enc_region(w: &mut SeekableMemWriter, cx: &ctxt, r: ty::Region) {
239     match r {
240         ty::ReLateBound(id, br) => {
241             mywrite!(w, "b[{}|", id.depth);
242             enc_bound_region(w, cx, br);
243             mywrite!(w, "]");
244         }
245         ty::ReEarlyBound(node_id, space, index, name) => {
246             mywrite!(w, "B[{}|{}|{}|{}]",
247                      node_id,
248                      space.to_uint(),
249                      index,
250                      token::get_name(name));
251         }
252         ty::ReFree(ref fr) => {
253             mywrite!(w, "f[");
254             enc_scope(w, cx, fr.scope);
255             mywrite!(w, "|");
256             enc_bound_region(w, cx, fr.bound_region);
257             mywrite!(w, "]");
258         }
259         ty::ReScope(scope) => {
260             mywrite!(w, "s");
261             enc_scope(w, cx, scope);
262             mywrite!(w, "|");
263         }
264         ty::ReStatic => {
265             mywrite!(w, "t");
266         }
267         ty::ReEmpty => {
268             mywrite!(w, "e");
269         }
270         ty::ReInfer(_) => {
271             // these should not crop up after typeck
272             cx.diag.handler().bug("cannot encode region variables");
273         }
274     }
275 }
276
277 fn enc_scope(w: &mut SeekableMemWriter, _cx: &ctxt, scope: region::CodeExtent) {
278     match scope {
279         region::CodeExtent::Misc(node_id) => mywrite!(w, "M{}", node_id)
280     }
281 }
282
283 fn enc_bound_region(w: &mut SeekableMemWriter, cx: &ctxt, br: ty::BoundRegion) {
284     match br {
285         ty::BrAnon(idx) => {
286             mywrite!(w, "a{}|", idx);
287         }
288         ty::BrNamed(d, name) => {
289             mywrite!(w, "[{}|{}]",
290                      (cx.ds)(d),
291                      token::get_name(name));
292         }
293         ty::BrFresh(id) => {
294             mywrite!(w, "f{}|", id);
295         }
296         ty::BrEnv => {
297             mywrite!(w, "e|");
298         }
299     }
300 }
301
302 pub fn enc_trait_ref<'a, 'tcx>(w: &mut SeekableMemWriter, cx: &ctxt<'a, 'tcx>,
303                                s: &ty::TraitRef<'tcx>) {
304     mywrite!(w, "{}|", (cx.ds)(s.def_id));
305     enc_substs(w, cx, s.substs);
306 }
307
308 pub fn enc_trait_store(w: &mut SeekableMemWriter, cx: &ctxt, s: ty::TraitStore) {
309     match s {
310         ty::UniqTraitStore => mywrite!(w, "~"),
311         ty::RegionTraitStore(re, m) => {
312             mywrite!(w, "&");
313             enc_region(w, cx, re);
314             enc_mutability(w, m);
315         }
316     }
317 }
318
319 fn enc_unsafety(w: &mut SeekableMemWriter, p: ast::Unsafety) {
320     match p {
321         ast::Unsafety::Normal => mywrite!(w, "n"),
322         ast::Unsafety::Unsafe => mywrite!(w, "u"),
323     }
324 }
325
326 fn enc_abi(w: &mut SeekableMemWriter, abi: Abi) {
327     mywrite!(w, "[");
328     mywrite!(w, "{}", abi.name());
329     mywrite!(w, "]")
330 }
331
332 fn enc_onceness(w: &mut SeekableMemWriter, o: ast::Onceness) {
333     match o {
334         ast::Once => mywrite!(w, "o"),
335         ast::Many => mywrite!(w, "m")
336     }
337 }
338
339 pub fn enc_bare_fn_ty<'a, 'tcx>(w: &mut SeekableMemWriter, cx: &ctxt<'a, 'tcx>,
340                                 ft: &ty::BareFnTy<'tcx>) {
341     enc_unsafety(w, ft.unsafety);
342     enc_abi(w, ft.abi);
343     enc_fn_sig(w, cx, &ft.sig);
344 }
345
346 pub fn enc_closure_ty<'a, 'tcx>(w: &mut SeekableMemWriter, cx: &ctxt<'a, 'tcx>,
347                                 ft: &ty::ClosureTy<'tcx>) {
348     enc_unsafety(w, ft.unsafety);
349     enc_onceness(w, ft.onceness);
350     enc_trait_store(w, cx, ft.store);
351     enc_existential_bounds(w, cx, &ft.bounds);
352     enc_fn_sig(w, cx, &ft.sig);
353     enc_abi(w, ft.abi);
354 }
355
356 fn enc_fn_sig<'a, 'tcx>(w: &mut SeekableMemWriter, cx: &ctxt<'a, 'tcx>,
357                         fsig: &ty::PolyFnSig<'tcx>) {
358     mywrite!(w, "[");
359     for ty in fsig.0.inputs.iter() {
360         enc_ty(w, cx, *ty);
361     }
362     mywrite!(w, "]");
363     if fsig.0.variadic {
364         mywrite!(w, "V");
365     } else {
366         mywrite!(w, "N");
367     }
368     match fsig.0.output {
369         ty::FnConverging(result_type) => {
370             enc_ty(w, cx, result_type);
371         }
372         ty::FnDiverging => {
373             mywrite!(w, "z");
374         }
375     }
376 }
377
378 pub fn enc_builtin_bounds(w: &mut SeekableMemWriter, _cx: &ctxt, bs: &ty::BuiltinBounds) {
379     for bound in bs.iter() {
380         match bound {
381             ty::BoundSend => mywrite!(w, "S"),
382             ty::BoundSized => mywrite!(w, "Z"),
383             ty::BoundCopy => mywrite!(w, "P"),
384             ty::BoundSync => mywrite!(w, "T"),
385         }
386     }
387
388     mywrite!(w, ".");
389 }
390
391 pub fn enc_existential_bounds<'a,'tcx>(w: &mut SeekableMemWriter,
392                                        cx: &ctxt<'a,'tcx>,
393                                        bs: &ty::ExistentialBounds<'tcx>) {
394     let param_bounds = ty::ParamBounds { trait_bounds: vec!(),
395                                          region_bounds: vec!(bs.region_bound),
396                                          builtin_bounds: bs.builtin_bounds,
397                                          projection_bounds: bs.projection_bounds.clone() };
398     enc_bounds(w, cx, &param_bounds);
399 }
400
401 pub fn enc_bounds<'a, 'tcx>(w: &mut SeekableMemWriter, cx: &ctxt<'a, 'tcx>,
402                             bs: &ty::ParamBounds<'tcx>) {
403     enc_builtin_bounds(w, cx, &bs.builtin_bounds);
404
405     for &r in bs.region_bounds.iter() {
406         mywrite!(w, "R");
407         enc_region(w, cx, r);
408     }
409
410     for tp in bs.trait_bounds.iter() {
411         mywrite!(w, "I");
412         enc_trait_ref(w, cx, &*tp.0);
413     }
414
415     for tp in bs.projection_bounds.iter() {
416         mywrite!(w, "P");
417         enc_projection_predicate(w, cx, &tp.0);
418     }
419
420     mywrite!(w, ".");
421 }
422
423 pub fn enc_type_param_def<'a, 'tcx>(w: &mut SeekableMemWriter, cx: &ctxt<'a, 'tcx>,
424                                     v: &ty::TypeParameterDef<'tcx>) {
425     mywrite!(w, "{}:{}|{}|{}|",
426              token::get_name(v.name), (cx.ds)(v.def_id),
427              v.space.to_uint(), v.index);
428     enc_bounds(w, cx, &v.bounds);
429     enc_opt(w, v.default, |w, t| enc_ty(w, cx, t));
430 }
431
432 pub fn enc_predicate<'a, 'tcx>(w: &mut SeekableMemWriter,
433                                cx: &ctxt<'a, 'tcx>,
434                                p: &ty::Predicate<'tcx>)
435 {
436     match *p {
437         ty::Predicate::Trait(ref trait_ref) => {
438             mywrite!(w, "t");
439             enc_trait_ref(w, cx, &*trait_ref.0.trait_ref);
440         }
441         ty::Predicate::Equate(ty::Binder(ty::EquatePredicate(a, b))) => {
442             mywrite!(w, "e");
443             enc_ty(w, cx, a);
444             enc_ty(w, cx, b);
445         }
446         ty::Predicate::RegionOutlives(ty::Binder(ty::OutlivesPredicate(a, b))) => {
447             mywrite!(w, "r");
448             enc_region(w, cx, a);
449             enc_region(w, cx, b);
450         }
451         ty::Predicate::TypeOutlives(ty::Binder(ty::OutlivesPredicate(a, b))) => {
452             mywrite!(w, "o");
453             enc_ty(w, cx, a);
454             enc_region(w, cx, b);
455         }
456         ty::Predicate::Projection(ty::Binder(ref data)) => {
457             mywrite!(w, "p");
458             enc_projection_predicate(w, cx, data)
459         }
460     }
461 }
462
463 fn enc_projection_predicate<'a, 'tcx>(w: &mut SeekableMemWriter,
464                                       cx: &ctxt<'a, 'tcx>,
465                                       data: &ty::ProjectionPredicate<'tcx>) {
466     enc_trait_ref(w, cx, &*data.projection_ty.trait_ref);
467     mywrite!(w, "{}|", token::get_name(data.projection_ty.item_name));
468     enc_ty(w, cx, data.ty);
469 }