finish extact funciton on parsed AST, structure extract / generate functions

This commit is contained in:
Dan Ballard 2022-01-10 09:18:40 -05:00
parent 763bf69112
commit b6d8190525
1 changed files with 35 additions and 10 deletions

View File

@ -6,22 +6,25 @@ use syn;
// cbind!(fn start_cwtch(app_dir: &str, tor_path: &str) -> i32 {c_StartCwtch});
#[proc_macro]
pub fn cbind(_def: TokenStream) -> TokenStream {
//dbg!(&_def);
let ast: syn::ItemFn = syn::parse(_def).unwrap();
dbg!(&ast);
let (fn_name, fn_args, fn_ret, fn_call) = extract(ast);
let fn_name = ast.sig.ident;
generate(fn_name, fn_args, fn_ret, fn_call)
}
fn extract(ast: syn::ItemFn) -> (String, Vec<(String, String)>, Option<String>, String) {
let fn_name = ast.sig.ident.to_string();
let fn_call = match &ast.block.stmts[0] {
syn::Stmt::Expr(expr) => match expr {
syn::Expr::Path(expr) => Ok(expr.path.segments[0].ident.to_string()),
_ => Err("".to_string()),
syn::Expr::Path(expr) => expr.path.segments[0].ident.to_string(),
_ => panic!("Could not find binding function to call, did you include '{}'", "{ bingden_fn_to_call() }"),
}
_ => Err("".to_string()),
_ => panic!("Could not find binding function to call, did you include '{}'", "{ bingden_fn_to_call() }"),
};
let ret_type = match &ast.sig.output {
syn::ReturnType::Type(_, box_type) => {
let ty= &**box_type;
let ty = &**box_type;
match ty {
syn::Type::Path(p) => {
if p.path.segments.len() == 1 {
@ -35,11 +38,33 @@ pub fn cbind(_def: TokenStream) -> TokenStream {
}
_ => None
};
let mut args: Vec<(String, String)> = vec!();
for arg in &ast.sig.inputs {
let arg_name = match arg {
syn::FnArg::Typed(pat_type) => {
(match &*pat_type.pat {
syn::Pat::Ident(ident) => ident.ident.to_string(),
_ => panic!("Could not find argument name")
},
match &*pat_type.ty {
syn::Type::Reference(tref) => match &*tref.elem {
syn::Type::Path(path) => path.path.segments[0].ident.to_string(),
_ => panic!("Could not find argument type")
},
_ => panic!("Could not find argument type")
})
}
_ => panic!("Could not find expected argument")
};
args.push(arg_name);
};
dbg!(fn_call);
dbg!(ret_type);
let args = ast.sig.inputs;
(fn_name, args, ret_type, fn_call)
}
fn generate(fn_name: String, fn_args: Vec<(String, String)>, fn_ret: Option<String>, fn_call: String) -> TokenStream {
quote!(fn #fn_name(&self) {}).into()
}