]> git.lizzy.rs Git - rust.git/blob - src/libfourcc/lib.rs
librustc: Don't try to perform the magical
[rust.git] / src / libfourcc / 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 generate FourCCs.
13
14 Once loaded, fourcc!() is called with a single 4-character string,
15 and an optional ident that is either `big`, `little`, or `target`.
16 The ident represents endianness, and specifies in which direction
17 the characters should be read. If the ident is omitted, it is assumed
18 to be `big`, i.e. left-to-right order. It returns a u32.
19
20 # Examples
21
22 To load the extension and use it:
23
24 ```rust,ignore
25 #[phase(plugin)]
26 extern crate fourcc;
27
28 fn main() {
29     let val = fourcc!("\xC0\xFF\xEE!");
30     assert_eq!(val, 0xC0FFEE21u32);
31     let little_val = fourcc!("foo ", little);
32     assert_eq!(little_val, 0x21EEFFC0u32);
33 }
34 ```
35
36 # References
37
38 * [Wikipedia: FourCC](http://en.wikipedia.org/wiki/FourCC)
39
40 */
41
42 #![crate_id = "fourcc#0.11.0-pre"]
43 #![experimental]
44 #![crate_type = "rlib"]
45 #![crate_type = "dylib"]
46 #![license = "MIT/ASL2"]
47 #![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
48        html_favicon_url = "http://www.rust-lang.org/favicon.ico",
49        html_root_url = "http://doc.rust-lang.org/")]
50
51 #![feature(plugin_registrar, managed_boxes)]
52
53 extern crate syntax;
54 extern crate rustc;
55
56 use syntax::ast;
57 use syntax::attr::contains;
58 use syntax::codemap::{Span, mk_sp};
59 use syntax::ext::base;
60 use syntax::ext::base::{ExtCtxt, MacExpr};
61 use syntax::ext::build::AstBuilder;
62 use syntax::parse;
63 use syntax::parse::token;
64 use syntax::parse::token::InternedString;
65 use rustc::plugin::Registry;
66
67 use std::gc::Gc;
68
69 #[plugin_registrar]
70 pub fn plugin_registrar(reg: &mut Registry) {
71     reg.register_macro("fourcc", expand_syntax_ext);
72 }
73
74 pub fn expand_syntax_ext(cx: &mut ExtCtxt, sp: Span, tts: &[ast::TokenTree])
75                          -> Box<base::MacResult> {
76     let (expr, endian) = parse_tts(cx, tts);
77
78     let little = match endian {
79         None => false,
80         Some(Ident{ident, span}) => match token::get_ident(ident).get() {
81             "little" => true,
82             "big" => false,
83             "target" => target_endian_little(cx, sp),
84             _ => {
85                 cx.span_err(span, "invalid endian directive in fourcc!");
86                 target_endian_little(cx, sp)
87             }
88         }
89     };
90
91     let s = match expr.node {
92         // expression is a literal
93         ast::ExprLit(ref lit) => match lit.node {
94             // string literal
95             ast::LitStr(ref s, _) => {
96                 if s.get().char_len() != 4 {
97                     cx.span_err(expr.span, "string literal with len != 4 in fourcc!");
98                 }
99                 s
100             }
101             _ => {
102                 cx.span_err(expr.span, "unsupported literal in fourcc!");
103                 return base::DummyResult::expr(sp)
104             }
105         },
106         _ => {
107             cx.span_err(expr.span, "non-literal in fourcc!");
108             return base::DummyResult::expr(sp)
109         }
110     };
111
112     let mut val = 0u32;
113     for codepoint in s.get().chars().take(4) {
114         let byte = if codepoint as u32 > 0xFF {
115             cx.span_err(expr.span, "fourcc! literal character out of range 0-255");
116             0u8
117         } else {
118             codepoint as u8
119         };
120
121         val = if little {
122             (val >> 8) | ((byte as u32) << 24)
123         } else {
124             (val << 8) | (byte as u32)
125         };
126     }
127     let e = cx.expr_lit(sp, ast::LitUint(val as u64, ast::TyU32));
128     MacExpr::new(e)
129 }
130
131 struct Ident {
132     ident: ast::Ident,
133     span: Span
134 }
135
136 fn parse_tts(cx: &ExtCtxt,
137              tts: &[ast::TokenTree]) -> (Gc<ast::Expr>, Option<Ident>) {
138     let p = &mut parse::new_parser_from_tts(cx.parse_sess(),
139                                             cx.cfg(),
140                                             tts.iter()
141                                                .map(|x| (*x).clone())
142                                                .collect());
143     let ex = p.parse_expr();
144     let id = if p.token == token::EOF {
145         None
146     } else {
147         p.expect(&token::COMMA);
148         let lo = p.span.lo;
149         let ident = p.parse_ident();
150         let hi = p.last_span.hi;
151         Some(Ident{ident: ident, span: mk_sp(lo, hi)})
152     };
153     if p.token != token::EOF {
154         p.unexpected();
155     }
156     (ex, id)
157 }
158
159 fn target_endian_little(cx: &ExtCtxt, sp: Span) -> bool {
160     let meta = cx.meta_name_value(sp, InternedString::new("target_endian"),
161         ast::LitStr(InternedString::new("little"), ast::CookedStr));
162     contains(cx.cfg().as_slice(), meta)
163 }
164
165 // FIXME (10872): This is required to prevent an LLVM assert on Windows
166 #[test]
167 fn dummy_test() { }