Skip to content

refactor!(macro) use outer macro pattern for modules #342

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 8 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 12 additions & 15 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,22 +19,19 @@ Export a simple function `function hello_world(string $name): string` to PHP:
```rust
#![cfg_attr(windows, feature(abi_vectorcall))]

use ext_php_rs::prelude::*;

/// Gives you a nice greeting!
///
/// @param string $name Your name.
///
/// @return string Nice greeting!
#[php_function]
pub fn hello_world(name: String) -> String {
format!("Hello, {}!", name)
}
use ext_php_rs::php_module;

// Required to register the extension with PHP.
#[php_module]
pub fn module(module: ModuleBuilder) -> ModuleBuilder {
module
mod module {
/// Gives you a nice greeting!
///
/// @param string $name Your name.
///
/// @return string Nice greeting!
#[php_function]
pub fn hello_world(name: String) -> String {
format!("Hello, {}!", name)
}
}
```

Expand Down Expand Up @@ -148,7 +145,7 @@ best resource at the moment. This can be viewed at [docs.rs].
functionality to be cross-platform is on the roadmap.
- To build the application in `DEBUG` mode on Windows,
you must have a `PHP SDK` built with the `DEBUG` option enabled
and specify the `PHP_LIB` to the folder containing the lib files.
and specify the `PHP_LIB` to the folder containing the lib files.
For example: set `PHP_LIB=C:\php-sdk\php-dev\vc16\x64\php-8.3.13-src\x64\Debug_TS`.

[vectorcall]: https://docs.microsoft.com/en-us/cpp/cpp/vectorcall?view=msvc-170
Expand Down
3 changes: 3 additions & 0 deletions crates/macros/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -19,3 +19,6 @@ quote = "1.0.9"
proc-macro2 = "1.0.26"
lazy_static = "1.4.0"
anyhow = "1.0"

[lints.rust]
missing_docs = "warn"
33 changes: 14 additions & 19 deletions crates/macros/src/class.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
use std::collections::HashMap;

use crate::STATE;
use anyhow::{anyhow, bail, Context, Result};
use darling::{FromMeta, ToTokens};
use proc_macro2::{Ident, Span, TokenStream};
Expand Down Expand Up @@ -41,7 +40,7 @@ pub struct AttrArgs {
flags: Option<Expr>,
}

