Skip to content

Commit

Permalink
Fixed up documentation links, tidied up
Browse files Browse the repository at this point in the history
  • Loading branch information
davidcole1340 committed Oct 7, 2021
1 parent 987eddd commit e35e3df
Show file tree
Hide file tree
Showing 37 changed files with 777 additions and 172 deletions.
2 changes: 1 addition & 1 deletion crates/macros/src/function.rs
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ pub fn parser(args: AttributeArgs, input: ItemFn) -> Result<(TokenStream, Functi
#input

#[doc(hidden)]
pub extern "C" fn #internal_ident(ex: &mut ::ext_php_rs::zend::ExecutionData, retval: &mut ::ext_php_rs::types::Zval) {
pub extern "C" fn #internal_ident(ex: &mut ::ext_php_rs::zend::ExecuteData, retval: &mut ::ext_php_rs::types::Zval) {
use ::ext_php_rs::convert::IntoZval;

#(#arg_definitions)*
Expand Down
4 changes: 2 additions & 2 deletions crates/macros/src/method.rs
Original file line number Diff line number Diff line change
Expand Up @@ -154,7 +154,7 @@ pub fn parser(input: &mut ImplItemMethod, rename_rule: RenameRule) -> Result<Par

#[doc(hidden)]
pub fn #internal_ident(
ex: &mut ::ext_php_rs::zend::ExecutionData
ex: &mut ::ext_php_rs::zend::ExecuteData
) -> ::ext_php_rs::class::ConstructorResult<Self> {
use ::ext_php_rs::convert::IntoZval;
use ::ext_php_rs::class::ConstructorResult;
Expand All @@ -171,7 +171,7 @@ pub fn parser(input: &mut ImplItemMethod, rename_rule: RenameRule) -> Result<Par

#[doc(hidden)]
pub extern "C" fn #internal_ident(
ex: &mut ::ext_php_rs::zend::ExecutionData,
ex: &mut ::ext_php_rs::zend::ExecuteData,
retval: &mut ::ext_php_rs::types::Zval
) {
use ::ext_php_rs::convert::IntoZval;
Expand Down
2 changes: 1 addition & 1 deletion src/args.rs
Original file line number Diff line number Diff line change
Expand Up @@ -204,7 +204,7 @@ impl<'a, 'b> ArgParser<'a, 'b> {
}

/// Uses the argument parser to parse the arguments contained in the given
/// `ExecutionData` object. Returns successfully if the arguments were
/// `ExecuteData` object. Returns successfully if the arguments were
/// parsed.
///
/// This function can only be safely called from within an exported PHP
Expand Down
2 changes: 1 addition & 1 deletion src/boxed.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
//! returns a [`ZBox<ZendStr>`].
//!
//! [memory arenas]: https://en.wikipedia.org/wiki/Region-based_memory_management
//! [`ZendStr`]: super::types::string::ZendStr
//! [`ZendStr`]: crate::types::ZendStr
//! [`emalloc`]: super::alloc::efree
use std::{
Expand Down
30 changes: 9 additions & 21 deletions src/builders/class.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use std::{alloc::Layout, ffi::CString};
use std::{ffi::CString, mem::MaybeUninit};

use crate::{
builders::FunctionBuilder,
Expand All @@ -12,13 +12,13 @@ use crate::{
},
flags::{ClassFlags, MethodFlags, PropertyFlags},
types::{ZendClassObject, ZendObject, ZendStr, Zval},
zend::{ClassEntry, ExecutionData, FunctionEntry},
zend::{ClassEntry, ExecuteData, FunctionEntry},
};

/// Builds a class to be exported as a PHP class.
/// Builder for registering a class in PHP.
pub struct ClassBuilder {
name: String,
ptr: &'static mut ClassEntry,
ptr: Box<ClassEntry>,
extends: Option<&'static ClassEntry>,
interfaces: Vec<&'static ClassEntry>,
methods: Vec<FunctionEntry>,
Expand All @@ -34,16 +34,10 @@ impl ClassBuilder {
/// # Parameters
///
/// * `name` - The name of the class.
#[allow(clippy::unwrap_used)]
pub fn new<T: Into<String>>(name: T) -> Self {
// SAFETY: Allocating temporary class entry. Will return a null-ptr if
// allocation fails, which will cause the program to panic (standard in
// Rust). Unwrapping is OK - the ptr will either be valid or null.
let ptr = unsafe {
(std::alloc::alloc_zeroed(Layout::new::<ClassEntry>()) as *mut ClassEntry)
.as_mut()
.unwrap()
};
// SAFETY: A zeroed class entry is in an initalized state, as it is a raw C type
// whose fields do not have a drop implementation.
let ptr = unsafe { Box::new(MaybeUninit::zeroed().assume_init()) };

Self {
name: name.into(),
Expand Down Expand Up @@ -175,7 +169,7 @@ impl ClassBuilder {
obj.into_raw().get_mut_zend_obj()
}

extern "C" fn constructor<T: RegisteredClass>(ex: &mut ExecutionData, _: &mut Zval) {
extern "C" fn constructor<T: RegisteredClass>(ex: &mut ExecuteData, _: &mut Zval) {
let ConstructorMeta { constructor, .. } = match T::CONSTRUCTOR {
Some(c) => c,
None => {
Expand Down Expand Up @@ -239,7 +233,7 @@ impl ClassBuilder {

let class = unsafe {
zend_register_internal_class_ex(
self.ptr,
self.ptr.as_mut(),
match self.extends {
Some(ptr) => (ptr as *const _) as *mut _,
None => std::ptr::null_mut(),
Expand All @@ -249,12 +243,6 @@ impl ClassBuilder {
.ok_or(Error::InvalidPointer)?
};

// SAFETY: We allocated memory for this pointer in `new`, so it is our job to
// free it when the builder has finished.
unsafe {
std::alloc::dealloc((self.ptr as *mut _) as *mut u8, Layout::new::<ClassEntry>())
};

for iface in self.interfaces {
unsafe { zend_do_implement_interface(class, std::mem::transmute(iface)) };
}
Expand Down
10 changes: 6 additions & 4 deletions src/builders/function.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,17 @@ use crate::{
error::{Error, Result},
flags::DataType,
types::Zval,
zend::{ExecutionData, FunctionEntry, ZendType},
zend::{ExecuteData, FunctionEntry, ZendType},
};
use std::{ffi::CString, mem, ptr};

/// Function representation in Rust.
pub type FunctionHandler = extern "C" fn(execute_data: &mut ExecutionData, retval: &mut Zval);
pub type FunctionHandler = extern "C" fn(execute_data: &mut ExecuteData, retval: &mut Zval);

/// Function representation in Rust using pointers.
type FunctionPointerHandler = extern "C" fn(execute_data: *mut ExecutionData, retval: *mut Zval);
type FunctionPointerHandler = extern "C" fn(execute_data: *mut ExecuteData, retval: *mut Zval);

/// Builds a function to be exported as a PHP function.
/// Builder for registering a function in PHP.
#[derive(Debug)]
pub struct FunctionBuilder<'a> {
name: String,
Expand All @@ -39,6 +39,8 @@ impl<'a> FunctionBuilder<'a> {
name: name.into(),
function: FunctionEntry {
fname: ptr::null(),
// SAFETY: `*mut T` and `&mut T` have the same ABI as long as `*mut T` is non-null,
// aligned and pointing to a `T`. PHP guarantees that these conditions will be met.
handler: Some(unsafe {
mem::transmute::<FunctionHandler, FunctionPointerHandler>(handler)
}),
Expand Down
3 changes: 3 additions & 0 deletions src/builders/mod.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
//! Structures that are used to construct other, more complicated types.
//! Generally zero-cost abstractions.
mod class;
mod function;
mod module;
Expand Down
9 changes: 5 additions & 4 deletions src/builders/module.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,9 @@ use std::{
mem, ptr,
};

/// Builds a Zend extension. Must be called from within an external function
/// called `get_module`, returning a mutable pointer to a `ModuleEntry`.
/// Builds a Zend module extension to be registered with PHP. Must be called
/// from within an external function called `get_module`, returning a mutable
/// pointer to a `ModuleEntry`.
///
/// ```
/// use ext_php_rs::{
Expand Down Expand Up @@ -49,8 +50,7 @@ impl ModuleBuilder {
/// # Arguments
///
/// * `name` - The name of the extension.
/// * `version` - The current version of the extension. TBD: Deprecate in
/// favour of the `Cargo.toml` version?
/// * `version` - The current version of the extension.
pub fn new<T: Into<String>, U: Into<String>>(name: T, version: U) -> Self {
Self {
name: name.into(),
Expand Down Expand Up @@ -165,5 +165,6 @@ impl ModuleBuilder {

/// A function to be called when the extension is starting up or shutting down.
pub type StartupShutdownFunc = extern "C" fn(_type: i32, _module_number: i32) -> i32;

/// A function to be called when `phpinfo();` is called.
pub type InfoFunc = extern "C" fn(zend_module: *mut ModuleEntry);
23 changes: 15 additions & 8 deletions src/class.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
//! Types and traits used for registering classes with PHP.
use std::{
collections::HashMap,
marker::PhantomData,
Expand All @@ -11,7 +13,7 @@ use crate::{
exception::PhpException,
props::Property,
types::ZendClassObject,
zend::{ClassEntry, ExecutionData, ZendObjectHandlers},
zend::{ClassEntry, ExecuteData, ZendObjectHandlers},
};

/// Implemented on Rust types which are exported to PHP. Allows users to get and
Expand Down Expand Up @@ -49,8 +51,10 @@ where
/// # Safety
///
/// Caller must guarantee that the object the function is called on is
/// immediately followed by a [`zend_object`], which is true when the
/// immediately followed by a [`ZendObject`], which is true when the
/// object was instantiated by PHP.
///
/// [`ZendObject`]: crate::types::ZendObject
unsafe fn get_property<'a, T: FromZval<'a>>(&'a self, name: &str) -> Option<T> {
let obj = ZendClassObject::<Self>::from_obj_ptr(self)?;
obj.std.get_property(name).ok()
Expand All @@ -71,8 +75,10 @@ where
/// # Safety
///
/// Caller must guarantee that the object the function is called on is
/// immediately followed by a [`zend_object`], which is true when the
/// immediately followed by a [`ZendObject`], which is true when the
/// object was instantiated by PHP.
///
/// [`ZendObject`]: crate::types::ZendObject
unsafe fn set_property(&mut self, name: &str, value: impl IntoZval) -> Option<()> {
let obj = ZendClassObject::<Self>::from_obj_ptr(self)?;
obj.std.set_property(name, value).ok()?;
Expand All @@ -87,10 +93,11 @@ where
fn get_properties<'a>() -> HashMap<&'static str, Property<'a, Self>>;
}

/// Object constructor metadata.
/// Stores metadata about a classes Rust constructor, including the function
/// pointer and the arguments of the function.
pub struct ConstructorMeta<T> {
/// Constructor function.
pub constructor: fn(&mut ExecutionData) -> ConstructorResult<T>,
pub constructor: fn(&mut ExecuteData) -> ConstructorResult<T>,
/// Function called to build the constructor function. Usually adds
/// arguments.
pub build_fn: fn(FunctionBuilder) -> FunctionBuilder,
Expand Down Expand Up @@ -125,7 +132,7 @@ impl<T> From<T> for ConstructorResult<T> {
}

/// Stores the class entry and handlers for a Rust type which has been exported
/// to PHP.
/// to PHP. Usually allocated statically.
pub struct ClassMetadata<T> {
handlers_init: AtomicBool,
handlers: MaybeUninit<ZendObjectHandlers>,
Expand Down Expand Up @@ -195,10 +202,10 @@ impl<T: RegisteredClass> ClassMetadata<T> {
/// Checks if the handlers have been initialized, and initializes them if
/// they are not.
fn check_handlers(&self) {
if !self.handlers_init.load(Ordering::Acquire) {
if !self.handlers_init.load(Ordering::SeqCst) {
// SAFETY: `MaybeUninit` has the same size as the handlers.
unsafe { ZendObjectHandlers::init::<T>(self.handlers.as_ptr() as *mut _) };
self.handlers_init.store(true, Ordering::Release);
self.handlers_init.store(true, Ordering::SeqCst);
}
}
}
8 changes: 4 additions & 4 deletions src/closure.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
//! Types ans functions used for exporting Rust closures to PHP.
//! Types and functions used for exporting Rust closures to PHP.
use std::collections::HashMap;

Expand All @@ -11,7 +11,7 @@ use crate::{
flags::{DataType, MethodFlags},
props::Property,
types::Zval,
zend::ExecutionData,
zend::ExecuteData,
};

/// Class entry and handlers for Rust closures.
Expand Down Expand Up @@ -138,7 +138,7 @@ impl Closure {
}

/// External function used by the Zend interpreter to call the closure.
extern "C" fn invoke(ex: &mut ExecutionData, ret: &mut Zval) {
extern "C" fn invoke(ex: &mut ExecuteData, ret: &mut Zval) {
let (parser, this) = ex.parser_method::<Self>();
let this = this.expect("Internal closure function called on non-closure class");

Expand All @@ -164,7 +164,7 @@ class_derives!(Closure);
///
/// Types must implement the `invoke` function which will be called when the
/// closure is called from PHP. Arguments must be parsed from the
/// [`ExecutionData`] and the return value is returned through the [`Zval`].
/// [`ExecuteData`] and the return value is returned through the [`Zval`].
///
/// This trait is automatically implemented on functions with up to 8
/// parameters.
Expand Down
3 changes: 2 additions & 1 deletion src/constant.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
//! Types relating to registering constants in PHP.
//! Types and traits for registering constants in PHP.
use std::ffi::CString;

Expand All @@ -9,6 +9,7 @@ use crate::ffi::{
zend_register_string_constant,
};

/// Implemented on types which can be registered as a constant in PHP.
pub trait IntoConst: Sized {
/// Registers a global module constant in PHP, with the value as the content
/// of self. This function _must_ be called in the module startup
Expand Down
4 changes: 4 additions & 0 deletions src/convert.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
//! Traits used to convert between Zend/PHP and Rust types.
use crate::{
boxed::ZBox,
error::Result,
Expand Down Expand Up @@ -111,6 +113,8 @@ pub trait IntoZendObject {
/// Alternative to the built-in Rust [`From`] and [`TryFrom`] implementations,
/// allowing the caller to specify whether the Zval contents will persist
/// between requests.
///
/// [`TryFrom`]: std::convert::TryFrom
pub trait IntoZval: Sized {
/// The corresponding type of the implemented value in PHP.
const TYPE: DataType;
Expand Down
7 changes: 6 additions & 1 deletion src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,18 @@
use std::{error::Error as ErrorTrait, ffi::NulError, fmt::Display};

use crate::{
boxed::ZBox,
exception::PhpException,
flags::{ClassFlags, DataType, ZvalTypeFlags},
types::ZendObject,
};

/// The main result type which is passed by the library.
pub type Result<T, E = Error> = std::result::Result<T, E>;

/// The main error type which is passed by the library inside the custom
/// [`Result`] type.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
#[derive(Debug)]
#[non_exhaustive]
pub enum Error {
/// An incorrect number of arguments was given to a PHP function.
Expand Down Expand Up @@ -52,6 +54,8 @@ pub enum Error {
InvalidException(ClassFlags),
/// Converting integer arguments resulted in an overflow.
IntegerOverflow,
/// An exception was thrown in a function.
Exception(ZBox<ZendObject>),
}

impl Display for Error {
Expand Down Expand Up @@ -85,6 +89,7 @@ impl Display for Error {
Error::IntegerOverflow => {
write!(f, "Converting integer arguments resulted in an overflow.")
}
Error::Exception(e) => write!(f, "Exception was thrown: {:?}", e),
}
}
}
Expand Down
2 changes: 1 addition & 1 deletion src/exception.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
//! Contains all the base PHP throwables, including `Throwable` and `Exception`.
//! Types and functions used for throwing exceptions from Rust to PHP.
use std::ffi::CString;

Expand Down
2 changes: 1 addition & 1 deletion src/ffi.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
//! Raw FFI bindings to the PHP API.
//! Raw FFI bindings to the Zend API.
#![allow(clippy::all)]
#![allow(warnings)]
Expand Down
2 changes: 1 addition & 1 deletion src/flags.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
//! Bitflags used in PHP and the Zend engine.
//! Flags and enums used in PHP and the Zend engine.
use bitflags::bitflags;

Expand Down
8 changes: 5 additions & 3 deletions src/internal.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
/// Called by startup functions registered with the `#[php_startup]` macro.
/// Initializes all classes that are defined by ext-php-rs (i.e. [`Closure`]).
//! Internal, public functions that are called from downstream extensions.
/// Called by startup functions registered with the [`#[php_startup]`] macro.
/// Initializes all classes that are defined by ext-php-rs (i.e. `Closure`).
///
/// [`Closure`]: ext_php_rs::php::types::closure::Closure
/// [`#[php_startup]`]: crate::php_startup
#[inline(always)]
pub fn ext_php_rs_startup() {
#[cfg(feature = "closure")]
Expand Down
Loading

0 comments on commit e35e3df

Please sign in to comment.