diff options
author | Arpad Borsos <arpad.borsos@googlemail.com> | 2015-02-03 13:49:24 +0100 |
---|---|---|
committer | Arpad Borsos <arpad.borsos@googlemail.com> | 2015-02-03 19:58:47 +0100 |
commit | 02d750adba9b2313ffcce8392965177738a35d62 (patch) | |
tree | 14cdaba2cef3c190758f007b88d004b68d977a03 /components/plugins/casing.rs | |
parent | ff53354ba7716fadc7656891d7b0723a3730e890 (diff) | |
download | servo-02d750adba9b2313ffcce8392965177738a35d62.tar.gz servo-02d750adba9b2313ffcce8392965177738a35d62.zip |
Lowercase DOM getters at compile time, fixes #4728
The implementation was copied directly from
https://github.com/rust-lang/rust/pull/16636
and updated for rust changes, so the credit goes to @Manishearth
Diffstat (limited to 'components/plugins/casing.rs')
-rw-r--r-- | components/plugins/casing.rs | 60 |
1 files changed, 60 insertions, 0 deletions
diff --git a/components/plugins/casing.rs b/components/plugins/casing.rs new file mode 100644 index 00000000000..374290f3cbb --- /dev/null +++ b/components/plugins/casing.rs @@ -0,0 +1,60 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +use syntax::ext::base::ExtCtxt; +use syntax::ext::build::AstBuilder; +use syntax::codemap::Span; +use syntax::ast; +use syntax::ext::base; +use syntax::parse::token; + +pub fn expand_lower<'cx>(cx: &'cx mut ExtCtxt, sp: Span, tts: &[ast::TokenTree]) + -> Box<base::MacResult + 'cx> { + expand_cased(cx, sp, tts, |c| { c.to_lowercase() }) +} + +pub fn expand_upper<'cx>(cx: &'cx mut ExtCtxt, sp: Span, tts: &[ast::TokenTree]) + -> Box<base::MacResult + 'cx> { + expand_cased(cx, sp, tts, |c| { c.to_uppercase() }) +} + +fn expand_cased<'cx, T>(cx: &'cx mut ExtCtxt, sp: Span, tts: &[ast::TokenTree], transform: T) + -> Box<base::MacResult + 'cx> + where T: Fn(char) -> char +{ + let es = match base::get_exprs_from_tts(cx, sp, tts) { + Some(e) => e, + None => return base::DummyResult::expr(sp) + }; + + let mut it = es.iter(); + let res = if let Some(expr) = it.next() { + if let ast::ExprLit(ref lit) = expr.node { + if let ast::LitStr(ref s, _) = lit.node { + Some((s, lit.span)) + } else { + cx.span_err(expr.span, "expected a string literal"); + None + } + } else { + cx.span_err(expr.span, "expected a string literal"); + None + } + } else { + cx.span_err(sp, "expected 1 argument, found 0"); + None + }; + match (res, it.count()) { + (Some((s, span)), 0) => { + let new_s = s.get().chars().map(transform).collect::<String>(); + base::MacExpr::new(cx.expr_str(span, token::intern_and_get_ident(new_s.as_slice()))) + } + (_, rest) => { + if rest > 0 { + cx.span_err(sp, format!("expected 1 argument, found {}", rest+1).as_slice()); + } + base::DummyResult::expr(sp) + } + } +} |