]> git.lizzy.rs Git - rust.git/blob - src/libhexfloat/lib.rs
f0f05baa28293e84f1555b6ea6b7292d735a68cb
[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(plugin)]
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.0-pre"]
40 #![experimental]
41 #![crate_type = "rlib"]
42 #![crate_type = "dylib"]
43 #![license = "MIT/ASL2"]
44 #![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
45        html_favicon_url = "http://www.rust-lang.org/favicon.ico",
46        html_root_url = "http://doc.rust-lang.org/")]
47 #![feature(plugin_registrar, managed_boxes)]
48
49 extern crate syntax;
50 extern crate rustc;
51
52 use syntax::ast;
53 use syntax::codemap::{Span, mk_sp};
54 use syntax::ext::base;
55 use syntax::ext::base::{ExtCtxt, MacExpr};
56 use syntax::ext::build::AstBuilder;
57 use syntax::parse;
58 use syntax::parse::token;
59 use rustc::plugin::Registry;
60
61 use std::gc::Gc;
62
63 #[plugin_registrar]
64 pub fn plugin_registrar(reg: &mut Registry) {
65     reg.register_macro("hexfloat", expand_syntax_ext);
66 }
67
68 //Check if the literal is valid (as LLVM expects),
69 //and return a descriptive error if not.
70 fn hex_float_lit_err(s: &str) -> Option<(uint, String)> {
71     let mut chars = s.chars().peekable();
72     let mut i = 0;
73     if chars.peek() == Some(&'-') { chars.next(); i+= 1 }
74     if chars.next() != Some('0') {
75         return Some((i, "Expected '0'".to_string()));
76     } i+=1;
77     if chars.next() != Some('x') {
78         return Some((i, "Expected 'x'".to_string()));
79     } i+=1;
80     let mut d_len = 0;
81     for _ in chars.take_while(|c| c.is_digit_radix(16)) { chars.next(); i+=1; d_len += 1;}
82     if chars.next() != Some('.') {
83         return Some((i, "Expected '.'".to_string()));
84     } i+=1;
85     let mut f_len = 0;
86     for _ in chars.take_while(|c| c.is_digit_radix(16)) { chars.next(); i+=1; f_len += 1;}
87     if d_len == 0 && f_len == 0 {
88         return Some((i, "Expected digits before or after decimal \
89                          point".to_string()));
90     }
91     if chars.next() != Some('p') {
92         return Some((i, "Expected 'p'".to_string()));
93     } i+=1;
94     if chars.peek() == Some(&'-') { chars.next(); i+= 1 }
95     let mut e_len = 0;
96     for _ in chars.take_while(|c| c.is_digit()) { chars.next(); i+=1; e_len += 1}
97     if e_len == 0 {
98         return Some((i, "Expected exponent digits".to_string()));
99     }
100     match chars.next() {
101         None => None,
102         Some(_) => Some((i, "Expected end of string".to_string()))
103     }
104 }
105
106 pub fn expand_syntax_ext(cx: &mut ExtCtxt, sp: Span, tts: &[ast::TokenTree])
107                          -> Box<base::MacResult> {
108     let (expr, ty_lit) = parse_tts(cx, tts);
109
110     let ty = match ty_lit {
111         None => None,
112         Some(Ident{ident, span}) => match token::get_ident(ident).get() {
113             "f32" => Some(ast::TyF32),
114             "f64" => Some(ast::TyF64),
115             "f128" => Some(ast::TyF128),
116             _ => {
117                 cx.span_err(span, "invalid floating point type in hexfloat!");
118                 None
119             }
120         }
121     };
122
123     let s = match expr.node {
124         // expression is a literal
125         ast::ExprLit(lit) => match lit.node {
126             // string literal
127             ast::LitStr(ref s, _) => {
128                 s.clone()
129             }
130             _ => {
131                 cx.span_err(expr.span, "unsupported literal in hexfloat!");
132                 return base::DummyResult::expr(sp);
133             }
134         },
135         _ => {
136             cx.span_err(expr.span, "non-literal in hexfloat!");
137             return base::DummyResult::expr(sp);
138         }
139     };
140
141     {
142         let err = hex_float_lit_err(s.get());
143         match err {
144             Some((err_pos, err_str)) => {
145                 let pos = expr.span.lo + syntax::codemap::Pos::from_uint(err_pos + 1);
146                 let span = syntax::codemap::mk_sp(pos,pos);
147                 cx.span_err(span,
148                             format!("invalid hex float literal in hexfloat!: \
149                                      {}",
150                                     err_str).as_slice());
151                 return base::DummyResult::expr(sp);
152             }
153             _ => ()
154         }
155     }
156
157     let lit = match ty {
158         None => ast::LitFloatUnsuffixed(s),
159         Some (ty) => ast::LitFloat(s, ty)
160     };
161     MacExpr::new(cx.expr_lit(sp, lit))
162 }
163
164 struct Ident {
165     ident: ast::Ident,
166     span: Span
167 }
168
169 fn parse_tts(cx: &ExtCtxt,
170              tts: &[ast::TokenTree]) -> (Gc<ast::Expr>, Option<Ident>) {
171     let p = &mut parse::new_parser_from_tts(cx.parse_sess(),
172                                             cx.cfg(),
173                                             tts.iter()
174                                                .map(|x| (*x).clone())
175                                                .collect());
176     let ex = p.parse_expr();
177     let id = if p.token == token::EOF {
178         None
179     } else {
180         p.expect(&token::COMMA);
181         let lo = p.span.lo;
182         let ident = p.parse_ident();
183         let hi = p.last_span.hi;
184         Some(Ident{ident: ident, span: mk_sp(lo, hi)})
185     };
186     if p.token != token::EOF {
187         p.unexpected();
188     }
189     (ex, id)
190 }
191
192 // FIXME (10872): This is required to prevent an LLVM assert on Windows
193 #[test]
194 fn dummy_test() { }