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

Error #22

Merged
merged 9 commits into from
Nov 21, 2020
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
4 changes: 4 additions & 0 deletions perde-core/src/args.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,10 @@ impl<'a> Args<'a> {
})
}

pub fn len(&self) -> usize {
self.tuple.len()
}

pub fn arg(&self, index: usize) -> Result<&ObjectRef> {
self.tuple.get(index)
}
Expand Down
2 changes: 1 addition & 1 deletion perde-core/src/decode/class.rs
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,7 @@ impl Class {
// If default is defined, use it.
// If this is optional, return `None`.
if let Some(d) = s.attr.default.as_ref() {
return Ok(d.clone());
return Ok(d.owned());
} else if let Some(d) = s.attr.default_factory.as_ref() {
return d.call0();
} else if s.schema.is_optional() {
Expand Down
7 changes: 6 additions & 1 deletion perde-core/src/encode.rs
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,12 @@ impl<'a> Serialize for WithSchema<'a> {
map.end()
}
Schema::Class(c) => {
let mut map = s.serialize_map(Some(c.ser_field_len))?;
let len = if c.flatten_dict.is_some() {
None
} else {
Some(c.ser_field_len)
};
let mut map = s.serialize_map(len)?;
serialize_fields(&self.object, &c.fields, &mut map)?;
map.end()
}
Expand Down
100 changes: 87 additions & 13 deletions perde-core/src/error.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,15 @@
use crate::object::ErrorObject;
use pyo3::{type_object::PyTypeObject, PyErr, Python};
use serde::{de, ser};
use std::fmt::{self, Display};

pub type Result<T> = std::result::Result<T, Error>;

#[derive(Debug)]
pub struct Error {
msg: String,
pub enum Error {
TypeError(String),
ValueError(String),
Native(String, Option<ErrorObject>),
}

#[macro_export]
Expand All @@ -16,31 +19,95 @@ macro_rules! err {
}
}

#[macro_export]
macro_rules! type_err {
($($t:tt)*) => {
$crate::error::Error::type_error(format!($($t)*))
}
}

#[macro_export]
macro_rules! value_err {
($($t:tt)*) => {
$crate::error::Error::value_error(format!($($t)*))
}
}

#[macro_export]
macro_rules! bail {
($($t:tt)*) => {
return Err($crate::err!($($t)*));
}
}

#[macro_export]
macro_rules! bail_type_err {
($($t:tt)*) => {
return Err($crate::type_err!($($t)*))
}
}

#[macro_export]
macro_rules! bail_value_err {
($($t:tt)*) => {
return Err($crate::value_err!($($t)*))
}
}

pub fn raise<T: PyTypeObject, U: ToString>(msg: U) {
let gil = Python::acquire_gil();
let py = gil.python();
let pyerr = PyErr::new::<T, _>(msg.to_string());
pyerr.restore(py);
}

impl Error {
pub fn new<T>(t: T) -> Self
where
T: ToString,
{
let py = unsafe { Python::assume_gil_acquired() };
Self::Native(t.to_string(), ErrorObject::new())
}

if PyErr::occurred(py) {
unsafe { pyo3::ffi::PyErr_Clear() };
}
pub fn type_error<T>(t: T) -> Self
where
T: ToString,
{
ErrorObject::clear();
Self::TypeError(t.to_string())
}

Self { msg: t.to_string() }
pub fn value_error<T>(t: T) -> Self
where
T: ToString,
{
ErrorObject::clear();
Self::ValueError(t.to_string())
}

pub fn restore_as<T: PyTypeObject>(self) {
let py = unsafe { Python::assume_gil_acquired() };
let pyerr = PyErr::new::<T, _>(self.msg);
pyerr.restore(py);
match self {
Error::TypeError(t) => raise::<pyo3::exceptions::PyTypeError, _>(t),
Error::ValueError(t) => raise::<pyo3::exceptions::PyValueError, _>(t),
Error::Native(_, Some(t)) => {
t.restore();
}
Error::Native(s, None) => raise::<T, _>(format!("{}", s)),
}
}

pub fn set_message(&mut self, message: String) {
match self {
Error::TypeError(m) | Error::ValueError(m) | Error::Native(m, _) => {
*m = message;
}
}
}

pub fn message(&self) -> &str {
match self {
Self::TypeError(m) | Self::ValueError(m) | Self::Native(m, _) => &m,
}
}
}

Expand All @@ -55,7 +122,13 @@ where

impl Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.msg)
write!(
f,
"{}",
match self {
Error::TypeError(m) | Error::ValueError(m) | Error::Native(m, _) => m,
}
)
}
}

