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.
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.
12 Syntax extension to create floating point literals from hexadecimal strings
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
21 To load the extension and use it:
25 extern crate hexfloat;
28 let val = hexfloat!("0x1.ffffb4", f32);
34 * [ExploringBinary: hexadecimal floating point constants]
35 (http://www.exploringbinary.com/hexadecimal-floating-point-constants/)
39 #![crate_id = "hexfloat#0.11.0-pre"]
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)]
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;
58 use syntax::parse::token;
59 use rustc::plugin::Registry;
64 pub fn plugin_registrar(reg: &mut Registry) {
65 reg.register_macro("hexfloat", expand_syntax_ext);
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();
73 if chars.peek() == Some(&'-') { chars.next(); i+= 1 }
74 if chars.next() != Some('0') {
75 return Some((i, "Expected '0'".to_string()));
77 if chars.next() != Some('x') {
78 return Some((i, "Expected 'x'".to_string()));
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()));
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 \
91 if chars.next() != Some('p') {
92 return Some((i, "Expected 'p'".to_string()));
94 if chars.peek() == Some(&'-') { chars.next(); i+= 1 }
96 for _ in chars.take_while(|c| c.is_digit()) { chars.next(); i+=1; e_len += 1}
98 return Some((i, "Expected exponent digits".to_string()));
102 Some(_) => Some((i, "Expected end of string".to_string()))
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);
110 let ty = match ty_lit {
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),
117 cx.span_err(span, "invalid floating point type in hexfloat!");
123 let s = match expr.node {
124 // expression is a literal
125 ast::ExprLit(lit) => match lit.node {
127 ast::LitStr(ref s, _) => {
131 cx.span_err(expr.span, "unsupported literal in hexfloat!");
132 return base::DummyResult::expr(sp);
136 cx.span_err(expr.span, "non-literal in hexfloat!");
137 return base::DummyResult::expr(sp);
142 let err = hex_float_lit_err(s.get());
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);
148 format!("invalid hex float literal in hexfloat!: \
150 err_str).as_slice());
151 return base::DummyResult::expr(sp);
158 None => ast::LitFloatUnsuffixed(s),
159 Some (ty) => ast::LitFloat(s, ty)
161 MacExpr::new(cx.expr_lit(sp, lit))
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(),
174 .map(|x| (*x).clone())
176 let ex = p.parse_expr();
177 let id = if p.token == token::EOF {
180 p.expect(&token::COMMA);
182 let ident = p.parse_ident();
183 let hi = p.last_span.hi;
184 Some(Ident{ident: ident, span: mk_sp(lo, hi)})
186 if p.token != token::EOF {
192 // FIXME (10872): This is required to prevent an LLVM assert on Windows