json_str 0.4.0

Write json literals without ugly strings.
Documentation
extern crate syntax;
extern crate rustc;
extern crate rustc_plugin;

use rustc_plugin::Registry;

use syntax::codemap::Span;
use syntax::ptr::P;
use syntax::symbol::Symbol;
use syntax::tokenstream::TokenTree;
use syntax::ext::base::{ ExtCtxt, MacResult, MacEager };
use syntax::ext::build::AstBuilder;
use ::parse::*;

fn tts_to_json(args: &[TokenTree]) -> String {
	let json_raw = syntax::print::pprust::tts_to_string(&args);
	let mut json = String::with_capacity(json_raw.len());
	sanitise(json_raw.as_bytes(), &mut json);

	json
}

//Parse a token tree to a json `str` at compile time.
pub fn expand_json_lit(cx: &mut ExtCtxt, sp: Span, args: &[TokenTree]) -> Box<MacResult+'static> {
	let json = tts_to_json(args);

	let str_lit = cx.expr_str(sp, Symbol::intern(&json));
	MacEager::expr(P(quote_expr!(cx, $str_lit).unwrap()))
}

//Parse a token tree to a json `String` at compile time.
pub fn expand_json_string(cx: &mut ExtCtxt, sp: Span, args: &[TokenTree]) -> Box<MacResult+'static> {
	let json = tts_to_json(args);

	let str_lit = cx.expr_str(sp, Symbol::intern(&json));
	MacEager::expr(P(quote_expr!(cx, String::from($str_lit)).unwrap()))
}

#[doc(hidden)]
#[plugin_registrar]
pub fn plugin_registrar(reg: &mut Registry) {
	reg.register_macro("json_lit", expand_json_lit);
	reg.register_macro("json_str", expand_json_string);
}