Skip to content

Commit

Permalink
extract from_py_with parsing into its own module
Browse files Browse the repository at this point in the history
  • Loading branch information
daniil-konovalenko committed Feb 9, 2021
1 parent 7d76bc7 commit e2ed1fc
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 15 deletions.
27 changes: 27 additions & 0 deletions pyo3-macros-backend/src/attrs.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
use proc_macro2::TokenStream;
use quote::ToTokens;
use syn::spanned::Spanned;
use syn::{Meta, MetaNameValue, Result};

#[derive(Clone, Debug, PartialEq)]
pub struct FromPyWithAttribute(syn::ExprPath);

impl FromPyWithAttribute {
pub fn from_meta(meta: Meta) -> Result<Self> {
if let Meta::NameValue(MetaNameValue {
lit: syn::Lit::Str(string_literal),
..
}) = meta
{
let expr_path = string_literal.parse::<syn::ExprPath>()?;
return Ok(FromPyWithAttribute(expr_path));
}
bail_spanned!(meta.span() => "expected a name-value: `pyo3(from_py_with = \"func\")` ")
}
}

impl ToTokens for FromPyWithAttribute {
fn to_tokens(&self, tokens: &mut TokenStream) {
self.0.to_tokens(tokens)
}
}
20 changes: 5 additions & 15 deletions pyo3-macros-backend/src/from_pyobject.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,9 @@
use crate::attrs::FromPyWithAttribute;
use proc_macro2::TokenStream;
use quote::quote;
use syn::punctuated::Punctuated;
use syn::spanned::Spanned;
use syn::{
parse_quote, Attribute, DataEnum, DeriveInput, Fields, Ident, Meta, MetaList, MetaNameValue,
Result,
};
use syn::{parse_quote, Attribute, DataEnum, DeriveInput, Fields, Ident, Meta, MetaList, Result};

/// Describes derivation input of an enum.
#[derive(Debug)]
Expand Down Expand Up @@ -320,7 +318,7 @@ impl ContainerAttribute {
#[derive(Clone, Debug)]
struct FieldAttributes {
getter: FieldGetter,
from_py_with: Option<syn::ExprPath>,
from_py_with: Option<FromPyWithAttribute>,
}

#[derive(Clone, Debug)]
Expand Down Expand Up @@ -418,16 +416,8 @@ impl FieldAttributes {
bail_spanned!(arg_list.span() => "expected a single literal argument");
}

fn from_py_with_arg(meta: Meta) -> syn::Result<syn::ExprPath> {
if let Meta::NameValue(MetaNameValue {
lit: syn::Lit::Str(string_literal),
..
}) = meta
{
let expr_path = string_literal.parse::<syn::ExprPath>()?;
return Ok(expr_path);
}
bail_spanned!(meta.span() => "expected a name-value: `pyo3(from_py_with = \"func\")` ")
fn from_py_with_arg(meta: Meta) -> syn::Result<FromPyWithAttribute> {
FromPyWithAttribute::from_meta(meta)
}
}

Expand Down
1 change: 1 addition & 0 deletions pyo3-macros-backend/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
#[macro_use]
mod utils;

mod attrs;
mod defs;
mod from_pyobject;
mod konst;
Expand Down

0 comments on commit e2ed1fc

Please sign in to comment.