Skip to content

Instantly share code, notes, and snippets.

@azyobuzin
Last active August 29, 2015 14:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save azyobuzin/507010037e6945cc1b69 to your computer and use it in GitHub Desktop.
Save azyobuzin/507010037e6945cc1b69 to your computer and use it in GitHub Desktop.
IdentTT
[package]
name = "identtt"
version = "0.0.1"
[lib]
name = "identtt_ext"
path = "lib.rs"
plugin = true
crate-type = ["dylib"]
[[bin]]
name = "identtt"
path = "main.rs"
#![allow(unstable)]
#![feature(box_syntax, plugin_registrar)]
extern crate rustc;
extern crate syntax;
use std::ascii::AsciiExt;
use rustc::plugin::Registry;
use syntax::ast;
use syntax::ast_util;
use syntax::codemap::{DUMMY_SP, Span};
use syntax::ext::base;
use syntax::ext::build::AstBuilder;
use syntax::parse::common::SeqSep;
use syntax::parse::token;
use syntax::ptr::P;
#[plugin_registrar]
pub fn plugin_registrar(reg: &mut Registry) {
let expander: base::IdentMacroExpanderFn = expand_upper_enum;
reg.register_syntax_extension(
token::intern("upper_enum"),
base::IdentTT(box expander, None)
);
}
fn expand_upper_enum(cx: &mut base::ExtCtxt, sp: Span, ident: ast::Ident, args: Vec<ast::TokenTree>) -> Box<base::MacResult + 'static> {
let members = cx.new_parser_from_tts(&args[])
.parse_seq_to_end(
&token::Eof,
SeqSep {
sep: Some(token::Comma),
trailing_sep_allowed: true
},
|p| {
let span = p.span;
let id = p.parse_ident().as_str().to_ascii_uppercase();
P(cx.variant(span, cx.ident_of(&id[]), Vec::new()))
}
);
let attr = cx.attribute(DUMMY_SP, cx.meta_list(
DUMMY_SP,
token::InternedString::new("derive"),
vec![cx.meta_word(DUMMY_SP, token::InternedString::new("Show"))]
));
let item = cx.item(sp, ident, vec![attr],
ast::ItemEnum(
ast::EnumDef { variants: members },
ast_util::empty_generics()
)
);
base::MacItems::new(vec![item].into_iter())
}
#![feature(plugin)]
#[plugin]
#[no_link]
extern crate identtt_ext;
upper_enum! Nemui {
Meccha, SorehodoDemonai
}
fn main() {
println!("{:?}, {:?}",
Nemui::MECCHA, Nemui::SOREHODODEMONAI);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment