]> git.lizzy.rs Git - rust.git/blob - src/libfourcc/lib.rs
auto merge of #13711 : alexcrichton/rust/snapshots, r=brson
[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(syntax)]
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-pre"]
43 #![crate_type = "rlib"]
44 #![crate_type = "dylib"]
45 #![license = "MIT/ASL2"]
46 #![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
47        html_favicon_url = "http://www.rust-lang.org/favicon.ico",
48        html_root_url = "http://static.rust-lang.org/doc/master")]
49
50 #![deny(deprecated_owned_vector)]
51 #![feature(macro_registrar, managed_boxes)]
52
53 extern crate syntax;
54
55 use syntax::ast;
56 use syntax::ast::Name;
57 use syntax::attr::contains;
58 use syntax::codemap::{Span, mk_sp};
59 use syntax::ext::base;
60 use syntax::ext::base::{SyntaxExtension, BasicMacroExpander, NormalTT, ExtCtxt, MacExpr};
61 use syntax::ext::build::AstBuilder;
62 use syntax::parse;
63 use syntax::parse::token;
64 use syntax::parse::token::InternedString;
65
66 #[macro_registrar]
67 pub fn macro_registrar(register: |Name, SyntaxExtension|) {
68     register(token::intern("fourcc"),
69         NormalTT(~BasicMacroExpander {
70             expander: expand_syntax_ext,
71             span: None,
72         },
73         None));
74 }
75
76 pub fn expand_syntax_ext(cx: &mut ExtCtxt, sp: Span, tts: &[ast::TokenTree]) -> ~base::MacResult {
77     let (expr, endian) = parse_tts(cx, tts);
78
79     let little = match endian {
80         None => false,
81         Some(Ident{ident, span}) => match token::get_ident(ident).get() {
82             "little" => true,
83             "big" => false,
84             "target" => target_endian_little(cx, sp),
85             _ => {
86                 cx.span_err(span, "invalid endian directive in fourcc!");
87                 target_endian_little(cx, sp)
88             }
89         }
90     };
91
92     let s = match expr.node {
93         // expression is a literal
94         ast::ExprLit(ref lit) => match lit.node {
95             // string literal
96             ast::LitStr(ref s, _) => {
97                 if s.get().char_len() != 4 {
98                     cx.span_err(expr.span, "string literal with len != 4 in fourcc!");
99                 }
100                 s
101             }
102             _ => {
103                 cx.span_err(expr.span, "unsupported literal in fourcc!");
104                 return base::DummyResult::expr(sp)
105             }
106         },
107         _ => {
108             cx.span_err(expr.span, "non-literal in fourcc!");
109             return base::DummyResult::expr(sp)
110         }
111     };
112
113     let mut val = 0u32;
114     for codepoint in s.get().chars().take(4) {
115         let byte = if codepoint as u32 > 0xFF {
116             cx.span_err(expr.span, "fourcc! literal character out of range 0-255");
117             0u8
118         } else {
119             codepoint as u8
120         };
121
122         val = if little {
123             (val >> 8) | ((byte as u32) << 24)
124         } else {
125             (val << 8) | (byte as u32)
126         };
127     }
128     let e = cx.expr_lit(sp, ast::LitUint(val as u64, ast::TyU32));
129     MacExpr::new(e)
130 }
131
132 struct Ident {
133     ident: ast::Ident,
134     span: Span
135 }
136
137 fn parse_tts(cx: &ExtCtxt, tts: &[ast::TokenTree]) -> (@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() { }