]> git.lizzy.rs Git - rust.git/blob - src/test/auxiliary/roman_numerals.rs
Rollup merge of #28991 - goyox86:goyox86/rustfmting-liblog-II, r=alexcrichton
[rust.git] / src / test / auxiliary / roman_numerals.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 // force-host
12
13 #![crate_type="dylib"]
14 #![feature(plugin_registrar, rustc_private)]
15 #![feature(slice_patterns)]
16
17 extern crate syntax;
18 extern crate rustc;
19
20 use syntax::codemap::Span;
21 use syntax::ast::{TokenTree, TtToken};
22 use syntax::parse::token;
23 use syntax::ext::base::{ExtCtxt, MacResult, DummyResult, MacEager};
24 use syntax::ext::build::AstBuilder;  // trait for expr_usize
25 use rustc::plugin::Registry;
26
27 // WARNING WARNING WARNING WARNING WARNING
28 // =======================================
29 //
30 // This code also appears in src/doc/guide-plugin.md. Please keep
31 // the two copies in sync!  FIXME: have rustdoc read this file
32
33 fn expand_rn(cx: &mut ExtCtxt, sp: Span, args: &[TokenTree])
34         -> Box<MacResult + 'static> {
35
36     static NUMERALS: &'static [(&'static str, usize)] = &[
37         ("M", 1000), ("CM", 900), ("D", 500), ("CD", 400),
38         ("C",  100), ("XC",  90), ("L",  50), ("XL",  40),
39         ("X",   10), ("IX",   9), ("V",   5), ("IV",   4),
40         ("I",    1)];
41
42     let text = match args {
43         [TtToken(_, token::Ident(s, _))] => s.to_string(),
44         _ => {
45             cx.span_err(sp, "argument should be a single identifier");
46             return DummyResult::any(sp);
47         }
48     };
49
50     let mut text = &*text;
51     let mut total = 0;
52     while !text.is_empty() {
53         match NUMERALS.iter().find(|&&(rn, _)| text.starts_with(rn)) {
54             Some(&(rn, val)) => {
55                 total += val;
56                 text = &text[rn.len()..];
57             }
58             None => {
59                 cx.span_err(sp, "invalid Roman numeral");
60                 return DummyResult::any(sp);
61             }
62         }
63     }
64
65     MacEager::expr(cx.expr_usize(sp, total))
66 }
67
68 #[plugin_registrar]
69 pub fn plugin_registrar(reg: &mut Registry) {
70     reg.register_macro("rn", expand_rn);
71 }