]> git.lizzy.rs Git - rust.git/blob - src/librustc/metadata/tydecode.rs
011ee115e8c1521f3f6d5eb1804723dc45e155dd
[rust.git] / src / librustc / metadata / tydecode.rs
1 // Copyright 2012 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
12 // Type decoding
13
14 // tjc note: Would be great to have a `match check` macro equivalent
15 // for some of these
16
17 use middle::ty;
18
19 use syntax::abi::AbiSet;
20 use syntax::abi;
21 use syntax::ast;
22 use syntax::ast::*;
23 use syntax::codemap::dummy_sp;
24 use syntax::opt_vec;
25
26 // Compact string representation for ty::t values. API ty_str &
27 // parse_from_str. Extra parameters are for converting to/from def_ids in the
28 // data buffer. Whatever format you choose should not contain pipe characters.
29
30 // Def id conversion: when we encounter def-ids, they have to be translated.
31 // For example, the crate number must be converted from the crate number used
32 // in the library we are reading from into the local crate numbers in use
33 // here.  To perform this translation, the type decoder is supplied with a
34 // conversion function of type `conv_did`.
35 //
36 // Sometimes, particularly when inlining, the correct translation of the
37 // def-id will depend on where it originated from.  Therefore, the conversion
38 // function is given an indicator of the source of the def-id.  See
39 // astencode.rs for more information.
40 pub enum DefIdSource {
41     // Identifies a struct, trait, enum, etc.
42     NominalType,
43
44     // Identifies a type alias (`type X = ...`).
45     TypeWithId,
46
47     // Identifies a type parameter (`fn foo<X>() { ... }`).
48     TypeParameter
49 }
50 type conv_did<'self> =
51     &'self fn(source: DefIdSource, ast::def_id) -> ast::def_id;
52
53 pub struct PState {
54     data: @~[u8],
55     crate: int,
56     pos: uint,
57     tcx: ty::ctxt
58 }
59
60 fn peek(st: @mut PState) -> char {
61     st.data[st.pos] as char
62 }
63
64 fn next(st: @mut PState) -> char {
65     let ch = st.data[st.pos] as char;
66     st.pos = st.pos + 1u;
67     return ch;
68 }
69
70 fn next_byte(st: @mut PState) -> u8 {
71     let b = st.data[st.pos];
72     st.pos = st.pos + 1u;
73     return b;
74 }
75
76 fn scan<R>(st: &mut PState, is_last: &fn(char) -> bool,
77            op: &fn(&[u8]) -> R) -> R
78 {
79     let start_pos = st.pos;
80     debug!("scan: '%c' (start)", st.data[st.pos] as char);
81     while !is_last(st.data[st.pos] as char) {
82         st.pos += 1;
83         debug!("scan: '%c'", st.data[st.pos] as char);
84     }
85     let end_pos = st.pos;
86     st.pos += 1;
87     return op(st.data.slice(start_pos, end_pos));
88 }
89
90 pub fn parse_ident(st: @mut PState, last: char) -> ast::ident {
91     fn is_last(b: char, c: char) -> bool { return c == b; }
92     return parse_ident_(st, |a| is_last(last, a) );
93 }
94
95 fn parse_ident_(st: @mut PState, is_last: @fn(char) -> bool) ->
96    ast::ident {
97     let rslt = scan(st, is_last, str::from_bytes);
98     return st.tcx.sess.ident_of(rslt);
99 }
100
101 pub fn parse_state_from_data(data: @~[u8], crate_num: int,
102                              pos: uint, tcx: ty::ctxt) -> @mut PState {
103     @mut PState {
104         data: data,
105         crate: crate_num,
106         pos: pos,
107         tcx: tcx
108     }
109 }
110
111 pub fn parse_ty_data(data: @~[u8], crate_num: int, pos: uint, tcx: ty::ctxt,
112                      conv: conv_did) -> ty::t {
113     let st = parse_state_from_data(data, crate_num, pos, tcx);
114     parse_ty(st, conv)
115 }
116
117 pub fn parse_bare_fn_ty_data(data: @~[u8], crate_num: int, pos: uint, tcx: ty::ctxt,
118                              conv: conv_did) -> ty::BareFnTy {
119     let st = parse_state_from_data(data, crate_num, pos, tcx);
120     parse_bare_fn_ty(st, conv)
121 }
122
123 pub fn parse_trait_ref_data(data: @~[u8], crate_num: int, pos: uint, tcx: ty::ctxt,
124                             conv: conv_did) -> ty::TraitRef {
125     let st = parse_state_from_data(data, crate_num, pos, tcx);
126     parse_trait_ref(st, conv)
127 }
128
129 pub fn parse_arg_data(data: @~[u8], crate_num: int, pos: uint, tcx: ty::ctxt,
130                       conv: conv_did) -> ty::arg {
131     let st = parse_state_from_data(data, crate_num, pos, tcx);
132     parse_arg(st, conv)
133 }
134
135 fn parse_path(st: @mut PState) -> @ast::Path {
136     let mut idents: ~[ast::ident] = ~[];
137     fn is_last(c: char) -> bool { return c == '(' || c == ':'; }
138     idents.push(parse_ident_(st, is_last));
139     loop {
140         match peek(st) {
141           ':' => { next(st); next(st); }
142           c => {
143             if c == '(' {
144                 return @ast::Path { span: dummy_sp(),
145                                     global: false,
146                                     idents: idents,
147                                     rp: None,
148                                     types: ~[] };
149             } else { idents.push(parse_ident_(st, is_last)); }
150           }
151         }
152     };
153 }
154
155 fn parse_sigil(st: @mut PState) -> ast::Sigil {
156     match next(st) {
157         '@' => ast::ManagedSigil,
158         '~' => ast::OwnedSigil,
159         '&' => ast::BorrowedSigil,
160         c => st.tcx.sess.bug(fmt!("parse_sigil(): bad input '%c'", c))
161     }
162 }
163
164 fn parse_vstore(st: @mut PState) -> ty::vstore {
165     assert!(next(st) == '/');
166
167     let c = peek(st);
168     if '0' <= c && c <= '9' {
169         let n = parse_uint(st);
170         assert!(next(st) == '|');
171         return ty::vstore_fixed(n);
172     }
173
174     match next(st) {
175       '~' => ty::vstore_uniq,
176       '@' => ty::vstore_box,
177       '&' => ty::vstore_slice(parse_region(st)),
178       c => st.tcx.sess.bug(fmt!("parse_vstore(): bad input '%c'", c))
179     }
180 }
181
182 fn parse_trait_store(st: @mut PState) -> ty::TraitStore {
183     match next(st) {
184         '~' => ty::UniqTraitStore,
185         '@' => ty::BoxTraitStore,
186         '&' => ty::RegionTraitStore(parse_region(st)),
187         c => st.tcx.sess.bug(fmt!("parse_trait_store(): bad input '%c'", c))
188     }
189 }
190
191 fn parse_substs(st: @mut PState, conv: conv_did) -> ty::substs {
192     let self_r = parse_opt(st, || parse_region(st) );
193
194     let self_ty = parse_opt(st, || parse_ty(st, conv) );
195
196     assert!(next(st) == '[');
197     let mut params: ~[ty::t] = ~[];
198     while peek(st) != ']' { params.push(parse_ty(st, conv)); }
199     st.pos = st.pos + 1u;
200
201     return ty::substs {
202         self_r: self_r,
203         self_ty: self_ty,
204         tps: params
205     };
206 }
207
208 fn parse_bound_region(st: @mut PState) -> ty::bound_region {
209     match next(st) {
210       's' => ty::br_self,
211       'a' => {
212         let id = parse_uint(st);
213         assert!(next(st) == '|');
214         ty::br_anon(id)
215       }
216       '[' => ty::br_named(st.tcx.sess.ident_of(parse_str(st, ']'))),
217       'c' => {
218         let id = parse_uint(st) as int;
219         assert!(next(st) == '|');
220         ty::br_cap_avoid(id, @parse_bound_region(st))
221       },
222       _ => fail!(~"parse_bound_region: bad input")
223     }
224 }
225
226 fn parse_region(st: @mut PState) -> ty::Region {
227     match next(st) {
228       'b' => {
229         ty::re_bound(parse_bound_region(st))
230       }
231       'f' => {
232         assert!(next(st) == '[');
233         let id = parse_uint(st) as int;
234         assert!(next(st) == '|');
235         let br = parse_bound_region(st);
236         assert!(next(st) == ']');
237         ty::re_free(ty::FreeRegion {scope_id: id,
238                                     bound_region: br})
239       }
240       's' => {
241         let id = parse_uint(st) as int;
242         assert!(next(st) == '|');
243         ty::re_scope(id)
244       }
245       't' => {
246         ty::re_static
247       }
248       _ => fail!(~"parse_region: bad input")
249     }
250 }
251
252 fn parse_opt<T>(st: @mut PState, f: &fn() -> T) -> Option<T> {
253     match next(st) {
254       'n' => None,
255       's' => Some(f()),
256       _ => fail!(~"parse_opt: bad input")
257     }
258 }
259
260 fn parse_str(st: @mut PState, term: char) -> ~str {
261     let mut result = ~"";
262     while peek(st) != term {
263         result += str::from_byte(next_byte(st));
264     }
265     next(st);
266     return result;
267 }
268
269 fn parse_trait_ref(st: @mut PState, conv: conv_did) -> ty::TraitRef {
270     let def = parse_def(st, NominalType, conv);
271     let substs = parse_substs(st, conv);
272     ty::TraitRef {def_id: def, substs: substs}
273 }
274
275 fn parse_ty(st: @mut PState, conv: conv_did) -> ty::t {
276     match next(st) {
277       'n' => return ty::mk_nil(),
278       'z' => return ty::mk_bot(),
279       'b' => return ty::mk_bool(),
280       'i' => return ty::mk_int(),
281       'u' => return ty::mk_uint(),
282       'l' => return ty::mk_float(),
283       'M' => {
284         match next(st) {
285           'b' => return ty::mk_mach_uint(ast::ty_u8),
286           'w' => return ty::mk_mach_uint(ast::ty_u16),
287           'l' => return ty::mk_mach_uint(ast::ty_u32),
288           'd' => return ty::mk_mach_uint(ast::ty_u64),
289           'B' => return ty::mk_mach_int(ast::ty_i8),
290           'W' => return ty::mk_mach_int(ast::ty_i16),
291           'L' => return ty::mk_mach_int(ast::ty_i32),
292           'D' => return ty::mk_mach_int(ast::ty_i64),
293           'f' => return ty::mk_mach_float(ast::ty_f32),
294           'F' => return ty::mk_mach_float(ast::ty_f64),
295           _ => fail!(~"parse_ty: bad numeric type")
296         }
297       }
298       'c' => return ty::mk_char(),
299       't' => {
300         assert!((next(st) == '['));
301         let def = parse_def(st, NominalType, conv);
302         let substs = parse_substs(st, conv);
303         assert!(next(st) == ']');
304         return ty::mk_enum(st.tcx, def, substs);
305       }
306       'x' => {
307         assert!(next(st) == '[');
308         let def = parse_def(st, NominalType, conv);
309         let substs = parse_substs(st, conv);
310         let store = parse_trait_store(st);
311         let mt = parse_mutability(st);
312         assert!(next(st) == ']');
313         return ty::mk_trait(st.tcx, def, substs, store, mt);
314       }
315       'p' => {
316         let did = parse_def(st, TypeParameter, conv);
317         debug!("parsed ty_param: did=%?", did);
318         return ty::mk_param(st.tcx, parse_uint(st), did);
319       }
320       's' => {
321         let did = parse_def(st, TypeParameter, conv);
322         return ty::mk_self(st.tcx, did);
323       }
324       '@' => return ty::mk_box(st.tcx, parse_mt(st, conv)),
325       '~' => return ty::mk_uniq(st.tcx, parse_mt(st, conv)),
326       '*' => return ty::mk_ptr(st.tcx, parse_mt(st, conv)),
327       '&' => {
328         let r = parse_region(st);
329         let mt = parse_mt(st, conv);
330         return ty::mk_rptr(st.tcx, r, mt);
331       }
332       'U' => return ty::mk_unboxed_vec(st.tcx, parse_mt(st, conv)),
333       'V' => {
334         let mt = parse_mt(st, conv);
335         let v = parse_vstore(st);
336         return ty::mk_evec(st.tcx, mt, v);
337       }
338       'v' => {
339         let v = parse_vstore(st);
340         return ty::mk_estr(st.tcx, v);
341       }
342       'T' => {
343         assert!((next(st) == '['));
344         let mut params = ~[];
345         while peek(st) != ']' { params.push(parse_ty(st, conv)); }
346         st.pos = st.pos + 1u;
347         return ty::mk_tup(st.tcx, params);
348       }
349       'f' => {
350         return ty::mk_closure(st.tcx, parse_closure_ty(st, conv));
351       }
352       'F' => {
353         return ty::mk_bare_fn(st.tcx, parse_bare_fn_ty(st, conv));
354       }
355       'Y' => return ty::mk_type(st.tcx),
356       'C' => {
357         let sigil = parse_sigil(st);
358         return ty::mk_opaque_closure_ptr(st.tcx, sigil);
359       }
360       '#' => {
361         let pos = parse_hex(st);
362         assert!((next(st) == ':'));
363         let len = parse_hex(st);
364         assert!((next(st) == '#'));
365         let key = ty::creader_cache_key {cnum: st.crate,
366                                          pos: pos,
367                                          len: len };
368         match st.tcx.rcache.find(&key) {
369           Some(&tt) => return tt,
370           None => {
371             let ps = @mut PState {pos: pos ,.. copy *st};
372             let tt = parse_ty(ps, conv);
373             st.tcx.rcache.insert(key, tt);
374             return tt;
375           }
376         }
377       }
378       '"' => {
379         let _ = parse_def(st, TypeWithId, conv);
380         let inner = parse_ty(st, conv);
381         inner
382       }
383       'B' => ty::mk_opaque_box(st.tcx),
384       'a' => {
385           assert!((next(st) == '['));
386           let did = parse_def(st, NominalType, conv);
387           let substs = parse_substs(st, conv);
388           assert!((next(st) == ']'));
389           return ty::mk_struct(st.tcx, did, substs);
390       }
391       c => { error!("unexpected char in type string: %c", c); fail!();}
392     }
393 }
394
395 fn parse_mutability(st: @mut PState) -> ast::mutability {
396     match peek(st) {
397       'm' => { next(st); ast::m_mutbl }
398       '?' => { next(st); ast::m_const }
399       _ => { ast::m_imm }
400     }
401 }
402
403 fn parse_mt(st: @mut PState, conv: conv_did) -> ty::mt {
404     let m = parse_mutability(st);
405     ty::mt { ty: parse_ty(st, conv), mutbl: m }
406 }
407
408 fn parse_def(st: @mut PState, source: DefIdSource,
409              conv: conv_did) -> ast::def_id {
410     let mut def = ~[];
411     while peek(st) != '|' { def.push(next_byte(st)); }
412     st.pos = st.pos + 1u;
413     return conv(source, parse_def_id(def));
414 }
415
416 fn parse_uint(st: @mut PState) -> uint {
417     let mut n = 0;
418     loop {
419         let cur = peek(st);
420         if cur < '0' || cur > '9' { return n; }
421         st.pos = st.pos + 1u;
422         n *= 10;
423         n += (cur as uint) - ('0' as uint);
424     };
425 }
426
427 fn parse_hex(st: @mut PState) -> uint {
428     let mut n = 0u;
429     loop {
430         let cur = peek(st);
431         if (cur < '0' || cur > '9') && (cur < 'a' || cur > 'f') { return n; }
432         st.pos = st.pos + 1u;
433         n *= 16u;
434         if '0' <= cur && cur <= '9' {
435             n += (cur as uint) - ('0' as uint);
436         } else { n += 10u + (cur as uint) - ('a' as uint); }
437     };
438 }
439
440 fn parse_purity(c: char) -> purity {
441     match c {
442       'u' => unsafe_fn,
443       'p' => pure_fn,
444       'i' => impure_fn,
445       'c' => extern_fn,
446       _ => fail!(~"parse_purity: bad purity")
447     }
448 }
449
450 fn parse_abi_set(st: @mut PState) -> AbiSet {
451     assert!(next(st) == '[');
452     let mut abis = AbiSet::empty();
453     while peek(st) != ']' {
454         // FIXME(#5422) str API should not force this copy
455         let abi_str = scan(st, |c| c == ',', str::from_bytes);
456         let abi = abi::lookup(abi_str).expect(abi_str);
457         abis.add(abi);
458     }
459     assert!(next(st) == ']');
460     return abis;
461 }
462
463 fn parse_onceness(c: char) -> ast::Onceness {
464     match c {
465         'o' => ast::Once,
466         'm' => ast::Many,
467         _ => fail!(~"parse_onceness: bad onceness")
468     }
469 }
470
471 fn parse_arg(st: @mut PState, conv: conv_did) -> ty::arg {
472     ty::arg {
473         ty: parse_ty(st, conv)
474     }
475 }
476
477 fn parse_closure_ty(st: @mut PState, conv: conv_did) -> ty::ClosureTy {
478     let sigil = parse_sigil(st);
479     let purity = parse_purity(next(st));
480     let onceness = parse_onceness(next(st));
481     let region = parse_region(st);
482     let sig = parse_sig(st, conv);
483     ty::ClosureTy {
484         purity: purity,
485         sigil: sigil,
486         onceness: onceness,
487         region: region,
488         sig: sig
489     }
490 }
491
492 fn parse_bare_fn_ty(st: @mut PState, conv: conv_did) -> ty::BareFnTy {
493     let purity = parse_purity(next(st));
494     let abi = parse_abi_set(st);
495     let sig = parse_sig(st, conv);
496     ty::BareFnTy {
497         purity: purity,
498         abis: abi,
499         sig: sig
500     }
501 }
502
503 fn parse_sig(st: @mut PState, conv: conv_did) -> ty::FnSig {
504     assert!((next(st) == '['));
505     let mut inputs: ~[ty::arg] = ~[];
506     while peek(st) != ']' {
507         inputs.push(ty::arg { ty: parse_ty(st, conv) });
508     }
509     st.pos += 1u; // eat the ']'
510     let ret_ty = parse_ty(st, conv);
511     ty::FnSig {bound_lifetime_names: opt_vec::Empty, // FIXME(#4846)
512                inputs: inputs,
513                output: ret_ty}
514 }
515
516 // Rust metadata parsing
517 pub fn parse_def_id(buf: &[u8]) -> ast::def_id {
518     let mut colon_idx = 0u;
519     let len = vec::len(buf);
520     while colon_idx < len && buf[colon_idx] != ':' as u8 { colon_idx += 1u; }
521     if colon_idx == len {
522         error!("didn't find ':' when parsing def id");
523         fail!();
524     }
525
526     let crate_part = vec::slice(buf, 0u, colon_idx);
527     let def_part = vec::slice(buf, colon_idx + 1u, len);
528
529     let crate_num = match uint::parse_bytes(crate_part, 10u) {
530        Some(cn) => cn as int,
531        None => fail!(fmt!("internal error: parse_def_id: crate number \
532                                expected, but found %?", crate_part))
533     };
534     let def_num = match uint::parse_bytes(def_part, 10u) {
535        Some(dn) => dn as int,
536        None => fail!(fmt!("internal error: parse_def_id: id expected, but \
537                                found %?", def_part))
538     };
539     ast::def_id { crate: crate_num, node: def_num }
540 }
541
542 pub fn parse_type_param_def_data(data: @~[u8], start: uint,
543                                  crate_num: int, tcx: ty::ctxt,
544                                  conv: conv_did) -> ty::TypeParameterDef
545 {
546     let st = parse_state_from_data(data, crate_num, start, tcx);
547     parse_type_param_def(st, conv)
548 }
549
550 fn parse_type_param_def(st: @mut PState, conv: conv_did) -> ty::TypeParameterDef {
551     ty::TypeParameterDef {def_id: parse_def(st, NominalType, conv),
552                           bounds: parse_bounds(st, conv)}
553 }
554
555 fn parse_bounds(st: @mut PState, conv: conv_did) -> @~[ty::param_bound] {
556     let mut bounds = ~[];
557     loop {
558         bounds.push(match next(st) {
559           'S' => ty::bound_owned,
560           'C' => ty::bound_copy,
561           'K' => ty::bound_const,
562           'O' => ty::bound_durable,
563           'I' => ty::bound_trait(@parse_trait_ref(st, conv)),
564           '.' => break,
565           _ => fail!(~"parse_bounds: bad bounds")
566         });
567     }
568     @bounds
569 }
570
571 //
572 // Local Variables:
573 // mode: rust
574 // fill-column: 78;
575 // indent-tabs-mode: nil
576 // c-basic-offset: 4
577 // buffer-file-coding-system: utf-8-unix
578 // End:
579 //