Skip to content

Instantly share code, notes, and snippets.

@bombless
Forked from pnkfelix/beatles transcript
Last active August 29, 2015 14:17
Show Gist options
  • Save bombless/d007b9192d6f8db1ec89 to your computer and use it in GitHub Desktop.
Save bombless/d007b9192d6f8db1ec89 to your computer and use it in GitHub Desktop.
% rustc goodbye.rs && rustc -L . beatles.rs && ./beatles
goodbye.rs:10:25: 10:29 warning: unused import, #[warn(unused_imports)] on by default
goodbye.rs:10 use syntax::ext::base::{self, ExtCtxt, MacResult, DummyResult, MacEager};
^~~~
I don't know why you say goodbye, I say hello
#![feature(plugin)]
#![plugin(goodbye)]
macro_rules! beatles {
($fmt:tt, $($arg:tt)*) => {
println!(concat!(goodbye!($fmt), $fmt), $($arg)*)
}
}
fn main() {
beatles!("{} hello", "I don't know why you say", ", I say");
}
fn f1() { let _s = "Goodbye {}"; }
#![feature(plugin)]
#![plugin(goodbye)]
fn main() {
f1();
f2();
f3();
}
fn f1() {
let _s = goodbye!("Hello {}");
}
fn f2() {
println!(goodbye!("Hello {}"), 2);
}
fn f3() {
macro_rules! gprintln {
($fmt:tt, $($arg:tt)*) => {
println!(goodbye!($fmt), $($arg)*)
}
}
gprintln!("Hello {}", 3);
}
#![crate_type="dylib"]
#![feature(plugin_registrar, rustc_private)]
extern crate syntax;
extern crate rustc;
use syntax::codemap::Span;
use syntax::parse::token;
use syntax::ast::{TokenTree, TtToken};
use syntax::ext::base::{self, ExtCtxt, MacResult, DummyResult, MacEager};
use syntax::ext::build::AstBuilder; // trait for expr_usize
use rustc::plugin::Registry;
fn expand_goodbye(cx: &mut ExtCtxt, sp: Span, args: &[TokenTree]) -> Box<MacResult + 'static> {
let name = match args {
[TtToken(_, token::Literal(token::Lit::Str_(name), _opt_name))] |
[TtToken(_, token::Literal(token::Lit::StrRaw(name, _ /* hash count */), _opt_name))]
=> name,
ref t => {
cx.span_err(sp, &format!("argument should be a single token, got {:?}", t));
return DummyResult::any(sp);
}
};
let new_text = token::get_name(name)
.replace("hello", "goodbye")
.replace("Hello", "Goodbye")
.replace("HELLO", "GOODBYE");
MacEager::expr(cx.expr_str(sp, token::get_name(token::intern(&new_text))))
}
#[plugin_registrar]
pub fn plugin_registrar(reg: &mut Registry) {
reg.register_macro("goodbye", expand_goodbye);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment