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.
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.
14 // tjc note: Would be great to have a `match check` macro equivalent
19 use syntax::abi::AbiSet;
23 use syntax::codemap::dummy_sp;
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.
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`.
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.
44 // Identifies a type alias (`type X = ...`).
47 // Identifies a type parameter (`fn foo<X>() { ... }`).
50 type conv_did<'self> =
51 &'self fn(source: DefIdSource, ast::def_id) -> ast::def_id;
60 fn peek(st: @mut PState) -> char {
61 st.data[st.pos] as char
64 fn next(st: @mut PState) -> char {
65 let ch = st.data[st.pos] as char;
70 fn next_byte(st: @mut PState) -> u8 {
71 let b = st.data[st.pos];
76 fn scan<R>(st: &mut PState, is_last: &fn(char) -> bool,
77 op: &fn(&[u8]) -> R) -> R
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) {
83 debug!("scan: '%c'", st.data[st.pos] as char);
87 return op(st.data.slice(start_pos, end_pos));
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) );
95 fn parse_ident_(st: @mut PState, is_last: @fn(char) -> bool) ->
97 let rslt = scan(st, is_last, str::from_bytes);
98 return st.tcx.sess.ident_of(rslt);
101 pub fn parse_state_from_data(data: @~[u8], crate_num: int,
102 pos: uint, tcx: ty::ctxt) -> @mut PState {
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);
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)
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)
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);
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));
141 ':' => { next(st); next(st); }
144 return @ast::Path { span: dummy_sp(),
149 } else { idents.push(parse_ident_(st, is_last)); }
155 fn parse_sigil(st: @mut PState) -> ast::Sigil {
157 '@' => ast::ManagedSigil,
158 '~' => ast::OwnedSigil,
159 '&' => ast::BorrowedSigil,
160 c => st.tcx.sess.bug(fmt!("parse_sigil(): bad input '%c'", c))
164 fn parse_vstore(st: @mut PState) -> ty::vstore {
165 assert!(next(st) == '/');
168 if '0' <= c && c <= '9' {
169 let n = parse_uint(st);
170 assert!(next(st) == '|');
171 return ty::vstore_fixed(n);
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))
182 fn parse_trait_store(st: @mut PState) -> ty::TraitStore {
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))
191 fn parse_substs(st: @mut PState, conv: conv_did) -> ty::substs {
192 let self_r = parse_opt(st, || parse_region(st) );
194 let self_ty = parse_opt(st, || parse_ty(st, conv) );
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;
208 fn parse_bound_region(st: @mut PState) -> ty::bound_region {
212 let id = parse_uint(st);
213 assert!(next(st) == '|');
216 '[' => ty::br_named(st.tcx.sess.ident_of(parse_str(st, ']'))),
218 let id = parse_uint(st) as int;
219 assert!(next(st) == '|');
220 ty::br_cap_avoid(id, @parse_bound_region(st))
222 _ => fail!(~"parse_bound_region: bad input")
226 fn parse_region(st: @mut PState) -> ty::Region {
229 ty::re_bound(parse_bound_region(st))
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,
241 let id = parse_uint(st) as int;
242 assert!(next(st) == '|');
248 _ => fail!(~"parse_region: bad input")
252 fn parse_opt<T>(st: @mut PState, f: &fn() -> T) -> Option<T> {
256 _ => fail!(~"parse_opt: bad input")
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));
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}
275 fn parse_ty(st: @mut PState, conv: conv_did) -> ty::t {
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(),
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")
298 'c' => return ty::mk_char(),
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);
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);
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);
321 let did = parse_def(st, TypeParameter, conv);
322 return ty::mk_self(st.tcx, did);
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)),
328 let r = parse_region(st);
329 let mt = parse_mt(st, conv);
330 return ty::mk_rptr(st.tcx, r, mt);
332 'U' => return ty::mk_unboxed_vec(st.tcx, parse_mt(st, conv)),
334 let mt = parse_mt(st, conv);
335 let v = parse_vstore(st);
336 return ty::mk_evec(st.tcx, mt, v);
339 let v = parse_vstore(st);
340 return ty::mk_estr(st.tcx, v);
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);
350 return ty::mk_closure(st.tcx, parse_closure_ty(st, conv));
353 return ty::mk_bare_fn(st.tcx, parse_bare_fn_ty(st, conv));
355 'Y' => return ty::mk_type(st.tcx),
357 let sigil = parse_sigil(st);
358 return ty::mk_opaque_closure_ptr(st.tcx, sigil);
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,
368 match st.tcx.rcache.find(&key) {
369 Some(&tt) => return tt,
371 let ps = @mut PState {pos: pos ,.. copy *st};
372 let tt = parse_ty(ps, conv);
373 st.tcx.rcache.insert(key, tt);
379 let _ = parse_def(st, TypeWithId, conv);
380 let inner = parse_ty(st, conv);
383 'B' => ty::mk_opaque_box(st.tcx),
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);
391 c => { error!("unexpected char in type string: %c", c); fail!();}
395 fn parse_mutability(st: @mut PState) -> ast::mutability {
397 'm' => { next(st); ast::m_mutbl }
398 '?' => { next(st); ast::m_const }
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 }
408 fn parse_def(st: @mut PState, source: DefIdSource,
409 conv: conv_did) -> ast::def_id {
411 while peek(st) != '|' { def.push(next_byte(st)); }
412 st.pos = st.pos + 1u;
413 return conv(source, parse_def_id(def));
416 fn parse_uint(st: @mut PState) -> uint {
420 if cur < '0' || cur > '9' { return n; }
421 st.pos = st.pos + 1u;
423 n += (cur as uint) - ('0' as uint);
427 fn parse_hex(st: @mut PState) -> uint {
431 if (cur < '0' || cur > '9') && (cur < 'a' || cur > 'f') { return n; }
432 st.pos = st.pos + 1u;
434 if '0' <= cur && cur <= '9' {
435 n += (cur as uint) - ('0' as uint);
436 } else { n += 10u + (cur as uint) - ('a' as uint); }
440 fn parse_purity(c: char) -> purity {
446 _ => fail!(~"parse_purity: bad purity")
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);
459 assert!(next(st) == ']');
463 fn parse_onceness(c: char) -> ast::Onceness {
467 _ => fail!(~"parse_onceness: bad onceness")
471 fn parse_arg(st: @mut PState, conv: conv_did) -> ty::arg {
473 ty: parse_ty(st, conv)
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);
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);
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) });
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)
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");
526 let crate_part = vec::slice(buf, 0u, colon_idx);
527 let def_part = vec::slice(buf, colon_idx + 1u, len);
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))
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))
539 ast::def_id { crate: crate_num, node: def_num }
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
546 let st = parse_state_from_data(data, crate_num, start, tcx);
547 parse_type_param_def(st, conv)
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)}
555 fn parse_bounds(st: @mut PState, conv: conv_did) -> @~[ty::param_bound] {
556 let mut bounds = ~[];
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)),
565 _ => fail!(~"parse_bounds: bad bounds")
575 // indent-tabs-mode: nil
577 // buffer-file-coding-system: utf-8-unix