Compare commits
10 Commits
c399b89632
...
develop
| Author | SHA1 | Date | |
|---|---|---|---|
| b4543efaeb | |||
| a238b63e51 | |||
| 36b065ddb2 | |||
| 431fe30e34 | |||
| d8b4550392 | |||
| 577c02c9a4 | |||
| 6863d7377b | |||
| 134e35cc9e | |||
| d20e159731 | |||
| 3efbd9de2a |
@@ -15,7 +15,8 @@ authors = ["Dean J. Karstedt <dk@cl.team>"]
|
||||
license-file = "LICENSE"
|
||||
|
||||
[dependencies]
|
||||
pmp-emitter = { version = "1.0.0", path = "crates/pmp-emitter" }
|
||||
pmp-macro = { path = "crates/pmp-macro" }
|
||||
pmp-emitter = { path = "crates/pmp-emitter" }
|
||||
|
||||
clap = { version = "^4", features = ["derive"] }
|
||||
owo-colors = { version = "^4", features = ["supports-colors"] }
|
||||
|
||||
12
crates/pmp-core/Cargo.toml
Normal file
12
crates/pmp-core/Cargo.toml
Normal file
@@ -0,0 +1,12 @@
|
||||
[package]
|
||||
name = "pmp-core"
|
||||
version = "1.0.0"
|
||||
|
||||
edition.workspace = true
|
||||
authors.workspace = true
|
||||
license-file.workspace = true
|
||||
|
||||
[dependencies]
|
||||
syn = { version = "^2", features = ["full"] }
|
||||
darling = "^0"
|
||||
proc-macro2 = "^1"
|
||||
76
crates/pmp-core/src/attrs.rs
Normal file
76
crates/pmp-core/src/attrs.rs
Normal file
@@ -0,0 +1,76 @@
|
||||
use darling::FromMeta;
|
||||
|
||||
/// Implemented by any item that carries a `Vec<syn::Attribute>`.
|
||||
///
|
||||
/// Allows `parse_pmp_attrs` to be generic over variants, fields, etc.
|
||||
pub trait HasAttrs {
|
||||
fn attrs(&self) -> &[syn::Attribute];
|
||||
}
|
||||
|
||||
/// Blanket impl for anything that exposes `.attrs` as a public field via a deref,
|
||||
/// covered by explicit impls below for the common syn types.
|
||||
impl HasAttrs for syn::Field {
|
||||
fn attrs(&self) -> &[syn::Attribute] { &self.attrs }
|
||||
}
|
||||
|
||||
impl HasAttrs for syn::Variant {
|
||||
fn attrs(&self) -> &[syn::Attribute] { &self.attrs }
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------- //
|
||||
|
||||
/// Finds a `#[{attr_name}(...)]` attribute in the given list and parses it into `T`.
|
||||
///
|
||||
/// Returns `Ok(T::default())` if no such attribute is present or
|
||||
/// a span-accurate `Err` if the attribute is present but malformed.
|
||||
///
|
||||
/// Each proc-macro crate passes its own attribute name:
|
||||
/// ```
|
||||
/// // in pmp-emitter-core:
|
||||
/// let attrs: EnumAttrs = parse_pmp_attr(&input.attrs, "pmp_emitter")?;
|
||||
///
|
||||
/// // in pmp-macro-core:
|
||||
/// let attrs: MacroAttrs = parse_pmp_attr(&input.attrs, "pmp_macro")?;
|
||||
/// ```
|
||||
pub fn parse_pmp_attr<T>(attrs: &[syn::Attribute], attr_name: &str) -> syn::Result<T>
|
||||
where
|
||||
T: FromMeta + Default,
|
||||
{
|
||||
match attrs.iter().find(|a| a.path().is_ident(attr_name))
|
||||
{
|
||||
None => Ok(T::default()),
|
||||
Some(attr) => T::from_meta(&attr.meta)
|
||||
.map_err(|e| syn::Error::new_spanned(attr, e.to_string())),
|
||||
}
|
||||
}
|
||||
|
||||
/// Accumulates errors from parsing `#[{attr_name}(...)]` on a collection of items
|
||||
/// (e.g. enum variants or struct fields) into a single `syn::Error`.
|
||||
///
|
||||
/// Returns `Ok(Vec<T>)` with one parsed value per item, or `Err` containing all
|
||||
/// accumulated errors if any items failed.
|
||||
pub fn parse_pmp_attrs<T, I>(items: I, attr_name: &str) -> syn::Result<Vec<T>>
|
||||
where
|
||||
T: FromMeta + Default,
|
||||
I: IntoIterator<Item: HasAttrs>,
|
||||
{
|
||||
let mut results: Vec<T> = Vec::new();
|
||||
let mut errors: Option<syn::Error> = None;
|
||||
|
||||
for item in items
|
||||
{
|
||||
match parse_pmp_attr(item.attrs(), attr_name)
|
||||
{
|
||||
Ok(v) => results.push(v),
|
||||
Err(e) => match &mut errors {
|
||||
None => errors = Some(e),
|
||||
Some(existing) => existing.combine(e),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
match errors {
|
||||
None => Ok(results),
|
||||
Some(e) => Err(e),
|
||||
}
|
||||
}
|
||||
49
crates/pmp-core/src/functions.rs
Normal file
49
crates/pmp-core/src/functions.rs
Normal file
@@ -0,0 +1,49 @@
|
||||
|
||||
pub fn pascal_to_title(s: &str) -> String
|
||||
{
|
||||
let mut out = String::new();
|
||||
|
||||
for (i, ch) in s.chars().enumerate() {
|
||||
if ch.is_uppercase() && i > 0 { out.push(' '); }
|
||||
out.push(ch);
|
||||
}
|
||||
|
||||
out
|
||||
}
|
||||
|
||||
pub fn snake_to_title(s: &str) -> String
|
||||
{
|
||||
s.split('_')
|
||||
.map(|word| {
|
||||
let mut c = word.chars();
|
||||
match c.next() {
|
||||
None => String::new(),
|
||||
Some(f) => f.to_uppercase().collect::<String>() + c.as_str(),
|
||||
}
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join(" ")
|
||||
}
|
||||
|
||||
pub fn pascal_to_snake(s: &str) -> String
|
||||
{
|
||||
let mut out = String::with_capacity(s.len());
|
||||
let mut prev_lower = false;
|
||||
|
||||
for c in s.chars()
|
||||
{
|
||||
if c.is_uppercase()
|
||||
{
|
||||
if prev_lower { out.push('_'); }
|
||||
for lc in c.to_lowercase() { out.push(lc); }
|
||||
prev_lower = false;
|
||||
}
|
||||
else
|
||||
{
|
||||
prev_lower = true;
|
||||
out.push(c);
|
||||
}
|
||||
}
|
||||
|
||||
out
|
||||
}
|
||||
20
crates/pmp-core/src/lib.rs
Normal file
20
crates/pmp-core/src/lib.rs
Normal file
@@ -0,0 +1,20 @@
|
||||
//! Shared proc-macro utilities for all `pmp-*` crates.
|
||||
//!
|
||||
//! This crate provides building blocks that are identical across every
|
||||
//! `pmp-*-core` proc-derive-macro crate. Each consumer crate still defines
|
||||
//! its own darling input structs (because `forward_attrs` bakes in a per-crate
|
||||
//! attribute name at compile time), but everything else should be imported from here.
|
||||
//!
|
||||
//! | Module | Contents |
|
||||
//! |-----------|------------------------------------------------------------------|
|
||||
//! | `types` | [`StrictBool`], [`StrictString`], [`StrictPath`], [`StrictExpr`] |
|
||||
//! | `helpers` | [`pascal_to_title`], [`snake_to_title`] |
|
||||
//! | `attr` | [`parse_pmp_attr`], [`parse_pmp_attrs`], [`HasAttrs`] |
|
||||
|
||||
mod attrs;
|
||||
mod types;
|
||||
mod functions;
|
||||
|
||||
pub use attrs::*;
|
||||
pub use types::*;
|
||||
pub use functions::*;
|
||||
85
crates/pmp-core/src/types.rs
Normal file
85
crates/pmp-core/src/types.rs
Normal file
@@ -0,0 +1,85 @@
|
||||
use syn::{ Lit, Path };
|
||||
use darling::{ Error, Result, FromMeta };
|
||||
|
||||
/// A boolean that must be written as `= true` or `= false`
|
||||
#[allow(dead_code)]
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct StrictBool(pub bool);
|
||||
|
||||
impl FromMeta for StrictBool
|
||||
{
|
||||
fn from_word() -> Result<Self>
|
||||
{
|
||||
Err(Error::custom(
|
||||
"expected `= true/false`, provide a boolean value"
|
||||
))
|
||||
}
|
||||
|
||||
fn from_value(value: &Lit) -> Result<Self>
|
||||
{
|
||||
match value {
|
||||
Lit::Bool(b) => Ok(StrictBool(b.value)),
|
||||
_ => Err(Error::unexpected_lit_type(value)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A string that must be written as `= "..."`
|
||||
#[allow(dead_code)]
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct StrictString(pub String);
|
||||
|
||||
impl FromMeta for StrictString
|
||||
{
|
||||
fn from_word() -> Result<Self>
|
||||
{
|
||||
Err(Error::custom(
|
||||
"expected `= \"...\"`, provide a string value"
|
||||
))
|
||||
}
|
||||
|
||||
fn from_value(value: &Lit) -> Result<Self> {
|
||||
String::from_value(value).map(StrictString)
|
||||
}
|
||||
}
|
||||
|
||||
/// A path that must be written as `= my_fn`
|
||||
#[allow(dead_code)]
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct StrictPath(pub Path);
|
||||
|
||||
impl FromMeta for StrictPath
|
||||
{
|
||||
fn from_word() -> Result<Self>
|
||||
{
|
||||
Err(Error::custom(
|
||||
"expected `= my_fn`, provide a function path"
|
||||
))
|
||||
}
|
||||
|
||||
fn from_value(value: &Lit) -> Result<Self> {
|
||||
Path::from_value(value).map(StrictPath)
|
||||
}
|
||||
|
||||
fn from_expr(expr: &syn::Expr) -> Result<Self> {
|
||||
Path::from_expr(expr).map(StrictPath)
|
||||
}
|
||||
}
|
||||
|
||||
/// A Rust expression that must be written as `= <expr>`
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct StrictExpr(pub syn::Expr);
|
||||
|
||||
impl FromMeta for StrictExpr
|
||||
{
|
||||
fn from_word() -> Result<Self>
|
||||
{
|
||||
Err(Error::custom(
|
||||
"expected `= <expr>`, provide an expression, e.g. `target = Target::CLASS | Target::INTERFACE`"
|
||||
))
|
||||
}
|
||||
|
||||
fn from_expr(expr: &syn::Expr) -> Result<Self> {
|
||||
Ok(StrictExpr(expr.clone()))
|
||||
}
|
||||
}
|
||||
@@ -6,11 +6,6 @@ edition.workspace = true
|
||||
authors.workspace = true
|
||||
license-file.workspace = true
|
||||
|
||||
[lib]
|
||||
proc-macro = true
|
||||
|
||||
[dependencies]
|
||||
syn = { version = "^2", features = ["full"] }
|
||||
quote = "^1"
|
||||
darling = "^0"
|
||||
proc-macro2 = "^1"
|
||||
pmp-emitter-core = { path = "crates/pmp-emitter-core" }
|
||||
pmp-emitter-misc = { path = "crates/pmp-emitter-misc" }
|
||||
|
||||
18
crates/pmp-emitter/crates/pmp-emitter-core/Cargo.toml
Normal file
18
crates/pmp-emitter/crates/pmp-emitter-core/Cargo.toml
Normal file
@@ -0,0 +1,18 @@
|
||||
[package]
|
||||
name = "pmp-emitter-core"
|
||||
version = "1.0.0"
|
||||
|
||||
edition.workspace = true
|
||||
authors.workspace = true
|
||||
license-file.workspace = true
|
||||
|
||||
[lib]
|
||||
proc-macro = true
|
||||
|
||||
[dependencies]
|
||||
pmp-core = { path = "../../../pmp-core" }
|
||||
|
||||
syn = { version = "^2", features = ["full"] }
|
||||
quote = "^1"
|
||||
darling = "^0"
|
||||
proc-macro2 = "^1"
|
||||
46
crates/pmp-emitter/crates/pmp-emitter-core/src/attrs.rs
Normal file
46
crates/pmp-emitter/crates/pmp-emitter-core/src/attrs.rs
Normal file
@@ -0,0 +1,46 @@
|
||||
use darling::{ ast, FromMeta, FromVariant, FromDeriveInput };
|
||||
use pmp_core::{ StrictBool, StrictPath, StrictString };
|
||||
use syn::{ Type, Ident };
|
||||
|
||||
#[derive(Debug, FromDeriveInput)]
|
||||
#[darling(forward_attrs(pmp_emitter))]
|
||||
pub(crate) struct EmitterInput {
|
||||
pub ident: Ident,
|
||||
pub data: ast::Data<VariantReceiver, ()>,
|
||||
}
|
||||
|
||||
#[derive(Debug, FromVariant)]
|
||||
#[darling(forward_attrs(pmp_emitter))]
|
||||
pub(crate) struct VariantReceiver {
|
||||
pub ident: Ident,
|
||||
pub fields: ast::Fields<Type>,
|
||||
pub attrs: Vec<syn::Attribute>,
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------- //
|
||||
|
||||
/// - `descriptor = "..."` - prefix shown before all variant messages (default: enum name)
|
||||
/// - `exit = true|false` - whether to call process::exit (default: false)
|
||||
/// - `colorizer = fn` - fn(String) -> String applied to all variants unless overridden
|
||||
#[derive(Debug, Default, FromMeta)]
|
||||
pub(crate) struct EnumAttrs {
|
||||
#[darling(default)]
|
||||
pub exit: Option<StrictBool>,
|
||||
#[darling(default)]
|
||||
pub colorizer: Option<StrictPath>,
|
||||
#[darling(default)]
|
||||
pub descriptor: Option<StrictString>,
|
||||
}
|
||||
|
||||
/// - `message = "..."` - error message (default: variant name as title case)
|
||||
/// - `colorizer = fn` - optional fn(String) -> String for formatting
|
||||
/// - `exit = true|false` - overrides enum-level exit
|
||||
#[derive(Debug, Default, FromMeta)]
|
||||
pub(crate) struct VariantAttrs {
|
||||
#[darling(default)]
|
||||
pub exit: Option<StrictBool>,
|
||||
#[darling(default)]
|
||||
pub message: Option<StrictString>,
|
||||
#[darling(default)]
|
||||
pub colorizer: Option<StrictPath>,
|
||||
}
|
||||
103
crates/pmp-emitter/crates/pmp-emitter-core/src/expand.rs
Normal file
103
crates/pmp-emitter/crates/pmp-emitter-core/src/expand.rs
Normal file
@@ -0,0 +1,103 @@
|
||||
use proc_macro2::TokenStream as TokenStream2;
|
||||
use quote::{ quote, quote_spanned };
|
||||
use pmp_core::{ self, StrictPath };
|
||||
use syn::DeriveInput;
|
||||
use darling::ast;
|
||||
|
||||
use crate::attrs::{ EnumAttrs, EmitterInput, VariantAttrs };
|
||||
|
||||
// ---------------------------------------------------------------------------------------------- //
|
||||
|
||||
pub fn expand(shape: EmitterInput, raw_input: &DeriveInput) -> syn::Result<TokenStream2>
|
||||
{
|
||||
let enum_attrs: EnumAttrs = pmp_core::parse_pmp_attr(&raw_input.attrs, "pmp_emitter")?;
|
||||
|
||||
let enum_ident = &shape.ident;
|
||||
let descriptor = enum_attrs.descriptor
|
||||
.map(|s| s.0)
|
||||
.unwrap_or_else(|| pmp_core::pascal_to_title(&enum_ident.to_string()));
|
||||
let global_exit = enum_attrs.exit.map(|b| b.0).unwrap_or(false);
|
||||
let global_colorizer = enum_attrs.colorizer;
|
||||
|
||||
let variants = shape.data.take_enum().ok_or_else(|| {
|
||||
syn::Error::new_spanned(enum_ident, "PmpEmitter can only be derived on enums")
|
||||
})?;
|
||||
|
||||
let mut errors: Option<syn::Error> = None;
|
||||
let mut match_arms: Vec<TokenStream2> = Vec::with_capacity(variants.len());
|
||||
|
||||
for v in &variants
|
||||
{
|
||||
let var_ident = &v.ident;
|
||||
let title = pmp_core::pascal_to_title(&var_ident.to_string());
|
||||
|
||||
let v_attrs: VariantAttrs = match pmp_core::parse_pmp_attr(&v.attrs, "pmp_emitter")
|
||||
{
|
||||
Ok(a) => a,
|
||||
Err(e) =>
|
||||
{
|
||||
match &mut errors {
|
||||
None => errors = Some(e),
|
||||
Some(existing) => existing.combine(e),
|
||||
}
|
||||
continue;
|
||||
}
|
||||
};
|
||||
|
||||
let message = v_attrs.message.map(|s| s.0).unwrap_or_else(|| title.clone());
|
||||
let should_exit = v_attrs.exit.map(|b| b.0).unwrap_or(global_exit);
|
||||
|
||||
let header = format!("{}: {} (\"{}\")", descriptor, title, message);
|
||||
|
||||
let formatted_header = match v_attrs.colorizer.as_ref().or(global_colorizer.as_ref()) {
|
||||
Some(StrictPath(path)) => quote! { #path(#header) },
|
||||
None => quote! { #header.to_string() },
|
||||
};
|
||||
|
||||
let exit_tokens = if should_exit { quote! { std::process::exit(1); } } else { quote! {} };
|
||||
|
||||
let arm = match v.fields.style
|
||||
{
|
||||
ast::Style::Tuple =>
|
||||
{
|
||||
let pattern = if v.fields.len() == 1 { quote! { (trace) } } else { quote! { (trace, ..) } };
|
||||
|
||||
quote_spanned! { var_ident.span() =>
|
||||
#enum_ident::#var_ident #pattern =>
|
||||
{
|
||||
println!("{}\n\n{}", #formatted_header, trace);
|
||||
#exit_tokens
|
||||
}
|
||||
}
|
||||
},
|
||||
_ => quote_spanned! { var_ident.span() =>
|
||||
#enum_ident::#var_ident =>
|
||||
{
|
||||
println!("{}", #formatted_header);
|
||||
#exit_tokens
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
match_arms.push(arm);
|
||||
}
|
||||
|
||||
if let Some(e) = errors { return Err(e); }
|
||||
|
||||
Ok(quote!
|
||||
{
|
||||
impl #enum_ident
|
||||
{
|
||||
pub fn emit(&self) {
|
||||
match self { #(#match_arms),* }
|
||||
}
|
||||
}
|
||||
|
||||
impl ::pmp_emitter::pmp_emitter_misc::Emittable for #enum_ident
|
||||
{
|
||||
fn emit(&self) {
|
||||
self.emit()
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
25
crates/pmp-emitter/crates/pmp-emitter-core/src/lib.rs
Normal file
25
crates/pmp-emitter/crates/pmp-emitter-core/src/lib.rs
Normal file
@@ -0,0 +1,25 @@
|
||||
use darling::FromDeriveInput;
|
||||
use proc_macro::TokenStream;
|
||||
use syn::DeriveInput;
|
||||
|
||||
mod attrs;
|
||||
mod expand;
|
||||
|
||||
use attrs::EmitterInput;
|
||||
|
||||
// ---------------------------------------------------------------------------------------------- //
|
||||
|
||||
#[proc_macro_derive(PmpEmitter, attributes(pmp_emitter))]
|
||||
pub fn pmp_emitter(item: TokenStream) -> TokenStream
|
||||
{
|
||||
let input = syn::parse_macro_input!(item as DeriveInput);
|
||||
|
||||
let shape = match EmitterInput::from_derive_input(&input) {
|
||||
Ok(s) => s,
|
||||
Err(e) => return e.write_errors().into(),
|
||||
};
|
||||
|
||||
expand::expand(shape, &input)
|
||||
.unwrap_or_else(syn::Error::into_compile_error)
|
||||
.into()
|
||||
}
|
||||
9
crates/pmp-emitter/crates/pmp-emitter-misc/Cargo.toml
Normal file
9
crates/pmp-emitter/crates/pmp-emitter-misc/Cargo.toml
Normal file
@@ -0,0 +1,9 @@
|
||||
[package]
|
||||
name = "pmp-emitter-misc"
|
||||
version = "1.0.0"
|
||||
|
||||
edition.workspace = true
|
||||
authors.workspace = true
|
||||
license-file.workspace = true
|
||||
|
||||
[dependencies]
|
||||
4
crates/pmp-emitter/crates/pmp-emitter-misc/src/lib.rs
Normal file
4
crates/pmp-emitter/crates/pmp-emitter-misc/src/lib.rs
Normal file
@@ -0,0 +1,4 @@
|
||||
|
||||
pub trait Emittable {
|
||||
fn emit(&self);
|
||||
}
|
||||
@@ -1,185 +1,5 @@
|
||||
use quote::quote;
|
||||
use proc_macro::TokenStream;
|
||||
use syn::{ Lit, Path, Type, Ident, DeriveInput, parse_macro_input };
|
||||
use darling::{ ast, Error, Result, FromMeta, FromVariant, FromDeriveInput };
|
||||
#[doc(hidden)]
|
||||
pub extern crate pmp_emitter_misc;
|
||||
|
||||
// ---------------------------------------------------------------------------------------------- //
|
||||
|
||||
#[derive(Debug, FromDeriveInput)]
|
||||
#[darling(forward_attrs(pmp_emitter))]
|
||||
struct EmitterInput {
|
||||
ident: Ident,
|
||||
data: ast::Data<VariantReceiver, ()>,
|
||||
}
|
||||
|
||||
#[derive(Debug, FromVariant)]
|
||||
#[darling(forward_attrs(pmp_emitter))]
|
||||
struct VariantReceiver {
|
||||
ident: Ident,
|
||||
fields: ast::Fields<Type>,
|
||||
attrs: Vec<syn::Attribute>,
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------- //
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
struct StrictBool(bool);
|
||||
|
||||
/// - `descriptor = "..."` - prefix shown before all variant messages (default: enum name)
|
||||
/// - `exit = true|false` - whether to call process::exit (default: false)
|
||||
#[derive(Debug, FromMeta)]
|
||||
struct EnumAttrs {
|
||||
#[darling(default)]
|
||||
descriptor: Option<String>,
|
||||
#[darling(default)]
|
||||
exit: Option<StrictBool>,
|
||||
}
|
||||
|
||||
/// - `message = "..."` - error message (default: variant name as title case)
|
||||
/// - `colorizer = fn` - optional fn(String) -> String for formatting
|
||||
/// - `exit = true|false` - overrides enum-level exit
|
||||
#[derive(Debug, FromMeta)]
|
||||
struct VariantAttrs {
|
||||
#[darling(default)]
|
||||
exit: Option<StrictBool>,
|
||||
#[darling(default)]
|
||||
message: Option<String>,
|
||||
#[darling(default)]
|
||||
colorizer: Option<Path>,
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------- //
|
||||
|
||||
impl FromMeta for StrictBool
|
||||
{
|
||||
fn from_value(value: &Lit) -> Result<Self>
|
||||
{
|
||||
match value {
|
||||
Lit::Bool(b) => Ok(StrictBool(b.value)),
|
||||
_ => Err(Error::unexpected_lit_type(value)),
|
||||
}
|
||||
}
|
||||
|
||||
// intentionally NOT implementing from_word()
|
||||
}
|
||||
|
||||
fn parse_pmp_attr<T: FromMeta>(attrs: &[syn::Attribute]) -> T
|
||||
where
|
||||
T: Default,
|
||||
{
|
||||
attrs
|
||||
.iter()
|
||||
.find(|a| a.path().is_ident("pmp_emitter"))
|
||||
.map(|a| T::from_meta(&a.meta).expect("invalid pmp_emitter attribute"))
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
impl Default for EnumAttrs {
|
||||
fn default() -> Self {
|
||||
Self { descriptor: None, exit: None }
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for VariantAttrs {
|
||||
fn default() -> Self {
|
||||
Self { message: None, exit: None, colorizer: None }
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------- //
|
||||
|
||||
fn pascal_to_title(s: &str) -> String
|
||||
{
|
||||
let mut out = String::new();
|
||||
|
||||
for (i, ch) in s.chars().enumerate()
|
||||
{
|
||||
if ch.is_uppercase() && i > 0 { out.push(' '); }
|
||||
out.push(ch);
|
||||
}
|
||||
|
||||
out
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------- //
|
||||
|
||||
#[proc_macro_derive(PmpEmitter, attributes(pmp_emitter))]
|
||||
pub fn pmp_emitter(item: TokenStream) -> TokenStream
|
||||
{
|
||||
let input = parse_macro_input!(item as DeriveInput);
|
||||
|
||||
// parse enum shape
|
||||
let shape = match EmitterInput::from_derive_input(&input) {
|
||||
Ok(a) => a,
|
||||
Err(e) => return e.write_errors().into(),
|
||||
};
|
||||
|
||||
// parse enum-level #[pmp_emitter(...)] directly from the raw attrs
|
||||
let enum_attrs: EnumAttrs = parse_pmp_attr(&input.attrs);
|
||||
|
||||
let enum_ident = &shape.ident;
|
||||
let descriptor = enum_attrs.descriptor
|
||||
.unwrap_or_else(|| pascal_to_title(&enum_ident.to_string()));
|
||||
let global_exit = enum_attrs.exit.map(|b| b.0).unwrap_or(false);
|
||||
|
||||
let variants = shape
|
||||
.data
|
||||
.take_enum()
|
||||
.expect("PmpEmitter can only be derived on enums");
|
||||
|
||||
let match_arms = variants.iter().map(|v|
|
||||
{
|
||||
let var_ident = &v.ident;
|
||||
let title = pascal_to_title(&var_ident.to_string());
|
||||
|
||||
// parse variant-level #[pmp_emitter(...)] from the variant's raw attrs
|
||||
let vattrs: VariantAttrs = parse_pmp_attr(&v.attrs);
|
||||
|
||||
let message = vattrs.message.unwrap_or_else(|| title.clone());
|
||||
let should_exit = vattrs.exit.map(|b| b.0).unwrap_or(global_exit);
|
||||
|
||||
// ┌─ Output format ───────────────────────────────┐
|
||||
// │ {descriptor}: {Variant Title} ("{message}") │
|
||||
// │ │
|
||||
// │ {stacktrace} │
|
||||
// └───────────────────────────────────────────────┘
|
||||
let header = format!("{}: {} (\"{}\")", descriptor, title, message);
|
||||
|
||||
let formatted_header = match &vattrs.colorizer
|
||||
{
|
||||
Some(path) => quote! { #path(#header) },
|
||||
None => quote! { #header.to_string() },
|
||||
};
|
||||
|
||||
let exit_tokens = if should_exit { quote! { std::process::exit(1); } } else { quote! {} };
|
||||
|
||||
match v.fields.style
|
||||
{
|
||||
ast::Style::Tuple => quote! {
|
||||
#enum_ident::#var_ident(trace) =>
|
||||
{
|
||||
println!("{}\n\n{}", #formatted_header, trace);
|
||||
#exit_tokens
|
||||
}
|
||||
},
|
||||
_ => quote! {
|
||||
#enum_ident::#var_ident =>
|
||||
{
|
||||
println!("{}", #formatted_header);
|
||||
#exit_tokens
|
||||
}
|
||||
},
|
||||
}
|
||||
});
|
||||
|
||||
quote! {
|
||||
impl #enum_ident
|
||||
{
|
||||
pub fn emit(&self) {
|
||||
match self {
|
||||
#(#match_arms),*
|
||||
}
|
||||
}
|
||||
}
|
||||
}.into()
|
||||
}
|
||||
pub use pmp_emitter_misc::Emittable;
|
||||
pub use pmp_emitter_core::PmpEmitter;
|
||||
|
||||
11
crates/pmp-macro/Cargo.toml
Normal file
11
crates/pmp-macro/Cargo.toml
Normal file
@@ -0,0 +1,11 @@
|
||||
[package]
|
||||
name = "pmp-macro"
|
||||
version = "1.0.0"
|
||||
|
||||
edition.workspace = true
|
||||
authors.workspace = true
|
||||
license-file.workspace = true
|
||||
|
||||
[dependencies]
|
||||
pmp-macro-core = { path = "crates/pmp-macro-core" }
|
||||
pmp-macro-misc = { path = "crates/pmp-macro-misc" }
|
||||
19
crates/pmp-macro/crates/pmp-macro-core/Cargo.toml
Normal file
19
crates/pmp-macro/crates/pmp-macro-core/Cargo.toml
Normal file
@@ -0,0 +1,19 @@
|
||||
[package]
|
||||
name = "pmp-macro-core"
|
||||
version = "1.0.0"
|
||||
|
||||
edition.workspace = true
|
||||
authors.workspace = true
|
||||
license-file.workspace = true
|
||||
|
||||
[lib]
|
||||
proc-macro = true
|
||||
|
||||
[dependencies]
|
||||
pmp-core = { path = "../../../pmp-core" }
|
||||
pmp-macro-misc = { path = "../pmp-macro-misc" }
|
||||
|
||||
syn = { version = "^2", features = ["full"] }
|
||||
quote = "^1"
|
||||
darling = "^0"
|
||||
proc-macro2 = "^1"
|
||||
49
crates/pmp-macro/crates/pmp-macro-core/src/attrs.rs
Normal file
49
crates/pmp-macro/crates/pmp-macro-core/src/attrs.rs
Normal file
@@ -0,0 +1,49 @@
|
||||
use pmp_core::{ StrictBool, StrictExpr, StrictString };
|
||||
use darling::{ ast, FromField, FromDeriveInput };
|
||||
use syn::{ Type, Ident };
|
||||
|
||||
/// - `name = "..."` - PHP attribute name (default: struct name)
|
||||
/// - `target = <expr>` - which PHP constructs may use this attribute (default: Target::ALL)
|
||||
/// - `docs = "..."` - description for diagnostics and generated docs
|
||||
#[derive(Debug, FromDeriveInput)]
|
||||
#[darling(attributes(pmp_macro), forward_attrs(allow, doc, cfg))]
|
||||
pub struct MacroInput {
|
||||
pub ident: Ident,
|
||||
pub data: ast::Data<darling::util::Ignored, FieldInput>,
|
||||
|
||||
#[darling(default)]
|
||||
pub name: Option<StrictString>,
|
||||
#[darling(default)]
|
||||
pub target: Option<StrictExpr>,
|
||||
#[darling(default)]
|
||||
pub docs: Option<StrictString>,
|
||||
}
|
||||
|
||||
/// - `php_type = "..."` - PHP type hint, e.g. `"class-string[]"` (required)
|
||||
/// - `default = "..."` - PHP default value, e.g. `"[]"`
|
||||
/// - `required = bool` - overrides required inference
|
||||
#[derive(Debug, FromField)]
|
||||
#[darling(attributes(param))]
|
||||
pub struct FieldInput {
|
||||
pub ident: Option<Ident>,
|
||||
#[allow(dead_code)]
|
||||
pub ty: Type,
|
||||
|
||||
#[darling(default)]
|
||||
pub php_type: Option<StrictString>,
|
||||
#[darling(default)]
|
||||
pub default: Option<StrictString>,
|
||||
#[darling(default)]
|
||||
pub required: Option<StrictBool>,
|
||||
}
|
||||
|
||||
impl FieldInput
|
||||
{
|
||||
pub fn is_param(&self) -> bool {
|
||||
self.php_type.is_some()
|
||||
}
|
||||
|
||||
pub fn is_required(&self) -> bool {
|
||||
self.required.map(|b| b.0).unwrap_or(self.default.is_none())
|
||||
}
|
||||
}
|
||||
129
crates/pmp-macro/crates/pmp-macro-core/src/expand.rs
Normal file
129
crates/pmp-macro/crates/pmp-macro-core/src/expand.rs
Normal file
@@ -0,0 +1,129 @@
|
||||
use quote::{ format_ident, quote, quote_spanned };
|
||||
use proc_macro2::TokenStream as TokenStream2;
|
||||
|
||||
use crate::attrs::MacroInput;
|
||||
|
||||
fn rewrite_bitor_target_expr(expr: syn::Expr) -> syn::Expr
|
||||
{
|
||||
match expr
|
||||
{
|
||||
syn::Expr::Binary(mut bin) if matches!(bin.op, syn::BinOp::BitOr(_)) => {
|
||||
bin.left = Box::new(rewrite_bitor_target_expr(*bin.left));
|
||||
bin.right = Box::new(rewrite_bitor_target_expr(*bin.right));
|
||||
syn::Expr::Binary(bin)
|
||||
}
|
||||
|
||||
other => {
|
||||
syn::parse_quote! { (#other).bits() }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn expand(parsed: MacroInput) -> syn::Result<TokenStream2>
|
||||
{
|
||||
let struct_ident = &parsed.ident;
|
||||
|
||||
let fields = parsed.data.take_struct().ok_or_else(|| {
|
||||
syn::Error::new_spanned(struct_ident, "PmpMacro can only be derived for structs")
|
||||
})?;
|
||||
|
||||
let attr_name: String = parsed.name
|
||||
.map(|s| s.0)
|
||||
.unwrap_or_else(|| struct_ident.to_string());
|
||||
|
||||
let target_expr: syn::Expr = parsed.target
|
||||
.map(|e| rewrite_bitor_target_expr(e.0))
|
||||
.unwrap_or_else(|| syn::parse_quote! { ::pmp_macro::Target::ALL.bits() });
|
||||
|
||||
let docs: String = parsed.docs.map(|s| s.0).unwrap_or_default();
|
||||
|
||||
let mut param_tokens: Vec<TokenStream2> = Vec::new();
|
||||
let mut errors: Option<syn::Error> = None;
|
||||
|
||||
for field in fields.iter().filter(|f| f.is_param())
|
||||
{
|
||||
let span = field.ident.as_ref().map(|i| i.span()).unwrap_or_else(|| struct_ident.span());
|
||||
let field_name = field.ident.as_ref().map(|i| i.to_string()).unwrap_or_default();
|
||||
|
||||
let php_type = match &field.php_type
|
||||
{
|
||||
Some(s) => s.0.clone(),
|
||||
None =>
|
||||
{
|
||||
let e = syn::Error::new(
|
||||
span,
|
||||
format!("field `{field_name}` has #[param] but is missing `php_type = \"...\"`"),
|
||||
);
|
||||
match &mut errors {
|
||||
None => errors = Some(e),
|
||||
Some(existing) => existing.combine(e),
|
||||
}
|
||||
continue;
|
||||
}
|
||||
};
|
||||
|
||||
let required = field.is_required();
|
||||
let default_tokens = match field.default.as_ref().map(|s| s.0.as_str()) {
|
||||
Some(d) => quote! { Some(#d) },
|
||||
None => quote! { None },
|
||||
};
|
||||
|
||||
param_tokens.push(quote_spanned! { span =>
|
||||
::pmp_macro::ParamDescriptor {
|
||||
name: #field_name,
|
||||
php_type: #php_type,
|
||||
required: #required,
|
||||
default: #default_tokens,
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
if let Some(e) = errors { return Err(e); }
|
||||
|
||||
let snaked_ident = pmp_core::pascal_to_snake(struct_ident.to_string().as_str());
|
||||
let mod_ident = format_ident!("__pmp_macro_impl_{}", snaked_ident);
|
||||
let handler = quote! { super::#struct_ident };
|
||||
|
||||
Ok(quote!
|
||||
{
|
||||
#[doc(hidden)]
|
||||
mod #mod_ident
|
||||
{
|
||||
use ::pmp_macro::{
|
||||
AnalyzeFn, MacroDescriptor, MacroRegistration,
|
||||
ParamDescriptor, Target, TransformFn, PmpMacro,
|
||||
};
|
||||
|
||||
static PARAMS: &[ParamDescriptor] = &[ #(#param_tokens),* ];
|
||||
|
||||
static DESCRIPTOR: MacroDescriptor = MacroDescriptor {
|
||||
name: #attr_name,
|
||||
target_bits: #target_expr,
|
||||
docs: #docs,
|
||||
params: PARAMS,
|
||||
};
|
||||
|
||||
fn analyze(
|
||||
ctx: &::pmp_macro::MacroContext,
|
||||
attr: &::pmp_macro::ResolvedAttr,
|
||||
node: &::pmp_macro::AttributedNode,
|
||||
) -> ::std::vec::Vec<::pmp_macro::Diagnostic>
|
||||
{
|
||||
<#handler as PmpMacro>::analyze(&::std::default::Default::default(), ctx, attr, node)
|
||||
}
|
||||
|
||||
fn transform(
|
||||
ctx: &::pmp_macro::MacroContext,
|
||||
attr: &::pmp_macro::ResolvedAttr,
|
||||
node: &::pmp_macro::AttributedNode,
|
||||
) -> ::std::vec::Vec<::pmp_macro::Rewrite>
|
||||
{
|
||||
<#handler as PmpMacro>::transform(&::std::default::Default::default(), ctx, attr, node)
|
||||
}
|
||||
|
||||
::pmp_macro::inventory::submit! {
|
||||
MacroRegistration::new(&DESCRIPTOR, analyze, transform)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
55
crates/pmp-macro/crates/pmp-macro-core/src/lib.rs
Normal file
55
crates/pmp-macro/crates/pmp-macro-core/src/lib.rs
Normal file
@@ -0,0 +1,55 @@
|
||||
use darling::FromDeriveInput;
|
||||
use proc_macro::TokenStream;
|
||||
use syn::DeriveInput;
|
||||
|
||||
mod attrs;
|
||||
mod expand;
|
||||
|
||||
use attrs::MacroInput;
|
||||
|
||||
/// Derives registration boilerplate for a PHP macro attribute handler.
|
||||
///
|
||||
/// #### Struct-level attributes (`#[pmp_macro(...)]`)
|
||||
///
|
||||
/// | Key | Type | Default | Description |
|
||||
/// |------------|---------------|------------------|----------------------------------------------|
|
||||
/// | `name` | `= "..."` | Struct name | PHP attribute name to match against |
|
||||
/// | `target` | `= <expr>` | `Target::ALL` | Which PHP constructs may use this attribute |
|
||||
/// | `docs` | `= "..."` | `""` | Description for diagnostics and generated docs |
|
||||
///
|
||||
/// #### Field-level attributes (`#[param(...)]`)
|
||||
///
|
||||
/// Fields without `#[param(...)]` are ignored - they are treated as handler
|
||||
/// implementation details, not PHP constructor parameters.
|
||||
///
|
||||
/// | Key | Type | Default | Description |
|
||||
/// |------------|-----------|-------------------|------------------------------------------|
|
||||
/// | `php_type` | `= "..."` | *(required)* | PHP type hint, e.g. `"class-string[]"` |
|
||||
/// | `default` | `= "..."` | `None` | PHP default value, e.g. `"[]"` |
|
||||
/// | `required` | `= bool` | inferred | Overrides required inference |
|
||||
///
|
||||
/// #### What is generated
|
||||
///
|
||||
/// - A hidden module containing a `static MacroDescriptor` and `static [ParamDescriptor]`
|
||||
/// - Two free functions delegating to the handler's `PmpMacro::analyze` / `::transform`
|
||||
/// - An `inventory::submit!` registration wiring it all together
|
||||
///
|
||||
/// #### Requirements
|
||||
///
|
||||
/// - The struct must implement [`pmp_macro_misc::PmpMacro`] (user-written)
|
||||
/// - The struct must implement [`Default`] (needed to construct a handler instance
|
||||
/// inside the generated delegation functions)
|
||||
#[proc_macro_derive(PmpMacro, attributes(pmp_macro, param))]
|
||||
pub fn pmp_macro_derive(item: TokenStream) -> TokenStream
|
||||
{
|
||||
let input = syn::parse_macro_input!(item as DeriveInput);
|
||||
|
||||
let parsed = match MacroInput::from_derive_input(&input) {
|
||||
Ok(p) => p,
|
||||
Err(e) => return e.write_errors().into(),
|
||||
};
|
||||
|
||||
expand::expand(parsed)
|
||||
.unwrap_or_else(syn::Error::into_compile_error)
|
||||
.into()
|
||||
}
|
||||
11
crates/pmp-macro/crates/pmp-macro-misc/Cargo.toml
Normal file
11
crates/pmp-macro/crates/pmp-macro-misc/Cargo.toml
Normal file
@@ -0,0 +1,11 @@
|
||||
[package]
|
||||
name = "pmp-macro-misc"
|
||||
version = "1.0.0"
|
||||
|
||||
edition.workspace = true
|
||||
authors.workspace = true
|
||||
license-file.workspace = true
|
||||
|
||||
[dependencies]
|
||||
bitflags = "^2"
|
||||
inventory = "^0"
|
||||
45
crates/pmp-macro/crates/pmp-macro-misc/src/context.rs
Normal file
45
crates/pmp-macro/crates/pmp-macro-misc/src/context.rs
Normal file
@@ -0,0 +1,45 @@
|
||||
// ---------------------------------------------------------------------------------------------- //
|
||||
// Mago-facing placeholders //
|
||||
// //
|
||||
// These types will wrap or re-export mago's AST / symbol / source types once the //
|
||||
// integration surface is understood. For now they are empty structs so the trait //
|
||||
// and derive can be written against concrete type names without a mago dependency. //
|
||||
// ---------------------------------------------------------------------------------------------- //
|
||||
|
||||
/// Global preprocessor state passed to every handler invocation.
|
||||
///
|
||||
/// Will hold references to mago's parsed file set, resolved symbol table,
|
||||
/// and any cross-file index needed for macros like `#[Sealed]` that must
|
||||
/// scan the entire project.
|
||||
///
|
||||
/// TODO: replace with real mago types.
|
||||
#[non_exhaustive]
|
||||
pub struct MacroContext;
|
||||
|
||||
/// The PHP AST node that carries the attribute being processed, together
|
||||
/// with the specific attribute instance (which macro it is, its position).
|
||||
///
|
||||
/// TODO: replace with real mago node types.
|
||||
#[non_exhaustive]
|
||||
pub struct AttributedNode;
|
||||
|
||||
/// The parsed and type-resolved arguments supplied to the attribute.
|
||||
///
|
||||
/// e.g. for `#[Sealed([Success::class, Failure::class])]` this would
|
||||
/// expose the two resolved class names as typed Rust values.
|
||||
///
|
||||
/// TODO: replace with real resolved argument types.
|
||||
#[non_exhaustive]
|
||||
pub struct ResolvedAttr;
|
||||
|
||||
/// A single source-level diagnostic emitted by a macro handler.
|
||||
///
|
||||
/// TODO: decide between a custom type or wrapping mago's / miette's diagnostic type.
|
||||
#[non_exhaustive]
|
||||
pub struct Diagnostic;
|
||||
|
||||
/// A rewrite instruction produced by `PmpMacro::transform`.
|
||||
///
|
||||
/// TODO: decide between text-span replacement or typed AST mutation depending on what mago exposes.
|
||||
#[non_exhaustive]
|
||||
pub struct Rewrite;
|
||||
26
crates/pmp-macro/crates/pmp-macro-misc/src/descriptor.rs
Normal file
26
crates/pmp-macro/crates/pmp-macro-misc/src/descriptor.rs
Normal file
@@ -0,0 +1,26 @@
|
||||
use crate::target::Target;
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct ParamDescriptor {
|
||||
pub name: &'static str,
|
||||
pub php_type: &'static str,
|
||||
pub required: bool,
|
||||
pub default: Option<&'static str>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct MacroDescriptor {
|
||||
pub name: &'static str,
|
||||
/// Raw bitflags value - use `.target()` to get a `Target`.
|
||||
/// Stored as `u16` so the static initializer remains `const`.
|
||||
pub target_bits: u16,
|
||||
pub docs: &'static str,
|
||||
pub params: &'static [ParamDescriptor],
|
||||
}
|
||||
|
||||
impl MacroDescriptor
|
||||
{
|
||||
pub fn target(&self) -> Target {
|
||||
Target::from_bits_truncate(self.target_bits)
|
||||
}
|
||||
}
|
||||
23
crates/pmp-macro/crates/pmp-macro-misc/src/lib.rs
Normal file
23
crates/pmp-macro/crates/pmp-macro-misc/src/lib.rs
Normal file
@@ -0,0 +1,23 @@
|
||||
//! Shared types, traits, and registration machinery for `pmp-macro`.
|
||||
//!
|
||||
//! # Crate layout
|
||||
//!
|
||||
//! | Module | Contents |
|
||||
//! |--------------|-----------------------------------------------------------------|
|
||||
//! | `target` | [`Target`] bitflags for PHP attribute target sites |
|
||||
//! | `descriptor` | [`MacroDescriptor`] and [`ParamDescriptor`] - static metadata |
|
||||
//! | `context` | [`MacroContext`], [`AttributedNode`], [`ResolvedAttr`], etc. |
|
||||
//! | `traits` | [`PmpMacro`] trait, [`MacroRegistration`], [`MacroRegistry`] |
|
||||
|
||||
mod target;
|
||||
mod traits;
|
||||
mod context;
|
||||
mod descriptor;
|
||||
|
||||
#[doc(hidden)]
|
||||
pub use inventory;
|
||||
|
||||
pub use target::*;
|
||||
pub use traits::*;
|
||||
pub use context::*;
|
||||
pub use descriptor::*;
|
||||
75
crates/pmp-macro/crates/pmp-macro-misc/src/target.rs
Normal file
75
crates/pmp-macro/crates/pmp-macro-misc/src/target.rs
Normal file
@@ -0,0 +1,75 @@
|
||||
use std::fmt::{ Display, Formatter };
|
||||
use bitflags::bitflags;
|
||||
|
||||
bitflags!
|
||||
{
|
||||
/// The PHP construct(s) that a macro attribute is permitted to annotate.
|
||||
///
|
||||
/// Mirrors PHP's `Attribute::TARGET_*` constants. A macro may target
|
||||
/// multiple sites by OR-ing flags together:
|
||||
///
|
||||
/// ```
|
||||
/// let target = Target::CLASS | Target::INTERFACE;
|
||||
/// ```
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct Target: u16
|
||||
{
|
||||
const CLASS = 1 << 0;
|
||||
const INTERFACE = 1 << 1;
|
||||
const TRAIT = 1 << 2;
|
||||
const ENUM = 1 << 3;
|
||||
const METHOD = 1 << 4;
|
||||
const FUNCTION = 1 << 5;
|
||||
const PROPERTY = 1 << 6;
|
||||
const CONSTANT = 1 << 7;
|
||||
const PARAMETER = 1 << 8;
|
||||
|
||||
/// Convenience: any class-like construct.
|
||||
const ANY_CLASS_LIKE = Self::CLASS.bits()
|
||||
| Self::INTERFACE.bits()
|
||||
| Self::TRAIT.bits()
|
||||
| Self::ENUM.bits();
|
||||
|
||||
/// Convenience: any callable construct.
|
||||
const ANY_CALLABLE = Self::METHOD.bits()
|
||||
| Self::FUNCTION.bits();
|
||||
|
||||
/// Convenience: all targets.
|
||||
const ALL = u16::MAX;
|
||||
}
|
||||
}
|
||||
|
||||
impl Display for Target
|
||||
{
|
||||
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result
|
||||
{
|
||||
let mut first = true;
|
||||
|
||||
macro_rules! write_flag
|
||||
{
|
||||
($flag:ident) =>
|
||||
{
|
||||
if self.contains(Target::$flag)
|
||||
{
|
||||
if !first { write!(f, " | ")?; }
|
||||
write!(f, "Target::{}", stringify!($flag))?;
|
||||
first = false;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
write_flag!(CLASS);
|
||||
write_flag!(INTERFACE);
|
||||
write_flag!(TRAIT);
|
||||
write_flag!(ENUM);
|
||||
write_flag!(METHOD);
|
||||
write_flag!(FUNCTION);
|
||||
write_flag!(PROPERTY);
|
||||
write_flag!(CONSTANT);
|
||||
write_flag!(PARAMETER);
|
||||
|
||||
if first { write!(f, "Target::ALL")?; }
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
146
crates/pmp-macro/crates/pmp-macro-misc/src/traits.rs
Normal file
146
crates/pmp-macro/crates/pmp-macro-misc/src/traits.rs
Normal file
@@ -0,0 +1,146 @@
|
||||
use std::{
|
||||
sync::OnceLock,
|
||||
collections::HashMap
|
||||
};
|
||||
|
||||
use crate::{
|
||||
descriptor::MacroDescriptor,
|
||||
context::{ Rewrite, Diagnostic, ResolvedAttr, MacroContext, AttributedNode }
|
||||
};
|
||||
|
||||
// --------------------------------------------------------------------------------------------- //
|
||||
|
||||
/// The handler trait implemented by each PHP macro attribute struct.
|
||||
///
|
||||
/// The two handler methods have default no-op
|
||||
/// implementations so that analysis-only and transform-only macros only need
|
||||
/// to override what they actually do.
|
||||
///
|
||||
/// The trait is object-safe (`&self`, no generics), so the registry can store
|
||||
/// `Box<dyn PmpMacro>` without knowing concrete types.
|
||||
pub trait PmpMacro: Send + Sync
|
||||
{
|
||||
/// Analyse the attributed PHP node and emit diagnostics.
|
||||
///
|
||||
/// Called during the analysis pass. Returning an empty `Vec` means no
|
||||
/// issues were found. The default implementation is a no-op.
|
||||
#[allow(unused_variables)]
|
||||
fn analyze(
|
||||
&self,
|
||||
ctx: &MacroContext,
|
||||
attr: &ResolvedAttr,
|
||||
node: &AttributedNode,
|
||||
) -> Vec<Diagnostic> { vec![] }
|
||||
|
||||
/// Produce rewrite instructions for the attributed PHP node.
|
||||
///
|
||||
/// Called during the transform pass, after all analysis is complete.
|
||||
/// The default implementation is a no-op.
|
||||
#[allow(unused_variables)]
|
||||
fn transform(
|
||||
&self,
|
||||
ctx: &MacroContext,
|
||||
attr: &ResolvedAttr,
|
||||
node: &AttributedNode,
|
||||
) -> Vec<Rewrite> { vec![] }
|
||||
}
|
||||
|
||||
// --------------------------------------------------------------------------------------------- //
|
||||
|
||||
/// Type alias for the analyze handler function pointer.
|
||||
pub type AnalyzeFn = fn(&MacroContext, &ResolvedAttr, &AttributedNode) -> Vec<Diagnostic>;
|
||||
/// Type alias for the transform handler function pointer.
|
||||
pub type TransformFn = fn(&MacroContext, &ResolvedAttr, &AttributedNode) -> Vec<Rewrite>;
|
||||
|
||||
/// An entry in the global macro registry, submitted via `inventory::submit!`.
|
||||
///
|
||||
/// Stores static metadata alongside fn pointers that delegate to the
|
||||
/// handler struct's `PmpMacro` impl, avoiding the need for `dyn` dispatch.
|
||||
///
|
||||
/// Generated via `#[derive(PmpMacro)]`
|
||||
pub struct MacroRegistration {
|
||||
/// Static metadata for this macro — attribute name, targets, params, docs.
|
||||
pub descriptor: &'static MacroDescriptor,
|
||||
/// Delegates to `<Handler as PmpMacro>::analyze`.
|
||||
pub analyze: AnalyzeFn,
|
||||
/// Delegates to `<Handler as PmpMacro>::transform`.
|
||||
pub transform: TransformFn,
|
||||
}
|
||||
|
||||
impl MacroRegistration
|
||||
{
|
||||
pub const fn new(
|
||||
descriptor: &'static MacroDescriptor,
|
||||
analyze: AnalyzeFn,
|
||||
transform: TransformFn,
|
||||
) -> Self
|
||||
{
|
||||
Self { descriptor, analyze, transform }
|
||||
}
|
||||
}
|
||||
|
||||
inventory::collect!(MacroRegistration);
|
||||
|
||||
// --------------------------------------------------------------------------------------------- //
|
||||
|
||||
/// Validated, deduplicated view of the global macro registry.
|
||||
/// Built once on first access via [`registry()`] and cached for the process lifetime.
|
||||
pub struct MacroRegistry {
|
||||
/// Handlers keyed by attribute name for O(1) lookup during processing.
|
||||
handlers: HashMap<&'static str, &'static MacroRegistration>,
|
||||
}
|
||||
|
||||
static REGISTRY: OnceLock<MacroRegistry> = OnceLock::new();
|
||||
|
||||
impl MacroRegistry
|
||||
{
|
||||
/// Returns the global macro registry, validating and building it on first call.
|
||||
///
|
||||
/// Deduplication is checked here — if two macros share the same attribute name
|
||||
/// this will panic with a descriptive message. Subsequent calls are free
|
||||
/// (just an atomic load from the `OnceLock`).
|
||||
///
|
||||
/// This is the only intended way to access registered macros. Direct use of
|
||||
/// `inventory::iter::<MacroRegistration>` bypasses dedup and should be avoided.
|
||||
pub fn registry() -> &'static MacroRegistry {
|
||||
REGISTRY.get_or_init(MacroRegistry::build)
|
||||
}
|
||||
|
||||
fn build() -> Self
|
||||
{
|
||||
let mut handlers: HashMap<&'static str, &'static MacroRegistration> = HashMap::new();
|
||||
|
||||
for reg in inventory::iter::<MacroRegistration>
|
||||
{
|
||||
let name = reg.descriptor.name;
|
||||
|
||||
if handlers.insert(name, reg).is_some() {
|
||||
panic!(
|
||||
"duplicate PmpMacro registration: attribute name \"{name}\" is \
|
||||
registered more than once - check your macro definitions"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Self { handlers }
|
||||
}
|
||||
|
||||
/// Look up a registered macro by its PHP attribute name.
|
||||
pub fn get(&self, name: &str) -> Option<&'static MacroRegistration> {
|
||||
self.handlers.get(name).copied()
|
||||
}
|
||||
|
||||
/// Iterate over all registered macros.
|
||||
pub fn iter(&self) -> impl Iterator<Item = &'static MacroRegistration> {
|
||||
self.handlers.values().copied()
|
||||
}
|
||||
|
||||
/// The number of registered macros.
|
||||
pub fn len(&self) -> usize {
|
||||
self.handlers.len()
|
||||
}
|
||||
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.handlers.is_empty()
|
||||
}
|
||||
}
|
||||
5
crates/pmp-macro/src/lib.rs
Normal file
5
crates/pmp-macro/src/lib.rs
Normal file
@@ -0,0 +1,5 @@
|
||||
#[doc(hidden)]
|
||||
pub extern crate pmp_macro_misc;
|
||||
|
||||
pub use pmp_macro_misc::*;
|
||||
pub use pmp_macro_core::*;
|
||||
Reference in New Issue
Block a user