]> git.lizzy.rs Git - rust.git/blob - src/libhexfloat/lib.rs
e65b84091e5f915e44baec16a0b35510efeb87eb
[rust.git] / src / libhexfloat / lib.rs
1 // Copyright 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 Syntax extension to create floating point literals from hexadecimal strings
13
14 Once loaded, hexfloat!() is called with a string containing the hexadecimal
15 floating-point literal, and an optional type (f32 or f64).
16 If the type is omitted, the literal is treated the same as a normal unsuffixed
17 literal.
18
19 # Examples
20
21 To load the extension and use it:
22
23 ```rust,ignore
24 #[phase(syntax)]
25 extern crate hexfloat;
26
27 fn main() {
28     let val = hexfloat!("0x1.ffffb4", f32);
29 }
30  ```
31
32 # References
33
34 * [ExploringBinary: hexadecimal floating point constants]
35   (http://www.exploringbinary.com/hexadecimal-floating-point-constants/)
36
37 */
38
39 #![crate_id = "hexfloat#0.11-pre"]
40 #![crate_type = "rlib"]
41 #![crate_type = "dylib"]
42 #![license = "MIT/ASL2"]
43 #![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
44        html_favicon_url = "http://www.rust-lang.org/favicon.ico",
45        html_root_url = "http://static.rust-lang.org/doc/master")]
46
47 #![deny(deprecated_owned_vector)]
48 #![feature(macro_registrar, managed_boxes)]
49
50 extern crate syntax;
51
52 use syntax::ast;
53 use syntax::ast::Name;
54 use syntax::codemap::{Span, mk_sp};
55 use syntax::ext::base;
56 use syntax::ext::base::{SyntaxExtension, BasicMacroExpander, NormalTT, ExtCtxt, MacExpr};
57 use syntax::ext::build::AstBuilder;
58 use syntax::parse;
59 use syntax::parse::token;
60
61 #[macro_registrar]
62 pub fn macro_registrar(register: |Name, SyntaxExtension|) {
63     register(token::intern("hexfloat"),
64         NormalTT(~BasicMacroExpander {
65             expander: expand_syntax_ext,
66             span: None,
67         },
68         None));
69 }
70
71 //Check if the literal is valid (as LLVM expects),
72 //and return a descriptive error if not.
73 fn hex_float_lit_err(s: &str) -> Option<(uint, ~str)> {
74     let mut chars = s.chars().peekable();
75     let mut i = 0;
76     if chars.peek() == Some(&'-') { chars.next(); i+= 1 }
77     if chars.next() != Some('0') { return Some((i, ~"Expected '0'")); } i+=1;
78     if chars.next() != Some('x') { return Some((i, ~"Expected 'x'")); } i+=1;
79     let mut d_len = 0;
80     for _ in chars.take_while(|c| c.is_digit_radix(16)) { chars.next(); i+=1; d_len += 1;}
81     if chars.next() != Some('.') { return Some((i, ~"Expected '.'")); } i+=1;
82     let mut f_len = 0;
83     for _ in chars.take_while(|c| c.is_digit_radix(16)) { chars.next(); i+=1; f_len += 1;}
84     if d_len == 0 && f_len == 0 {
85         return Some((i, ~"Expected digits before or after decimal point"));
86     }
87     if chars.next() != Some('p') { return Some((i, ~"Expected 'p'")); } i+=1;
88     if chars.peek() == Some(&'-') { chars.next(); i+= 1 }
89     let mut e_len = 0;
90     for _ in chars.take_while(|c| c.is_digit()) { chars.next(); i+=1; e_len += 1}
91     if e_len == 0 {
92         return Some((i, ~"Expected exponent digits"));
93     }
94     match chars.next() {
95         None => None,
96         Some(_) => Some((i, ~"Expected end of string"))
97     }
98 }
99
100 pub fn expand_syntax_ext(cx: &mut ExtCtxt, sp: Span, tts: &[ast::TokenTree]) -> ~base::MacResult {
101     let (expr, ty_lit) = parse_tts(cx, tts);
102
103     let ty = match ty_lit {
104         None => None,
105         Some(Ident{ident, span}) => match token::get_ident(ident).get() {
106             "f32" => Some(ast::TyF32),
107             "f64" => Some(ast::TyF64),
108             _ => {
109                 cx.span_err(span, "invalid floating point type in hexfloat!");
110                 None
111             }
112         }
113     };
114
115     let s = match expr.node {
116         // expression is a literal
117         ast::ExprLit(lit) => match lit.node {
118             // string literal
119             ast::LitStr(ref s, _) => {
120                 s.clone()
121             }
122             _ => {
123                 cx.span_err(expr.span, "unsupported literal in hexfloat!");
124                 return base::DummyResult::expr(sp);
125             }
126         },
127         _ => {
128             cx.span_err(expr.span, "non-literal in hexfloat!");
129             return base::DummyResult::expr(sp);
130         }
131     };
132
133     {
134         let err = hex_float_lit_err(s.get());
135         match err {
136             Some((err_pos, err_str)) => {
137                 let pos = expr.span.lo + syntax::codemap::Pos::from_uint(err_pos + 1);
138                 let span = syntax::codemap::mk_sp(pos,pos);
139                 cx.span_err(span, format!("invalid hex float literal in hexfloat!: {}", err_str));
140                 return base::DummyResult::expr(sp);
141             }
142             _ => ()
143         }
144     }
145
146     let lit = match ty {
147         None => ast::LitFloatUnsuffixed(s),
148         Some (ty) => ast::LitFloat(s, ty)
149     };
150     MacExpr::new(cx.expr_lit(sp, lit))
151 }
152
153 struct Ident {
154     ident: ast::Ident,
155     span: Span
156 }
157
158 fn parse_tts(cx: &ExtCtxt, tts: &[ast::TokenTree]) -> (@ast::Expr, Option<Ident>) {
159     let p = &mut parse::new_parser_from_tts(cx.parse_sess(),
160                                             cx.cfg(),
161                                             tts.iter()
162                                                .map(|x| (*x).clone())
163                                                .collect());
164     let ex = p.parse_expr();
165     let id = if p.token == token::EOF {
166         None
167     } else {
168         p.expect(&token::COMMA);
169         let lo = p.span.lo;
170         let ident = p.parse_ident();
171         let hi = p.last_span.hi;
172         Some(Ident{ident: ident, span: mk_sp(lo, hi)})
173     };
174     if p.token != token::EOF {
175         p.unexpected();
176     }
177     (ex, id)
178 }
179
180 // FIXME (10872): This is required to prevent an LLVM assert on Windows
181 #[test]
182 fn dummy_test() { }