2015-04-19 03:22:03 +00:00
|
|
|
// Copyright (c) 2015 Daniel Grunwald
|
|
|
|
//
|
|
|
|
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
|
|
|
|
// software and associated documentation files (the "Software"), to deal in the Software
|
|
|
|
// without restriction, including without limitation the rights to use, copy, modify, merge,
|
|
|
|
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
|
|
|
|
// to whom the Software is furnished to do so, subject to the following conditions:
|
|
|
|
//
|
|
|
|
// The above copyright notice and this permission notice shall be included in all copies or
|
|
|
|
// substantial portions of the Software.
|
|
|
|
//
|
|
|
|
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
|
|
|
|
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
|
|
|
|
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
|
|
|
|
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
|
|
|
|
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
|
|
|
|
// DEALINGS IN THE SOFTWARE.
|
|
|
|
|
2015-04-17 20:13:15 +00:00
|
|
|
#![feature(unsafe_no_drop_flag)] // crucial so that PyObject<'p> is binary compatible with *mut ffi::PyObject
|
2016-03-04 23:13:38 +00:00
|
|
|
#![feature(filling_drop)] // necessary to avoid segfault with unsafe_no_drop_flag (#5016)
|
|
|
|
#![feature(optin_builtin_traits)] // for opting out of Sync/Send (#13231)
|
|
|
|
#![feature(stmt_expr_attributes)] // easier python 2.x/3.x distinction (#15701)
|
2016-03-05 00:16:54 +00:00
|
|
|
#![feature(const_fn)] // for GILProtected::new (#24111)
|
2016-03-05 01:01:03 +00:00
|
|
|
#![feature(shared)] // for std::ptr::Shared (#27730)
|
2016-03-04 23:13:38 +00:00
|
|
|
|
|
|
|
#![feature(plugin)] // necessary because `fn concat_idents!(...)()` is
|
|
|
|
#![plugin(interpolate_idents)] // not supported by the current macro system.
|
|
|
|
|
2015-06-27 21:49:53 +00:00
|
|
|
#![allow(unused_imports)] // because some imports are only necessary with python 2.x or 3.x
|
2015-01-05 16:05:53 +00:00
|
|
|
|
2015-06-27 20:45:35 +00:00
|
|
|
//! Rust bindings to the Python interpreter.
|
2015-04-18 20:20:19 +00:00
|
|
|
//!
|
2015-04-18 22:39:04 +00:00
|
|
|
//! # Ownership and Lifetimes
|
2015-06-27 20:45:35 +00:00
|
|
|
//! In Python, all objects are implicitly reference counted.
|
|
|
|
//! In rust, we will use the `PyObject` type to represent a reference to a Python object.
|
2015-04-18 22:39:04 +00:00
|
|
|
//!
|
2015-10-26 22:52:18 +00:00
|
|
|
//! The method `clone_ref()` (from trait `PyClone`) can be used to create additional
|
|
|
|
//! references to the same Python object.
|
|
|
|
//!
|
2016-01-29 03:13:39 +00:00
|
|
|
//! Because all Python objects potentially have multiple owners, the
|
2015-10-26 22:52:18 +00:00
|
|
|
//! concept of Rust mutability does not apply to Python objects.
|
2015-06-27 20:45:35 +00:00
|
|
|
//! As a result, this API will allow mutating Python objects even if they are not stored
|
2015-10-26 22:52:18 +00:00
|
|
|
//! in a mutable Rust variable.
|
2015-04-18 22:39:04 +00:00
|
|
|
//!
|
2015-06-27 20:45:35 +00:00
|
|
|
//! The Python interpreter uses a global interpreter lock (GIL)
|
2015-04-18 22:39:04 +00:00
|
|
|
//! to ensure thread-safety.
|
2015-10-26 22:52:18 +00:00
|
|
|
//! This API uses a zero-sized `struct Python<'p>` as a token to indicate
|
|
|
|
//! that a function can assume that the GIL is held.
|
2015-04-18 22:39:04 +00:00
|
|
|
//!
|
2015-10-26 22:52:18 +00:00
|
|
|
//! You obtain a `Python` instance by acquiring the GIL,
|
|
|
|
//! and have to pass it into all operations that call into the Python runtime.
|
2015-04-18 22:39:04 +00:00
|
|
|
//!
|
|
|
|
//! # Error Handling
|
2015-10-26 22:52:18 +00:00
|
|
|
//! The vast majority of operations in this library will return `PyResult<...>`.
|
|
|
|
//! This is an alias for the type `Result<..., PyErr>`.
|
2015-04-18 22:39:04 +00:00
|
|
|
//!
|
2015-06-27 20:45:35 +00:00
|
|
|
//! A `PyErr` represents a Python exception. Errors within the rust-cpython library are
|
|
|
|
//! also exposed as Python exceptions.
|
2015-04-18 22:39:04 +00:00
|
|
|
//!
|
2015-04-18 20:20:19 +00:00
|
|
|
//! # Example
|
|
|
|
//! ```
|
2015-04-18 22:39:04 +00:00
|
|
|
//! extern crate cpython;
|
2015-04-18 20:20:19 +00:00
|
|
|
//!
|
2015-04-18 22:39:04 +00:00
|
|
|
//! use cpython::{PythonObject, Python};
|
2015-07-27 18:56:59 +00:00
|
|
|
//! use cpython::ObjectProtocol; //for call method
|
|
|
|
//!
|
2015-04-18 20:20:19 +00:00
|
|
|
//! fn main() {
|
2015-07-27 18:56:59 +00:00
|
|
|
//! let gil = Python::acquire_gil();
|
2015-10-26 22:52:18 +00:00
|
|
|
//! let py = gil.python(); // obtain `Python` token
|
2015-07-27 18:56:59 +00:00
|
|
|
//!
|
2015-04-18 20:20:19 +00:00
|
|
|
//! let sys = py.import("sys").unwrap();
|
2015-10-26 22:52:18 +00:00
|
|
|
//! let version: String = sys.get(py, "version").unwrap().extract(py).unwrap();
|
2015-07-27 18:56:59 +00:00
|
|
|
//!
|
|
|
|
//! let os = py.import("os").unwrap();
|
2015-10-26 22:52:18 +00:00
|
|
|
//! let getenv = os.get(py, "getenv").unwrap();
|
|
|
|
//! let user: String = getenv.call(py, ("USER",), None).unwrap().extract(py).unwrap();
|
2015-07-27 18:56:59 +00:00
|
|
|
//!
|
|
|
|
//! println!("Hello {}, I'm Python {}", user, version);
|
2015-04-18 20:20:19 +00:00
|
|
|
//! }
|
|
|
|
//! ```
|
|
|
|
|
2015-01-05 16:05:53 +00:00
|
|
|
extern crate libc;
|
2015-05-19 21:32:32 +00:00
|
|
|
|
2015-06-20 14:02:09 +00:00
|
|
|
extern crate abort_on_panic;
|
|
|
|
|
2015-05-19 21:32:32 +00:00
|
|
|
#[cfg(feature="python27-sys")]
|
2015-03-09 13:31:20 +00:00
|
|
|
extern crate python27_sys as ffi;
|
2015-05-19 21:32:32 +00:00
|
|
|
|
|
|
|
#[cfg(feature="python3-sys")]
|
|
|
|
extern crate python3_sys as ffi;
|
|
|
|
|
2015-01-05 16:05:53 +00:00
|
|
|
pub use ffi::Py_ssize_t;
|
|
|
|
pub use err::{PyErr, PyResult};
|
2015-01-05 16:02:30 +00:00
|
|
|
pub use objects::*;
|
2015-10-25 16:55:29 +00:00
|
|
|
pub use python::{Python, PythonObject, PythonObjectWithCheckedDowncast, PythonObjectWithTypeObject, PyClone, PyDrop};
|
2015-06-21 22:35:01 +00:00
|
|
|
pub use pythonrun::{GILGuard, GILProtected, prepare_freethreaded_python};
|
2015-07-18 20:39:55 +00:00
|
|
|
pub use conversion::{ExtractPyObject, ToPyObject};
|
2015-01-04 20:37:43 +00:00
|
|
|
pub use objectprotocol::{ObjectProtocol};
|
2015-06-21 22:35:01 +00:00
|
|
|
pub use rustobject::{PyRustType, PyRustObject};
|
|
|
|
pub use rustobject::typebuilder::PyRustTypeBuilder;
|
2015-03-08 14:29:44 +00:00
|
|
|
|
2015-06-28 16:55:20 +00:00
|
|
|
#[cfg(feature="python27-sys")]
|
|
|
|
#[allow(non_camel_case_types)]
|
|
|
|
pub type Py_hash_t = libc::c_long;
|
|
|
|
|
|
|
|
#[cfg(feature="python3-sys")]
|
|
|
|
#[allow(non_camel_case_types)]
|
|
|
|
pub type Py_hash_t = ffi::Py_hash_t;
|
|
|
|
|
2015-06-24 22:02:56 +00:00
|
|
|
use std::ptr;
|
|
|
|
|
2015-04-18 20:20:19 +00:00
|
|
|
/// Constructs a `&'static CStr` literal.
|
2015-03-08 14:29:44 +00:00
|
|
|
macro_rules! cstr(
|
|
|
|
($s: tt) => (
|
|
|
|
// TODO: verify that $s is a string literal without nuls
|
|
|
|
unsafe {
|
|
|
|
::std::ffi::CStr::from_ptr(concat!($s, "\0").as_ptr() as *const _)
|
|
|
|
}
|
|
|
|
);
|
|
|
|
);
|
2015-01-05 16:05:53 +00:00
|
|
|
|
|
|
|
mod python;
|
|
|
|
mod err;
|
2015-01-04 23:07:31 +00:00
|
|
|
mod conversion;
|
2015-01-05 16:02:30 +00:00
|
|
|
mod objects;
|
2015-01-04 20:37:43 +00:00
|
|
|
mod objectprotocol;
|
2015-01-05 16:05:53 +00:00
|
|
|
mod pythonrun;
|
2015-08-02 22:06:15 +00:00
|
|
|
pub mod argparse;
|
2015-06-25 21:58:57 +00:00
|
|
|
mod function;
|
2015-05-27 19:19:32 +00:00
|
|
|
mod rustobject;
|
2015-01-05 16:05:53 +00:00
|
|
|
|
2015-04-18 20:20:19 +00:00
|
|
|
/// Private re-exports for macros. Do not use.
|
2015-04-18 22:39:04 +00:00
|
|
|
#[doc(hidden)]
|
2015-04-18 18:17:25 +00:00
|
|
|
pub mod _detail {
|
2016-03-04 20:35:52 +00:00
|
|
|
pub mod ffi {
|
|
|
|
pub use ::ffi::*;
|
|
|
|
}
|
|
|
|
pub mod libc {
|
|
|
|
pub use ::libc::c_char;
|
|
|
|
}
|
2015-06-20 14:02:09 +00:00
|
|
|
pub use abort_on_panic::PanicGuard;
|
2015-04-18 18:17:25 +00:00
|
|
|
pub use err::from_owned_ptr_or_panic;
|
2016-03-05 14:05:41 +00:00
|
|
|
pub use function::{get_kwargs, result_to_ptr, py_fn_impl};
|
2015-06-26 01:31:35 +00:00
|
|
|
pub use rustobject::method::{py_method_impl, py_class_method_impl};
|
2015-06-24 22:02:56 +00:00
|
|
|
|
|
|
|
/// assume_gil_acquired(), but the returned Python<'p> is bounded by the scope
|
|
|
|
/// of the referenced variable.
|
2015-10-26 22:52:18 +00:00
|
|
|
/// This is useful in macros to ensure that type inference doesn't set `'p` == `'static`.
|
2015-06-24 22:02:56 +00:00
|
|
|
#[inline]
|
2015-06-28 02:12:51 +00:00
|
|
|
pub unsafe fn bounded_assume_gil_acquired<'p, T>(_bound: &'p T) -> super::Python<'p> {
|
2015-06-24 22:02:56 +00:00
|
|
|
super::Python::assume_gil_acquired()
|
|
|
|
}
|
2015-04-18 18:17:25 +00:00
|
|
|
}
|
|
|
|
|
2015-06-27 20:45:35 +00:00
|
|
|
/// Expands to an `extern "C"` function that allows Python to load
|
|
|
|
/// the rust code as a Python extension module.
|
2015-04-18 20:20:19 +00:00
|
|
|
///
|
2015-06-24 22:02:56 +00:00
|
|
|
/// Macro syntax: `py_module_initializer!($name, |$py, $m| $body)`
|
2015-04-18 20:20:19 +00:00
|
|
|
///
|
2015-10-26 22:52:18 +00:00
|
|
|
/// 1. `name`: The module name as a Rust identifier.
|
|
|
|
/// 2. A lambda of type `Fn(Python, &PyModule) -> PyResult<()>`.
|
2015-04-18 20:20:19 +00:00
|
|
|
/// This function will be called when the module is imported, and is responsible
|
|
|
|
/// for adding the module's members.
|
|
|
|
///
|
|
|
|
/// # Example
|
|
|
|
/// ```
|
|
|
|
/// #![crate_type = "dylib"]
|
2015-05-24 18:06:08 +00:00
|
|
|
/// #![feature(plugin)]
|
|
|
|
/// #![plugin(interpolate_idents)]
|
2015-04-18 20:20:19 +00:00
|
|
|
/// #[macro_use] extern crate cpython;
|
2015-08-02 22:06:15 +00:00
|
|
|
/// use cpython::{Python, PyResult, PyObject};
|
2015-04-18 20:20:19 +00:00
|
|
|
///
|
2015-05-24 18:06:08 +00:00
|
|
|
/// py_module_initializer!(example, |py, m| {
|
2015-10-26 22:52:18 +00:00
|
|
|
/// try!(m.add(py, "__doc__", "Module documentation string"));
|
|
|
|
/// try!(m.add(py, "run", py_fn!(run())));
|
2015-04-18 20:20:19 +00:00
|
|
|
/// Ok(())
|
|
|
|
/// });
|
2015-07-27 18:56:59 +00:00
|
|
|
///
|
2015-10-25 16:55:29 +00:00
|
|
|
/// fn run(py: Python) -> PyResult<PyObject> {
|
2015-04-18 20:20:19 +00:00
|
|
|
/// println!("Rust says: Hello Python!");
|
|
|
|
/// Ok(py.None())
|
|
|
|
/// }
|
|
|
|
/// # fn main() {}
|
|
|
|
/// ```
|
|
|
|
/// The code must be compiled into a file `example.so`.
|
|
|
|
///
|
|
|
|
/// ```bash
|
|
|
|
/// rustc example.rs -o example.so
|
|
|
|
/// ```
|
2015-06-27 20:45:35 +00:00
|
|
|
/// It can then be imported into Python:
|
2015-04-18 20:20:19 +00:00
|
|
|
///
|
|
|
|
/// ```python
|
|
|
|
/// >>> import example
|
|
|
|
/// >>> example.run()
|
|
|
|
/// Rust says: Hello Python!
|
|
|
|
/// ```
|
2015-07-27 18:56:59 +00:00
|
|
|
///
|
2015-01-12 02:00:34 +00:00
|
|
|
#[macro_export]
|
2015-05-24 18:06:08 +00:00
|
|
|
#[cfg(feature="python27-sys")]
|
2015-01-12 02:00:34 +00:00
|
|
|
macro_rules! py_module_initializer {
|
2015-06-24 22:02:56 +00:00
|
|
|
($name: ident, |$py_id: ident, $m_id: ident| $body: expr) => ( interpolate_idents! {
|
2015-05-24 18:06:08 +00:00
|
|
|
#[[no_mangle]]
|
|
|
|
#[allow(non_snake_case)]
|
2015-06-24 22:02:56 +00:00
|
|
|
pub unsafe extern "C" fn [ init $name ]() {
|
|
|
|
// Nest init function so that $body isn't in unsafe context
|
2015-10-25 16:55:29 +00:00
|
|
|
fn init($py_id: $crate::Python, $m_id: &$crate::PyModule) -> $crate::PyResult<()> {
|
2015-06-24 22:02:56 +00:00
|
|
|
$body
|
2015-01-12 02:00:34 +00:00
|
|
|
}
|
2015-06-24 22:02:56 +00:00
|
|
|
let name = concat!(stringify!($name), "\0").as_ptr() as *const _;
|
|
|
|
$crate::py_module_initializer_impl(name, init)
|
|
|
|
}
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
#[doc(hidden)]
|
|
|
|
#[cfg(feature="python27-sys")]
|
|
|
|
pub unsafe fn py_module_initializer_impl(
|
|
|
|
name: *const libc::c_char,
|
2015-10-25 16:55:29 +00:00
|
|
|
init: fn(Python, &PyModule) -> PyResult<()>
|
2015-06-24 22:02:56 +00:00
|
|
|
) {
|
|
|
|
abort_on_panic!({
|
|
|
|
let py = Python::assume_gil_acquired();
|
2015-06-27 17:26:36 +00:00
|
|
|
ffi::PyEval_InitThreads();
|
2015-06-24 22:02:56 +00:00
|
|
|
let module = ffi::Py_InitModule(name, ptr::null_mut());
|
|
|
|
if module.is_null() { return; }
|
|
|
|
|
2015-10-25 16:55:29 +00:00
|
|
|
let module = match PyObject::from_borrowed_ptr(py, module).cast_into::<PyModule>(py) {
|
2015-06-24 22:02:56 +00:00
|
|
|
Ok(m) => m,
|
|
|
|
Err(e) => {
|
2015-10-25 16:55:29 +00:00
|
|
|
PyErr::from(e).restore(py);
|
2015-06-24 22:02:56 +00:00
|
|
|
return;
|
|
|
|
}
|
|
|
|
};
|
|
|
|
match init(py, &module) {
|
|
|
|
Ok(()) => (),
|
2015-10-25 16:55:29 +00:00
|
|
|
Err(e) => e.restore(py)
|
2015-01-12 02:00:34 +00:00
|
|
|
}
|
2015-05-24 18:06:08 +00:00
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
#[macro_export]
|
|
|
|
#[cfg(feature="python3-sys")]
|
|
|
|
macro_rules! py_module_initializer {
|
2015-06-24 22:02:56 +00:00
|
|
|
($name: ident, |$py_id: ident, $m_id: ident| $body: expr) => ( interpolate_idents! {
|
2015-05-24 18:06:08 +00:00
|
|
|
#[[no_mangle]]
|
|
|
|
#[allow(non_snake_case)]
|
2015-06-24 22:02:56 +00:00
|
|
|
pub unsafe extern "C" fn [ PyInit_ $name ]() -> *mut $crate::_detail::ffi::PyObject {
|
|
|
|
// Nest init function so that $body isn't in unsafe context
|
2015-10-25 16:55:29 +00:00
|
|
|
fn init($py_id: $crate::Python, $m_id: &$crate::PyModule) -> $crate::PyResult<()> {
|
2015-06-24 22:02:56 +00:00
|
|
|
$body
|
|
|
|
}
|
2015-05-24 18:06:08 +00:00
|
|
|
static mut module_def: $crate::_detail::ffi::PyModuleDef = $crate::_detail::ffi::PyModuleDef {
|
|
|
|
m_base: $crate::_detail::ffi::PyModuleDef_HEAD_INIT,
|
|
|
|
m_name: 0 as *const _,
|
|
|
|
m_doc: 0 as *const _,
|
|
|
|
m_size: 0, // we don't use per-module state
|
|
|
|
m_methods: 0 as *mut _,
|
|
|
|
m_reload: None,
|
|
|
|
m_traverse: None,
|
|
|
|
m_clear: None,
|
|
|
|
m_free: None
|
|
|
|
};
|
|
|
|
// We can't convert &'static str to *const c_char within a static initializer,
|
|
|
|
// so we'll do it here in the module initialization:
|
2015-06-24 22:02:56 +00:00
|
|
|
module_def.m_name = concat!(stringify!($name), "\0").as_ptr() as *const _;
|
|
|
|
$crate::py_module_initializer_impl(&mut module_def, init)
|
|
|
|
}
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
#[doc(hidden)]
|
|
|
|
#[cfg(feature="python3-sys")]
|
|
|
|
pub unsafe fn py_module_initializer_impl(
|
|
|
|
def: *mut ffi::PyModuleDef,
|
2015-10-25 16:55:29 +00:00
|
|
|
init: fn(Python, &PyModule) -> PyResult<()>
|
2015-06-24 22:02:56 +00:00
|
|
|
) -> *mut ffi::PyObject {
|
|
|
|
abort_on_panic!({
|
|
|
|
let py = Python::assume_gil_acquired();
|
2015-06-27 17:26:36 +00:00
|
|
|
ffi::PyEval_InitThreads();
|
2015-06-24 22:02:56 +00:00
|
|
|
let module = ffi::PyModule_Create(def);
|
|
|
|
if module.is_null() { return module; }
|
|
|
|
|
2015-10-25 16:55:29 +00:00
|
|
|
let module = match PyObject::from_owned_ptr(py, module).cast_into::<PyModule>(py) {
|
2015-06-24 22:02:56 +00:00
|
|
|
Ok(m) => m,
|
|
|
|
Err(e) => {
|
2015-10-25 16:55:29 +00:00
|
|
|
PyErr::from(e).restore(py);
|
2015-06-24 22:02:56 +00:00
|
|
|
return ptr::null_mut();
|
2015-05-24 18:06:08 +00:00
|
|
|
}
|
2015-06-24 22:02:56 +00:00
|
|
|
};
|
|
|
|
match init(py, &module) {
|
2015-06-27 17:08:28 +00:00
|
|
|
Ok(()) => module.into_object().steal_ptr(),
|
2015-06-24 22:02:56 +00:00
|
|
|
Err(e) => {
|
2015-10-25 16:55:29 +00:00
|
|
|
e.restore(py);
|
2015-06-24 22:02:56 +00:00
|
|
|
return ptr::null_mut();
|
2015-05-24 18:06:08 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
})
|
2015-01-12 02:00:34 +00:00
|
|
|
}
|