Expand Down Expand Up @@ -96,8 +169,9 @@ impl<T> Convert<T> for Result<T> {
where
C: ToString,
{
self.map_err(|e| Error {
msg: format!("{}: {}", context.to_string(), e),
self.map_err(|mut e| {
e.set_message(format!("{}: {}", context.to_string(), e));
e
})
}
}
84 changes: 36 additions & 48 deletions perde-core/src/import.rs
Original file line number Diff line number Diff line change
@@ -1,69 +1,57 @@
use crate::{error::Result, object::Object};
use crate::{
error::Result,
object::{Object, SyncObject},
};
use pyo3::prelude::*;
use std::ops::Deref;

#[derive(Debug)]
pub struct StaticObject(Object);

impl Deref for StaticObject {
type Target = Object;

fn deref(&self) -> &Self::Target {
&self.0
}
}

impl From<pyo3::PyObject> for StaticObject {
fn from(p: pyo3::PyObject) -> Self {
StaticObject(Object::new(p.into_ptr()).unwrap())
}
}

pub struct Import {
pub fields: StaticObject,
pub missing: StaticObject,
pub generic_alias: StaticObject,
pub base_generic_alias: Option<StaticObject>,
pub union_generic_alias: Option<StaticObject>,
pub special_generic_alias: Option<StaticObject>,
pub type_var: StaticObject,
pub any: StaticObject,
pub union: StaticObject,
pub tuple: StaticObject,
pub empty_tuple: StaticObject,
pub optional: StaticObject,
pub dict: StaticObject,
pub list: StaticObject,
pub set: StaticObject,
pub frozenset: StaticObject,
pub enum_meta: StaticObject,
pub datetime: StaticObject,
pub date: StaticObject,
pub time: StaticObject,
pub decimal: StaticObject,
pub uuid: StaticObject,
pub fields: SyncObject,
pub missing: SyncObject,
pub generic_alias: SyncObject,
pub base_generic_alias: Option<SyncObject>,
pub union_generic_alias: Option<SyncObject>,
pub special_generic_alias: Option<SyncObject>,
pub type_var: SyncObject,
pub any: SyncObject,
pub union: SyncObject,
pub tuple: SyncObject,
pub empty_tuple: SyncObject,
pub optional: SyncObject,
pub dict: SyncObject,
pub list: SyncObject,
pub set: SyncObject,
pub frozenset: SyncObject,
pub enum_meta: SyncObject,
pub datetime: SyncObject,
pub date: SyncObject,
pub time: SyncObject,
pub decimal: SyncObject,
pub uuid: SyncObject,
}

unsafe impl Sync for StaticObject {}

pub fn import() -> Result<&'static Import> {
STATIC_OBJECTS.as_ref().map_err(|e| err!("{}", e))
IMPORT.as_ref().map_err(|e| err!("{}", e))
}

macro_rules! getattr {
($module:expr, $name:expr) => {
$module
.getattr($name)
.map(|p| pyo3::PyObject::from(p).into())
.map(|p| {
Object::new(pyo3::PyObject::from(p).into_ptr())
.unwrap()
.into()
})
.map_err(|_| err!(concat!("couldn't find function `", $name, "`")))
};
}

lazy_static::lazy_static! {
static ref STATIC_OBJECTS: Result<Import> = {
static ref IMPORT: Result<Import> = {
use pyo3::{Python, types::PyModule};

let py = unsafe { Python::assume_gil_acquired() };
let gil = Python::acquire_gil();
let py = gil.python();

macro_rules! import {
($name:expr) => {
Expand Down Expand Up @@ -96,7 +84,7 @@ lazy_static::lazy_static! {
let frozenset = getattr!(typing, "FrozenSet")?;
let enum_meta = getattr!(enum_, "EnumMeta")?;

let empty_tuple = StaticObject(Object::new_unit()?);
let empty_tuple = SyncObject::new(Object::new_unit()?);

let datetime = getattr!(datetime_, "datetime")?;
let date = getattr!(datetime_, "date")?;
Expand Down
5 changes: 3 additions & 2 deletions perde-core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,11 @@ pub mod object;

pub mod prelude {
pub use crate::args::{Args, FastArgs};
pub use crate::error::{Convert, Error, Result};
pub use crate::error::{raise, Convert, Error, Result};
pub use crate::object::{Object, ObjectRef};
pub use crate::schema::{Schema, WithSchema};
pub use crate::{
bail, exception, impl_default_methods, method_fastcall, method_varargs, module,
bail, bail_type_err, bail_value_err, err, exception, impl_default_methods, method_fastcall,
method_varargs, module, type_err, value_err,
};
}
46 changes: 32 additions & 14 deletions perde-core/src/methods.rs
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,18 @@ macro_rules! impl_default_methods {

let inner = || {
let args = Args::new(args)?;
$loads_as(args.arg(0)?.resolve(None)?, args.arg(1)?)

if args.len() != 2 {
return Err($crate::type_err!(
"loads_as() requires 2 positional arguments but got {}",
args.len()
));
}

$loads_as(
args.arg(0)?.resolve(None).context("invalid argument")?,
args.arg(1)?,
)
};

match inner() {
Expand All @@ -119,19 +130,20 @@ macro_rules! impl_default_methods {

pub extern "C" fn dumps(
_self: *mut pyo3::ffi::PyObject,
args: *const *mut pyo3::ffi::PyObject,
nargs: pyo3::ffi::Py_ssize_t,
kwnames: *mut pyo3::ffi::PyObject,
args: *mut pyo3::ffi::PyObject,
) -> *mut pyo3::ffi::PyObject {
let inner = || {
let args = FastArgs::new(args, nargs, kwnames);
let args = Args::new(args)?;

if args.num_args() != 1 {
bail!("dumps() requires 1 positional argument");
if args.len() != 1 {
return Err($crate::type_err!(
"dumps() requires 1 positional argument but got {}",
args.len()
));
}

let obj = args.arg(0)?;
let resolved = obj.resolved_object()?;
let resolved = obj.resolved_object().context("invalid argument")?;

$dumps(resolved)
};
Expand All @@ -147,12 +159,18 @@ macro_rules! impl_default_methods {

pub extern "C" fn loads(
_self: *mut pyo3::ffi::PyObject,
args: *const *mut pyo3::ffi::PyObject,
nargs: pyo3::ffi::Py_ssize_t,
kwnames: *mut pyo3::ffi::PyObject,
args: *mut pyo3::ffi::PyObject,
) -> *mut pyo3::ffi::PyObject {
let inner = || {
let args = FastArgs::new(args, nargs, kwnames);
let args = Args::new(args)?;

if args.len() != 1 {
return Err($crate::type_err!(
"loads() requires 1 positional argument but got {}",
args.len()
));
}

let obj = args.arg(0)?;
$loads(obj)
};
Expand All @@ -169,8 +187,8 @@ macro_rules! impl_default_methods {
module!(
$module_name,
exception!($exception_type),
method_fastcall!(loads, ""),
method_fastcall!(dumps, ""),
method_varargs!(loads, ""),
method_varargs!(dumps, ""),
method_varargs!(loads_as, "")
);
};
Expand Down
Loading