1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
#![recursion_limit = "128"]
#![feature(proc_macro_span)]
extern crate proc_macro;
use self::embed_python::EmbedPython;
use proc_macro::TokenStream as TokenStream1;
use proc_macro2::{Span, TokenStream};
use pyo3::{ffi, AsPyPointer, PyErr, PyObject, Python};
use quote::quote;
use std::os::raw::c_char;
use std::ptr::NonNull;
macro_rules! error {
($format:literal $($tokens:tt)*) => ( syn::Error::new(proc_macro2::Span::call_site(), format!($format $($tokens)*)) );
($span:expr, $format:literal $($tokens:tt)*) => ( syn::Error::new($span, format!($format $($tokens)*)) );
}
mod embed_python;
fn python_impl(input: TokenStream) -> syn::Result<TokenStream> {
let tokens = input.clone();
check_no_attribute(input.clone())?;
let mut filename = input.clone().into_iter().next().map_or_else(
|| String::from("<unknown>"),
|t| t.span().unwrap().source_file().path().to_string_lossy().into_owned(),
);
let mut x = EmbedPython::new();
x.add(input)?;
let EmbedPython { mut python, variables, .. } = x;
python.push('\0');
filename.push('\0');
let compiled = unsafe {
let gil = Python::acquire_gil();
let py = gil.python();
let compiled_code = match NonNull::new(ffi::Py_CompileString(as_c_str(&python), as_c_str(&filename), ffi::Py_file_input)) {
None => return Err(compile_error_msg(py, tokens)),
Some(x) => PyObject::from_owned_ptr(py, x.as_ptr()),
};
python_marshal_object_to_bytes(py, &compiled_code)
.map_err(|_e| error!("failed to generate python byte-code"))?
};
let compiled = syn::LitByteStr::new(&compiled, proc_macro2::Span::call_site());
Ok(quote! {
::inline_python::FromInlinePython::from_python_macro(
#compiled,
|globals| { #variables },
)
})
}
fn check_no_attribute(input: TokenStream) -> syn::Result<()> {
let mut input = input.into_iter();
if let Some(token) = input.next() {
if token.to_string() == "#"
&& input.next().map_or(false, |t| t.to_string() == "!")
&& input.next().map_or(false, |t| t.to_string().starts_with('['))
{
return Err(error!(
token.span(),
"Attributes in python!{{}} are no longer supported. \
Use context.run(python!{{..}}) to use a context."
));
}
}
Ok(())
}
#[proc_macro]
pub fn python(input: TokenStream1) -> TokenStream1 {
TokenStream1::from(match python_impl(TokenStream::from(input)) {
Ok(tokens) => tokens,
Err(error) => error.to_compile_error(),
})
}
unsafe fn as_c_str<T: AsRef<[u8]> + ?Sized>(value: &T) -> *const c_char {
std::ffi::CStr::from_bytes_with_nul_unchecked(value.as_ref()).as_ptr()
}
extern "C" {
fn PyMarshal_WriteObjectToString(object: *mut ffi::PyObject, version: std::os::raw::c_int) -> *mut ffi::PyObject;
}
fn python_marshal_object_to_bytes(py: Python, object: &PyObject) -> pyo3::PyResult<Vec<u8>> {
unsafe {
let bytes = PyMarshal_WriteObjectToString(object.as_ptr(), 2);
if bytes.is_null() {
return Err(PyErr::fetch(py));
}
let mut buffer = std::ptr::null_mut();
let mut size = 0isize;
ffi::PyBytes_AsStringAndSize(bytes, &mut buffer, &mut size);
let result = Vec::from(std::slice::from_raw_parts(buffer as *const u8, size as usize));
ffi::Py_DecRef(bytes);
Ok(result)
}
}
unsafe fn py_unicode_string(object: *mut ffi::PyObject) -> String {
let mut size = 0isize;
let data = ffi::PyUnicode_AsUTF8AndSize(object, &mut size) as *const u8;
let data = std::slice::from_raw_parts(data, size as usize);
let data = std::str::from_utf8_unchecked(data);
String::from(data)
}
fn python_str(object: &PyObject) -> String {
unsafe {
let string = ffi::PyObject_Str(object.as_ptr());
let result = py_unicode_string(string);
ffi::Py_DecRef(string);
result
}
}
fn err_value_object(py: Python, value: pyo3::PyErrValue) -> Option<PyObject> {
match value {
pyo3::PyErrValue::None => None,
pyo3::PyErrValue::Value(x) => Some(x),
pyo3::PyErrValue::ToArgs(x) => Some(x.arguments(py)),
pyo3::PyErrValue::ToObject(x) => Some(x.to_object(py)),
}
}
fn compile_error_msg(py: Python, tokens: TokenStream) -> syn::Error {
use pyo3::type_object::PyTypeObject;
use pyo3::AsPyRef;
if !PyErr::occurred(py) {
return error!("failed to compile python code, but no detailed error is available");
}
let error = PyErr::fetch(py);
if error.matches(py, pyo3::exceptions::SyntaxError::type_object()) {
let PyErr {
ptype: kind,
pvalue: value,
..
} = error;
let value = match err_value_object(py, value) {
None => return error!("python: {}", kind.as_ref(py).name()),
Some(x) => x,
};
return match value.extract::<(String, (String, i32, i32, String))>(py) {
Ok((msg, (file, line, col, _token))) => match span_for_line(tokens, line as usize, col as usize) {
Some(span) => error!(span, "python: {}", msg),
None => error!("python: {} at {}:{}:{}", msg, file, line, col),
},
Err(_) => error!("python: {}", python_str(&value)),
};
}
let PyErr {
ptype: kind,
pvalue: value,
..
} = error;
let message = match err_value_object(py, value) {
None => kind.as_ref(py).name().into_owned(),
Some(x) => python_str(&x),
};
error!("python: {}", message)
}
fn span_for_line(input: TokenStream, line: usize, _col: usize) -> Option<Span> {
let mut spans = input
.into_iter()
.map(|x| x.span().unwrap())
.skip_while(|span| span.start().line < line)
.take_while(|span| span.start().line == line);
let mut result = spans.next()?;
for span in spans {
result = match result.join(span) {
None => return Some(Span::from(result)),
Some(span) => span,
}
}
Some(Span::from(result))
}