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-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")]
47 #![deny(deprecated_owned_vector)]
48 #![feature(macro_registrar, managed_boxes)]
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;
59 use syntax::parse::token;
62 pub fn macro_registrar(register: |Name, SyntaxExtension|) {
63 register(token::intern("hexfloat"),
64 NormalTT(box BasicMacroExpander {
65 expander: expand_syntax_ext,
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();
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;
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;
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()));
87 if chars.next() != Some('p') { return Some((i, "Expected 'p'".to_owned())); } i+=1;
88 if chars.peek() == Some(&'-') { chars.next(); i+= 1 }
90 for _ in chars.take_while(|c| c.is_digit()) { chars.next(); i+=1; e_len += 1}
92 return Some((i, "Expected exponent digits".to_owned()));
96 Some(_) => Some((i, "Expected end of string".to_owned()))
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);
104 let ty = match ty_lit {
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),
111 cx.span_err(span, "invalid floating point type in hexfloat!");
117 let s = match expr.node {
118 // expression is a literal
119 ast::ExprLit(lit) => match lit.node {
121 ast::LitStr(ref s, _) => {
125 cx.span_err(expr.span, "unsupported literal in hexfloat!");
126 return base::DummyResult::expr(sp);
130 cx.span_err(expr.span, "non-literal in hexfloat!");
131 return base::DummyResult::expr(sp);
136 let err = hex_float_lit_err(s.get());
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);
149 None => ast::LitFloatUnsuffixed(s),
150 Some (ty) => ast::LitFloat(s, ty)
152 MacExpr::new(cx.expr_lit(sp, lit))
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(),
164 .map(|x| (*x).clone())
166 let ex = p.parse_expr();
167 let id = if p.token == token::EOF {
170 p.expect(&token::COMMA);
172 let ident = p.parse_ident();
173 let hi = p.last_span.hi;
174 Some(Ident{ident: ident, span: mk_sp(lo, hi)})
176 if p.token != token::EOF {
182 // FIXME (10872): This is required to prevent an LLVM assert on Windows