]> git.lizzy.rs Git - rust.git/blob - src/librustc/metadata/tyencode.rs
auto merge of #15638 : blake2-ppc/rust/ptr-arithmetic-chars, 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_slice(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             }
225         }
226         ty::ty_enum(def, ref substs) => {
227             mywrite!(w, "t[{}|", (cx.ds)(def));
228             enc_substs(w, cx, substs);
229             mywrite!(w, "]");
230         }
231         ty::ty_trait(box ty::TyTrait {
232                 def_id,
233                 ref substs,
234                 bounds
235             }) => {
236             mywrite!(w, "x[{}|", (cx.ds)(def_id));
237             enc_substs(w, cx, substs);
238             let bounds = ty::ParamBounds {builtin_bounds: bounds,
239                                           trait_bounds: Vec::new()};
240             enc_bounds(w, cx, &bounds);
241             mywrite!(w, "]");
242         }
243         ty::ty_tup(ref ts) => {
244             mywrite!(w, "T[");
245             for t in ts.iter() { enc_ty(w, cx, *t); }
246             mywrite!(w, "]");
247         }
248         ty::ty_box(typ) => { mywrite!(w, "@"); enc_ty(w, cx, typ); }
249         ty::ty_uniq(typ) => { mywrite!(w, "~"); enc_ty(w, cx, typ); }
250         ty::ty_ptr(mt) => { mywrite!(w, "*"); enc_mt(w, cx, mt); }
251         ty::ty_rptr(r, mt) => {
252             mywrite!(w, "&");
253             enc_region(w, cx, r);
254             enc_mt(w, cx, mt);
255         }
256         ty::ty_vec(mt, sz) => {
257             mywrite!(w, "V");
258             enc_mt(w, cx, mt);
259             mywrite!(w, "/");
260             match sz {
261                 Some(n) => mywrite!(w, "{}|", n),
262                 None => mywrite!(w, "|"),
263             }
264         }
265         ty::ty_str => {
266             mywrite!(w, "v");
267         }
268         ty::ty_closure(ref f) => {
269             mywrite!(w, "f");
270             enc_closure_ty(w, cx, &**f);
271         }
272         ty::ty_bare_fn(ref f) => {
273             mywrite!(w, "F");
274             enc_bare_fn_ty(w, cx, f);
275         }
276         ty::ty_infer(_) => {
277             cx.diag.handler().bug("cannot encode inference variable types");
278         }
279         ty::ty_param(ParamTy {space, idx: id, def_id: did}) => {
280             mywrite!(w, "p{}|{}|{}|", (cx.ds)(did), id, space.to_uint())
281         }
282         ty::ty_struct(def, ref substs) => {
283             mywrite!(w, "a[{}|", (cx.ds)(def));
284             enc_substs(w, cx, substs);
285             mywrite!(w, "]");
286         }
287         ty::ty_unboxed_closure(def) => {
288             mywrite!(w, "k{}", (cx.ds)(def));
289         }
290         ty::ty_err => {
291             mywrite!(w, "e");
292         }
293     }
294 }
295
296 fn enc_fn_style(w: &mut MemWriter, p: FnStyle) {
297     match p {
298         NormalFn => mywrite!(w, "n"),
299         UnsafeFn => mywrite!(w, "u"),
300     }
301 }
302
303 fn enc_abi(w: &mut MemWriter, abi: Abi) {
304     mywrite!(w, "[");
305     mywrite!(w, "{}", abi.name());
306     mywrite!(w, "]")
307 }
308
309 fn enc_onceness(w: &mut MemWriter, o: Onceness) {
310     match o {
311         Once => mywrite!(w, "o"),
312         Many => mywrite!(w, "m")
313     }
314 }
315
316 pub fn enc_bare_fn_ty(w: &mut MemWriter, cx: &ctxt, ft: &ty::BareFnTy) {
317     enc_fn_style(w, ft.fn_style);
318     enc_abi(w, ft.abi);
319     enc_fn_sig(w, cx, &ft.sig);
320 }
321
322 pub fn enc_closure_ty(w: &mut MemWriter, cx: &ctxt, ft: &ty::ClosureTy) {
323     enc_fn_style(w, ft.fn_style);
324     enc_onceness(w, ft.onceness);
325     enc_trait_store(w, cx, ft.store);
326     let bounds = ty::ParamBounds {builtin_bounds: ft.bounds,
327                                   trait_bounds: Vec::new()};
328     enc_bounds(w, cx, &bounds);
329     enc_fn_sig(w, cx, &ft.sig);
330     enc_abi(w, ft.abi);
331 }
332
333 fn enc_fn_sig(w: &mut MemWriter, cx: &ctxt, fsig: &ty::FnSig) {
334     mywrite!(w, "[{}|", fsig.binder_id);
335     for ty in fsig.inputs.iter() {
336         enc_ty(w, cx, *ty);
337     }
338     mywrite!(w, "]");
339     if fsig.variadic {
340         mywrite!(w, "V");
341     } else {
342         mywrite!(w, "N");
343     }
344     enc_ty(w, cx, fsig.output);
345 }
346
347 fn enc_bounds(w: &mut MemWriter, cx: &ctxt, bs: &ty::ParamBounds) {
348     for bound in bs.builtin_bounds.iter() {
349         match bound {
350             ty::BoundSend => mywrite!(w, "S"),
351             ty::BoundStatic => mywrite!(w, "O"),
352             ty::BoundSized => mywrite!(w, "Z"),
353             ty::BoundCopy => mywrite!(w, "P"),
354             ty::BoundShare => mywrite!(w, "T"),
355         }
356     }
357
358     for tp in bs.trait_bounds.iter() {
359         mywrite!(w, "I");
360         enc_trait_ref(w, cx, &**tp);
361     }
362
363     mywrite!(w, ".");
364 }
365
366 pub fn enc_type_param_def(w: &mut MemWriter, cx: &ctxt, v: &ty::TypeParameterDef) {
367     mywrite!(w, "{}:{}|{}|{}|",
368              token::get_ident(v.ident), (cx.ds)(v.def_id),
369              v.space.to_uint(), v.index);
370     enc_bounds(w, cx, &*v.bounds);
371     enc_opt(w, v.default, |w, t| enc_ty(w, cx, t));
372 }