(index<- ) ./libhexfloat/lib.rs
git branch: * master 5200215 auto merge of #14035 : alexcrichton/rust/experimental, r=huonw
modified: Fri May 9 13:02:28 2014
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(box 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'".to_owned())); } i+=1;
78 if chars.next() != Some('x') { return Some((i, "Expected 'x'".to_owned())); } 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 '.'".to_owned())); } 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".to_owned()));
86 }
87 if chars.next() != Some('p') { return Some((i, "Expected 'p'".to_owned())); } 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".to_owned()));
93 }
94 match chars.next() {
95 None => None,
96 Some(_) => Some((i, "Expected end of string".to_owned()))
97 }
98 }
99
100 pub fn expand_syntax_ext(cx: &mut ExtCtxt, sp: Span, tts: &[ast::TokenTree])
101 -> Box<base::MacResult> {
102 let (expr, ty_lit) = parse_tts(cx, tts);
103
104 let ty = match ty_lit {
105 None => None,
106 Some(Ident{ident, span}) => match token::get_ident(ident).get() {
107 "f32" => Some(ast::TyF32),
108 "f64" => Some(ast::TyF64),
109 "f128" => Some(ast::TyF128),
110 _ => {
111 cx.span_err(span, "invalid floating point type in hexfloat!");
112 None
113 }
114 }
115 };
116
117 let s = match expr.node {
118 // expression is a literal
119 ast::ExprLit(lit) => match lit.node {
120 // string literal
121 ast::LitStr(ref s, _) => {
122 s.clone()
123 }
124 _ => {
125 cx.span_err(expr.span, "unsupported literal in hexfloat!");
126 return base::DummyResult::expr(sp);
127 }
128 },
129 _ => {
130 cx.span_err(expr.span, "non-literal in hexfloat!");
131 return base::DummyResult::expr(sp);
132 }
133 };
134
135 {
136 let err = hex_float_lit_err(s.get());
137 match err {
138 Some((err_pos, err_str)) => {
139 let pos = expr.span.lo + syntax::codemap::Pos::from_uint(err_pos + 1);
140 let span = syntax::codemap::mk_sp(pos,pos);
141 cx.span_err(span, format!("invalid hex float literal in hexfloat!: {}", err_str));
142 return base::DummyResult::expr(sp);
143 }
144 _ => ()
145 }
146 }
147
148 let lit = match ty {
149 None => ast::LitFloatUnsuffixed(s),
150 Some (ty) => ast::LitFloat(s, ty)
151 };
152 MacExpr::new(cx.expr_lit(sp, lit))
153 }
154
155 struct Ident {
156 ident: ast::Ident,
157 span: Span
158 }
159
160 fn parse_tts(cx: &ExtCtxt, tts: &[ast::TokenTree]) -> (@ast::Expr, Option<Ident>) {
161 let p = &mut parse::new_parser_from_tts(cx.parse_sess(),
162 cx.cfg(),
163 tts.iter()
164 .map(|x| (*x).clone())
165 .collect());
166 let ex = p.parse_expr();
167 let id = if p.token == token::EOF {
168 None
169 } else {
170 p.expect(&token::COMMA);
171 let lo = p.span.lo;
172 let ident = p.parse_ident();
173 let hi = p.last_span.hi;
174 Some(Ident{ident: ident, span: mk_sp(lo, hi)})
175 };
176 if p.token != token::EOF {
177 p.unexpected();
178 }
179 (ex, id)
180 }
181
182 // FIXME (10872): This is required to prevent an LLVM assert on Windows
183 #[test]
184 fn dummy_test() { }