speedyspec-php 0.8.4

Embedded, statically linked PHP interpreter for speedyspec.
Documentation
//! Assigning through a PHP reference Rust carries ([`speedyspec_hooks::OpaqueWriter`]).
//!
//! An argument array's element that is a PHP reference (`array( &$var )`) reaches Rust as a `Value::Opaque`
//! holding the reference ([`convert::pass_through_slot`]). [`assign`] does what PHP's `$args[0] = $value` does to
//! it: the variable takes the value. A reference to a typed property checks the value against the property's type
//! as a file without `strict_types` does (WordPress's `class-wp-hook.php` has none): a value that fits is coerced,
//! one that does not throws PHP's `TypeError`, which comes back as [`Assigned::Failed`] for the caller to rethrow.

use std::mem::{ManuallyDrop, MaybeUninit};
use std::ptr;

use ext_php_rs::ffi::{ext_php_rs_executor_globals, zend_execute_data, zend_reference, zval};
use ext_php_rs::types::Zval;
use speedyspec_hooks::{Assigned, Value};

use crate::boundary::{self, CallError, ENGINE, guard, take_thrown};
use crate::convert::{self, ZvalHandle};
use crate::runtime::{PhpError, failure_of};

// `ZEND_API zend_result zend_try_assign_typed_ref_ex(zend_reference *ref, zval *zv, bool strict)`, a symbol of the
// linked libphp: assigns `zv` (whose reference it takes) to the reference, checking the types of the properties
// the reference is held by; on failure it releases `zv`, throws a `TypeError` and returns FAILURE (-1).
unsafe extern "C" {
    fn zend_try_assign_typed_ref_ex(
        reference: *mut zend_reference,
        zv: *mut zval,
        strict: bool,
    ) -> i32;
}

/// `$target = $value` through the PHP reference `target` holds; [`Assigned::NotAReference`] for anything else.
pub(crate) fn assign(target: &dyn std::any::Any, value: &Value) -> Assigned {
    let Some(handle) = target.downcast_ref::<ZvalHandle>() else {
        return Assigned::NotAReference;
    };
    if !handle.is_reference() || !boundary::alive() {
        return Assigned::NotAReference;
    }
    let mut fresh = ManuallyDrop::new(Zval::new());
    let fresh_ptr: *mut zval = &raw mut *fresh;
    let dummy_func = ENGINE.with(|e| e.dummy_func.get());
    let written = guard(|| -> Result<(), convert::Unconvertible> {
        // SAFETY: `fresh` is zval storage owned by this frame; the handle keeps the reference alive. The dummy frame
        // (a TypeError needs a frame to be thrown from, as in `call_php`) lives in this closure's frame for the
        // duration of the assignment; a bailout resets EG(current_execute_data) itself.
        unsafe {
            convert::write_value(fresh_ptr, value)?;
            let reference = (*handle.raw_ptr()).value.ref_;
            let eg = ext_php_rs_executor_globals();
            let mut dummy = MaybeUninit::<zend_execute_data>::zeroed();
            let installed = (*eg).current_execute_data.is_null();
            if installed {
                (*dummy.as_mut_ptr()).func = dummy_func;
                (*eg).current_execute_data = dummy.as_mut_ptr();
            }
            // The reference to the written value moves into the variable (or is released on failure).
            zend_try_assign_typed_ref_ex(reference, fresh_ptr, false);
            if installed {
                (*eg).current_execute_data = ptr::null_mut();
            }
            Ok(())
        }
    });
    match written {
        Ok(Ok(())) => match take_thrown() {
            None => Assigned::Done,
            Some(thrown) => failed(CallError::Thrown(thrown)),
        },
        Ok(Err(why)) => {
            // Nothing was assigned; the partly written value is released.
            boundary::release_later(fresh);
            failed(CallError::Convert(why.to_string()))
        }
        Err(interrupted) => failed(CallError::Interrupted(interrupted)),
    }
}

fn failed(err: CallError) -> Assigned {
    let failure = failure_of(err);
    let message = match &failure.error {
        PhpError::Exception { message, .. } => message.clone(),
        other => other.to_string(),
    };
    Assigned::Failed {
        message,
        thrown: failure.exception,
    }
}