pub fn parser(args: AttributeArgs, mut input: ItemStruct) -> Result<TokenStream> {
pub fn parser(args: AttributeArgs, mut input: ItemStruct) -> Result<(TokenStream, String, Class)> {
let args = AttrArgs::from_list(&args)
.map_err(|e| anyhow!("Unable to parse attribute arguments: {:?}", e))?;

Expand All @@ -52,7 +51,11 @@ pub fn parser(args: AttributeArgs, mut input: ItemStruct) -> Result<TokenStream>

input.attrs = {
let mut unused = vec![];
for attr in input.attrs.into_iter() {
for attr in input
.attrs
.into_iter()
.filter(|a| !a.path.is_ident("php_class"))
{
match parse_attribute(&attr)? {
Some(parsed) => match parsed {
ParsedAttribute::Extends(class) => {
Expand Down Expand Up @@ -132,23 +135,15 @@ pub fn parser(args: AttributeArgs, mut input: ItemStruct) -> Result<TokenStream>
..Default::default()
};

let mut state = STATE.lock();
Ok((
quote! {
#input

if state.built_module {
bail!("The `#[php_module]` macro must be called last to ensure functions and classes are registered.");
}

if state.startup_function.is_some() {
bail!("The `#[php_startup]` macro must be called after all the classes have been defined.");
}

state.classes.insert(ident.to_string(), class);

Ok(quote! {
#input

::ext_php_rs::class_derives!(#ident);
})
::ext_php_rs::class_derives!(#ident);
},
ident.to_string(),
class,
))
}

#[derive(Debug)]
Expand Down
29 changes: 13 additions & 16 deletions crates/macros/src/constant.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,10 @@
use crate::helpers::get_docs;
use anyhow::{bail, Result};
use anyhow::Result;
use darling::ToTokens;
use proc_macro2::TokenStream;
use quote::quote;
use syn::{Expr, ItemConst};

use crate::STATE;

#[derive(Debug)]
pub struct Constant {
pub name: String,
Expand All @@ -15,23 +13,22 @@ pub struct Constant {
pub value: String,
}

pub fn parser(input: ItemConst) -> Result<TokenStream> {
let mut state = STATE.lock();

if state.startup_function.is_some() {
bail!("Constants must be declared before you declare your startup function and module function.");
}

state.constants.push(Constant {
pub fn parser(input: &mut ItemConst) -> Result<(TokenStream, Constant)> {
let constant = Constant {
name: input.ident.to_string(),
docs: get_docs(&input.attrs),
value: input.expr.to_token_stream().to_string(),
});
};

input.attrs.remove(0);

Ok(quote! {
#[allow(dead_code)]
#input
})
Ok((
quote! {
#[allow(dead_code)]
#input
},
constant,
))
}

impl Constant {
Expand Down
26 changes: 7 additions & 19 deletions crates/macros/src/function.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
use std::collections::HashMap;

use crate::helpers::get_docs;
use crate::{syn_ext::DropLifetimes, STATE};
use crate::syn_ext::DropLifetimes;
use anyhow::{anyhow, bail, Result};
use darling::{FromMeta, ToTokens};
use proc_macro2::{Ident, Literal, Span, TokenStream};
use quote::quote;
use syn::{
punctuated::Punctuated, AttributeArgs, FnArg, GenericArgument, ItemFn, Lit, PathArguments,
ReturnType, Signature, Token, Type, TypePath,
punctuated::Punctuated, FnArg, GenericArgument, ItemFn, Lit, PathArguments, ReturnType,
Signature, Token, Type, TypePath,
};

#[derive(Default, Debug, FromMeta)]
Expand Down Expand Up @@ -40,13 +40,8 @@ pub struct Function {
pub output: Option<(String, bool)>,
}

pub fn parser(args: AttributeArgs, input: ItemFn) -> Result<(TokenStream, Function)> {
let attr_args = match AttrArgs::from_list(&args) {
Ok(args) => args,
Err(e) => bail!("Unable to parse attribute arguments: {:?}", e),
};

let ItemFn { sig, .. } = &input;
pub fn parser(attr_args: AttrArgs, input: &ItemFn) -> Result<(TokenStream, Function)> {
let ItemFn { sig, block, .. } = &input;
let Signature {
ident,
output,
Expand All @@ -69,7 +64,8 @@ pub fn parser(args: AttributeArgs, input: ItemFn) -> Result<(TokenStream, Functi
let return_type = get_return_type(output)?;

let func = quote! {
#input
#sig
#block

::ext_php_rs::zend_fastcall! {
#[doc(hidden)]
Expand All @@ -89,12 +85,6 @@ pub fn parser(args: AttributeArgs, input: ItemFn) -> Result<(TokenStream, Functi
}
};

let mut state = STATE.lock();

if state.built_module && !attr_args.ignore_module {
bail!("The `#[php_module]` macro must be called last to ensure functions are registered. To ignore this error, pass the `ignore_module` option into this attribute invocation: `#[php_function(ignore_module)]`");
}

let function = Function {
name: attr_args.name.unwrap_or_else(|| ident.to_string()),
docs: get_docs(&input.attrs),
Expand All @@ -104,8 +94,6 @@ pub fn parser(args: AttributeArgs, input: ItemFn) -> Result<(TokenStream, Functi
output: return_type,
};

state.functions.push(function.clone());

Ok((func, function))
}

Expand Down
17 changes: 7 additions & 10 deletions crates/macros/src/impl_.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ use quote::quote;
use std::collections::HashMap;
use syn::{Attribute, AttributeArgs, ItemImpl, Lit, Meta, NestedMeta};

use crate::class::Class;
use crate::helpers::get_docs;
use crate::{
class::{Property, PropertyAttr},
Expand Down Expand Up @@ -94,7 +95,11 @@ pub enum PropAttrTy {
Setter,
}

pub fn parser(args: AttributeArgs, input: ItemImpl) -> Result<TokenStream> {
pub fn parser(
args: AttributeArgs,
input: ItemImpl,
classes: &mut HashMap<String, Class>,
) -> Result<TokenStream> {
let args = AttrArgs::from_list(&args)
.map_err(|e| anyhow!("Unable to parse attribute arguments: {:?}", e))?;

Expand All @@ -105,15 +110,7 @@ pub fn parser(args: AttributeArgs, input: ItemImpl) -> Result<TokenStream> {
bail!("This macro cannot be used on trait implementations.");
}

let mut state = crate::STATE.lock();

if state.startup_function.is_some() {
bail!(
"Impls must be declared before you declare your startup function and module function."
);
}

let class = state.classes.get_mut(&class_name).ok_or_else(|| {
let class = classes.get_mut(&class_name).ok_or_else(|| {
anyhow!(
"You must use `#[php_class]` on the struct before using this attribute on the impl."
)
Expand Down
Loading
Loading