]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/astconv_util.rs
Rollup merge of #26800 - tshepang:comma, r=Gankro
[rust.git] / src / librustc / middle / astconv_util.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 /*!
12  * This module contains a simple utility routine
13  * used by both `typeck` and `const_eval`.
14  * Almost certainly this could (and should) be refactored out of existence.
15  */
16
17 use middle::def;
18 use middle::ty::{self, Ty};
19 use syntax::ast;
20
21 pub const NO_REGIONS: usize = 1;
22 pub const NO_TPS: usize = 2;
23
24 pub fn check_path_args(tcx: &ty::ctxt, segments: &[ast::PathSegment], flags: usize) {
25     for segment in segments {
26         if (flags & NO_TPS) != 0 {
27             for typ in segment.parameters.types() {
28                 span_err!(tcx.sess, typ.span, E0109,
29                           "type parameters are not allowed on this type");
30                 break;
31             }
32         }
33
34         if (flags & NO_REGIONS) != 0 {
35             for lifetime in segment.parameters.lifetimes() {
36                 span_err!(tcx.sess, lifetime.span, E0110,
37                           "lifetime parameters are not allowed on this type");
38                 break;
39             }
40         }
41     }
42 }
43
44 pub fn prim_ty_to_ty<'tcx>(tcx: &ty::ctxt<'tcx>,
45                            segments: &[ast::PathSegment],
46                            nty: ast::PrimTy)
47                            -> Ty<'tcx> {
48     check_path_args(tcx, segments, NO_TPS | NO_REGIONS);
49     match nty {
50         ast::TyBool => tcx.types.bool,
51         ast::TyChar => tcx.types.char,
52         ast::TyInt(it) => tcx.mk_mach_int(it),
53         ast::TyUint(uit) => tcx.mk_mach_uint(uit),
54         ast::TyFloat(ft) => tcx.mk_mach_float(ft),
55         ast::TyStr => tcx.mk_str()
56     }
57 }
58
59 pub fn ast_ty_to_prim_ty<'tcx>(tcx: &ty::ctxt<'tcx>, ast_ty: &ast::Ty)
60                                -> Option<Ty<'tcx>> {
61     if let ast::TyPath(None, ref path) = ast_ty.node {
62         let def = match tcx.def_map.borrow().get(&ast_ty.id) {
63             None => {
64                 tcx.sess.span_bug(ast_ty.span,
65                                   &format!("unbound path {:?}", path))
66             }
67             Some(d) => d.full_def()
68         };
69         if let def::DefPrimTy(nty) = def {
70             Some(prim_ty_to_ty(tcx, &path.segments, nty))
71         } else {
72             None
73         }
74     } else {
75         None
76     }
77 }