1
1
use std:: io:: Cursor ;
2
2
3
- use crate :: { error:: Error , eval:: cache:: CBNCache , program:: Program } ;
3
+ use crate :: {
4
+ error:: { Error , SerializationError } ,
5
+ eval:: cache:: CBNCache ,
6
+ program:: Program ,
7
+ serialize,
8
+ } ;
4
9
5
10
use pyo3:: { create_exception, exceptions:: PyException , prelude:: * } ;
6
11
@@ -10,18 +15,30 @@ impl std::convert::From<Error> for PyErr {
10
15
fn from ( err : Error ) -> PyErr {
11
16
match err {
12
17
// TODO better exceptions
13
- error => NickelException :: new_err ( format ! ( "unexpected error: {error:?}" ) ) ,
18
+ error => NickelException :: new_err ( format ! ( "{error:?}" ) ) ,
14
19
}
15
20
}
16
21
}
17
22
18
- // Some test function
23
+ impl std:: convert:: From < SerializationError > for PyErr {
24
+ fn from ( err : SerializationError ) -> PyErr {
25
+ match err {
26
+ // TODO better exceptions
27
+ error => NickelException :: new_err ( format ! ( "{error:?}" ) ) ,
28
+ }
29
+ }
30
+ }
31
+
32
+ /// Evaluate from a Python str of a Nickel expression to a Python str of the resulting JSON.
19
33
#[ pyfunction]
20
34
pub fn run ( s : String ) -> PyResult < String > {
21
35
let mut program: Program < CBNCache > =
22
36
Program :: new_from_source ( Cursor :: new ( s. to_string ( ) ) , "python" ) ?;
23
- let term = program. eval ( ) ?;
24
- Ok ( term. to_string ( ) )
37
+ let term = program. eval_full ( ) ?;
38
+ serialize:: validate ( serialize:: ExportFormat :: Json , & term) ?;
39
+ let json_string = serialize:: to_string ( serialize:: ExportFormat :: Json , & term) ?;
40
+
41
+ Ok ( json_string)
25
42
}
26
43
27
44
#[ pymodule]
0 commit comments