Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Extract struct fields into metadata #3

Merged
merged 6 commits into from
Jun 30, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
68 changes: 49 additions & 19 deletions core/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,16 +1,38 @@
use std::collections::HashMap;

use quote::ToTokens;
use syn::*;

use crate::meta::types::CustomType;

pub mod meta;

pub fn extract_from_mod(input: &ItemMod) -> Vec<meta::Struct> {
pub fn extract_from_mod(input: &ItemMod) -> HashMap<String, meta::types::CustomType> {
let mut custom_types_by_name = HashMap::new();
input
.content
.as_ref()
.unwrap()
.1
.iter()
.filter_map(|a| match a {
.for_each(|a| match a {
Item::Struct(strct) => {
if strct
.attrs
.iter()
.any(|a| a.path.to_token_stream().to_string() == "diplomat :: opaque")
{
custom_types_by_name.insert(
strct.ident.to_string(),
meta::types::CustomType::Opaque(strct.ident.to_string(), vec![]),
);
} else {
custom_types_by_name.insert(
strct.ident.to_string(),
meta::types::CustomType::Struct(meta::structs::Struct::from(strct)),
);
}
}
Item::Impl(ipl) => {
assert!(ipl.trait_.is_none());

Expand All @@ -19,33 +41,41 @@ pub fn extract_from_mod(input: &ItemMod) -> Vec<meta::Struct> {
_ => panic!("Self type not found"),
};

Some(meta::Struct {
name: self_typ.path.get_ident().unwrap().to_string(),
methods: ipl
.items
.iter()
.filter_map(|i| match i {
ImplItem::Method(m) => Some(meta::Method::from_syn(m, self_typ)),
_ => None,
})
.collect(),
})
let mut new_methods = ipl
.items
.iter()
.filter_map(|i| match i {
ImplItem::Method(m) => Some(meta::methods::Method::from_syn(m, self_typ)),
_ => None,
})
.collect();

match custom_types_by_name
.get_mut(&self_typ.path.get_ident().unwrap().to_string())
.unwrap()
{
CustomType::Struct(strct) => {
strct.methods.append(&mut new_methods);
}
CustomType::Opaque(_, methods) => methods.append(&mut new_methods),
}
}
_ => None,
})
.collect()
_ => {}
});

custom_types_by_name
}

pub fn extract_from_file(file: File) -> Vec<meta::Struct> {
let mut out = vec![];
pub fn extract_from_file(file: File) -> HashMap<String, meta::types::CustomType> {
let mut out = HashMap::new();
file.items.iter().for_each(|i| {
if let Item::Mod(item_mod) = i {
if item_mod
.attrs
.iter()
.any(|a| a.path.to_token_stream().to_string() == "diplomat :: bridge")
{
out.append(&mut extract_from_mod(item_mod));
out.extend(extract_from_mod(item_mod));
}
}
});
Expand Down
81 changes: 81 additions & 0 deletions core/src/meta/methods.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
use syn::*;

use super::types::TypeName;

#[derive(Clone, Debug)]
pub struct Method {
pub name: String,
pub full_path_name: String,
pub self_param: Option<Param>,
pub params: Vec<Param>,
pub return_type: Option<TypeName>,
}

impl Method {
pub fn from_syn(m: &ImplItemMethod, self_type: &TypePath) -> Method {
let self_ident = self_type.path.get_ident().unwrap();
let method_ident = &m.sig.ident;
let extern_ident = Ident::new(
format!("{}_{}", &self_ident.to_string(), method_ident.to_string()).as_str(),
m.sig.ident.span(),
);

let all_params = m
.sig
.inputs
.iter()
.filter_map(|a| match a {
FnArg::Receiver(_) => None,
FnArg::Typed(t) => Some(t.into()),
})
.collect::<Vec<_>>();

let self_param = m.sig.receiver().map(|rec| match rec {
FnArg::Receiver(rec) => Param {
name: "self".to_string(),
ty: if rec.reference.is_some() {
TypeName::Reference(
Box::new(TypeName::Named(self_ident.to_string())),
rec.mutability.is_some(),
)
} else {
TypeName::Named(self_ident.to_string())
},
},
_ => panic!("Unexpected self param type"),
});

let return_ty = match &m.sig.output {
ReturnType::Type(_, return_typ) => Some(return_typ.as_ref().into()),
ReturnType::Default => None,
};

Method {
name: method_ident.to_string(),
full_path_name: extern_ident.to_string(),
self_param,
params: all_params,
return_type: return_ty,
}
}
}

#[derive(Clone, Debug)]
pub struct Param {
pub name: String,
pub ty: TypeName,
}

impl From<&syn::PatType> for Param {
fn from(t: &PatType) -> Param {
let ident = match t.pat.as_ref() {
Pat::Ident(ident) => ident.clone(),
_ => panic!("Unexpected param type"),
};

Param {
name: ident.ident.to_string(),
ty: t.ty.as_ref().into(),
}
}
}
3 changes: 3 additions & 0 deletions core/src/meta/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
pub mod methods;
pub mod structs;
pub mod types;
33 changes: 33 additions & 0 deletions core/src/meta/structs.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
use std::collections::HashMap;

use super::{methods::Method, types::TypeName};

#[derive(Clone, Debug)]
pub struct Struct {
pub name: String,
pub fields: HashMap<String, TypeName>,
pub methods: Vec<Method>,
}

impl From<&syn::ItemStruct> for Struct {
fn from(strct: &syn::ItemStruct) -> Struct {
Struct {
name: strct.ident.to_string(),
fields: strct
.fields
.iter()
.enumerate()
.map(|(i, f)| {
(
f.ident
.as_ref()
.map(|i| i.to_string())
.unwrap_or(format!("{}", i)),
(&f.ty).into(),
)
})
.collect(),
methods: vec![],
}
}
}
Loading