Skip to content

Instantly share code, notes, and snippets.

@Noxivs
Created August 2, 2014 16:28
Show Gist options
  • Save Noxivs/2289f0d213656fd7a22f to your computer and use it in GitHub Desktop.
Save Noxivs/2289f0d213656fd7a22f to your computer and use it in GitHub Desktop.
#![feature(quote)]
extern crate syntax;
extern crate rustc;
use std::collections::HashMap;
use std::hash::Hash;
use std::gc::{Gc, GC};
use syntax::ast;
use syntax::codemap;
use syntax::ext::build::AstBuilder;
use syntax::ext::base::{ExtCtxt, MacResult, MacExpr};
use syntax::ext::quote::rt::ToTokens;
pub struct TreeGen<'a, K, V> {
root: Box<Node<K, V>>,
cx: &'a ExtCtxt<'a>,
sp: codemap::Span
}
impl<'a, K: Eq + Hash + ToTokens, V: Clone + ToTokens> TreeGen<'a, K, V> {
pub fn gen(&self) -> Gc<ast::Expr> {
quote_expr!(self.cx,
fn f(keys: Vec<$K:ty>, default: V) -> (){ //
}
f
)
}
}
struct Node<K, V> {
value: Option<V>,
children: HashMap<K, Box<Node<K, V>>>,
index: i16
}
impl<K: Eq + Hash + ToTokens, V: Clone + ToTokens> Node<K, V> {
fn build(&self, cx: &ExtCtxt, sp: codemap::Span, default: V) -> Gc<ast::Expr> {
if self.value.is_none() { // TODO : check keys.len and index
let mut arms = vec!();
for(key , node) in self.children.iter() {
arms.push(gen_arm_inst(cx, sp, key, node.build(cx, sp, default.clone())));
}
arms.push(gen_wild_arm_inst(sp, quote_expr!(cx, default)));
let index = self.index as uint;
cx.expr_match(sp, quote_expr!(cx, keys.get($index)), arms)
} else {
let value = self.value.get_ref().clone();
quote_expr!(cx, {
$value
})
}
}
}
fn gen_arm_inst<K: ToTokens>(cx: &ExtCtxt, sp: codemap::Span, key: &K, body: Gc<ast::Expr>) -> ast::Arm {
let key_pat = cx.pat_lit(sp,quote_expr!(cx, $key));
cx.arm(sp, vec!(key_pat), body)
}
fn gen_wild_arm_inst(sp: codemap::Span, body: Gc<ast::Expr>) -> ast::Arm {
ast::Arm {
attrs: vec!(),
pats: vec!(box(GC) ast::Pat{
id:
ast::DUMMY_NODE_ID,
span: sp,
node: ast::PatWild,
}),
guard: None,
body: body
}
}
fn main() {
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment