mirror of
https://github.com/GraphiteEditor/Graphite.git
synced 2026-10-08 15:28:11 +08:00
Make the data model use Item and List types universally, with nodes authored as rank-polymorphic kernels (#4335)
* Add rank polymorphism node audit classifying all 271 nodes
* Implement StaticType for Item<T>
* Generate Item and mapped List wire variants for nodes declaring an Item<T> primary input
* Migrate nine nodes to Item element-wise kernels, dissolving the blending trait boilerplate
* Document the Item kernel implementation and staging plan
* Route Item<Vector> through TaggedValue::TypeDefault
* Add executor integration tests covering the Item and List wire variants
* Collapse element-wise Item/List wire pairs to the List form for conversion insertion
* Migrate sixteen vector modifier nodes to Item element-wise kernels
* Migrate Sample Image, Extend Image to Bounds, and Dehaze to Item element-wise kernels
* Fix bevel_with_transform test to actually exercise the transform attribute
* Implement From<T> for Item<T>
* Register PromoteNode rank adapters wrapping bare values into Item wires
* Insert PromoteNode adapters for Item/List wire pair fields in the preprocessor
* Define a real promote node backing the PromoteNode registry identifiers
* Zip ranked Item connectors by frame slot in the mapped element-wise variant
* Register ItemToListNode singleton raise adapters
* Resolve Item wires against List connectors by inserting promotion adapters at construction
* Rank the Offset Points distance connector and prove mixed-rank resolution end-to-end
* Implement Clampable for Item and List wires with per-variant clamp bounds
* Rank the Round Corners radius connector, exercising hard bounds on a ranked wire
* Implement ApplyTransform for Item
* Add Item wire implementations to the Transform node, keeping rank-0 chains rank 0
* Detect element-wise nodes by lazy primary connectors declaring Output = Item
* Convert Transform to an Item kernel with ranked parameters, delivering the broadcast milestone
* Rename Apply Transform to Bake Transform, baking item transforms on Vector, DAffine2, and DVec2
* Promote bare wires onto Item connectors at resolution via WrapItemNode adapters
* Rank the numeric, vector, and boolean parameters across the migrated element-wise nodes
* Rank the enum, integer, and seed parameters, registering their rank adapters via a consolidated macro
* Amend the audit with the DashPattern value type resolution
* Migrate the string family to Item element-wise kernels
* Unwrap Item wires into bare legacy connectors at resolution via UnwrapItemNode adapters
* Shadow owned node parameters in bodies instead of mut in signatures
* Migrate the math family and string measure nodes to Item element-wise kernels
* Convert the comparison and clamp nodes to Item kernels, dropping unreachable &str rows
* Flat-map expander kernels returning List under the mapped variant's frame
* Migrate the expander nodes to Item kernels flat-mapping under the frame
* Remove the unused peel_list helper
* Rank the raster adjustment and blending kernels, recontextualizing shader nodes onto an Item stand-in
Migrate the 16 adjustment nodes, Mix, Color Overlay, and Gradient Map from whole-List kernels to rank-0 Item kernels, letting the macro derive the List-mapped (zip) variants. Move the Adjust and Blend per-element seams off List onto the element types (add the Raster<CPU> impls, drop the now-dead List impls).
Shader nodes keep their bodies verbatim: PerPixelAdjust re-emits the identical kernel against a transparent no_std Item stand-in, so every Item<T> connector and .element() call resolves to a zero-cost identity on the GPU while the uniform buffer stays bare repr(C). The macro peels Item off ranked uniform params, wraps the fetched texel and uniforms at the entry point, and unwraps the result. This drops the shader_node/Item incompatibility guard. Register rank adapters for the adjustment enums.
* Update the rank polymorphism roadmap for the landed shader-node and adjustments chunk
* Rename the GPU Item stand-in to ShaderItem, aliased as Item at its shader-node import sites
* Flip the vector shape generators to emit rank-0 Item<Vector>
The shape generators (Rectangle, Circle, Ellipse, Arc, Spiral, Polygon, Star, Arrow, Line, Grid, QR Code) each produced exactly one shape wrapped in a singleton List<Vector>. Emit Item<Vector> directly so they connect to the rank-0 content connector of the migrated Transform node. Downstream List consumers receive the value through the existing Item to List promotion.
Relax the element-wise validation so a `()` (generator) primary may return Item<T> without being element-wise. Adapt the Repeat on Points test, which still takes a List content connector, by raising the generator's Item output through a singleton wrapper node.
* Parse ranked Item<T> parameter defaults against the bare element type
A ranked `Item<T>` parameter's default value is a bare, unranked `T` (promoted to the wire at resolution), but the preprocessor was handed the wrapped `Item<T>` type and could not parse the literal, flooding the console with warnings and dropping the defaults. Key the field's default_type metadata off the peeled element type for concrete ranked parameters, leaving generic `Item<T>` primaries and skip_impl nodes untouched.
* Parse an element-wise primary's scalar default against the bare element type
An element-wise node's primary reports its default_type as the List wire form so an unconnected primary defaults to an empty list. But when the primary carries a scalar `#[default]` (such as Root's radicand), that literal must parse as a bare element, not a List. Key the primary's default_type off the bare element type when it has a Default value source, keeping the List form otherwise.
* Add the DashPattern value type for stroke dash sequences
Introduce a rank-0 DashPattern value type (a Vec<f64> of alternating dash and gap lengths) so a stroke's dash pattern is a single frameable value rather than a rank-1 List<f64>. Register it as an auto-generated TaggedValue variant, parse its default from a comma or space separated string, and register its rank adapters. Not yet wired into the Stroke node.
* Rank the Fill and Stroke nodes element-wise and give Stroke a DashPattern connector
Migrate Fill and Stroke to element-wise Item<V> primaries (over Vector and Graphic element types) via a new element-level VectorItemMut trait, so styling one shape yields one shape and rank is preserved instead of promoting the input to a singleton List and emitting a List. The macro derives the List-mapped variant for genuine collections.
Wire the Stroke dash sequence to the new rank-0 DashPattern value type, collapsing the old content x paint x dash cartesian and dropping the IntoF64Vec trait. Update the stroke properties dash widget, the drawing tool, and graph-operation plumbing to read and write DashPattern, and migrate legacy F64Array, F64, and String dash inputs on document open.
Assign Colors stays a whole-collection node: each element's gradient position depends on its index among all siblings, which the element frame does not expose, so it keeps its List primary and the VectorListIterMut trait.
* Register rank adapters for the ranked Stroke enum parameters
The element-wise Stroke node ranks its align, cap, and paint order parameters as Item<StrokeAlign>, Item<StrokeCap>, and Item<PaintOrder>, but those enums lacked promotion adapters, so a bare default enum value could not be promoted to its Item wire and no Stroke variant resolved ("No construct found for node"). Register their rank adapters alongside StrokeJoin.
* Display Item wires in the Data panel without a List's ID column
Add a TableItemLayout impl for Item<T> and recognize Item wire types when introspecting graph data. An Item holds a single element, so it renders as a one-row table of the element plus its attributes with no leading index column, and it labels as its element type T rather than a List's T[]. Add ItemAttributeValues::get_any for the attribute widget dispatch.
* Register MonitorNode for Item wire types so the Data panel introspects them directly
Graph introspection wraps the inspected output in a generic MonitorNode typed to the wire. Without Item<T> monitor registrations, an Item<Vector> output could only be monitored after an Item to List promotion, so the Data panel captured and displayed a List<Vector> despite the connector being Item<Vector>. Register monitors for the Item types the element-wise nodes emit, and add the matching Data panel downcast entries.
* Color and double Item/List wires and cleave layer-stack connectors in the node graph
* Route wire color and rank through hidden nodes and refresh them on type changes
* Rework the DashPattern connector conversions with element-wise promotion and an explicit reducer node
* Rank the remaining value, context, aggregation, and transform nodes onto Item<T> wires
* Back DashPattern with a List<f64> so the Data panel can introspect its lengths
* Carry a single Item<T> through varargs so the Read context nodes emit Item<T> not List<T>
* Relax rank validation for aggregation shapes, add element adapters, and match variants by fewest promotions
* Rank the remaining bare and unnecessarily-List connectors across the node catalog
* Add Graphic::None and the FillChoice paint value, making colors and gradients plain values
* Rename GradientStops to Gradient and the legacy Gradient/Fill structs to LegacyGradient/LegacyFill
* Restore generator frame-from-params ranking to the roadmap as a planned stage
* Rename the ranked-field adapter identifier from PromoteNode to FieldAdapterNode to reflect its full contract
* Unload only the wires whose displayed style changed when types update
* Peel wire rank in the editor's semantic type checks so rank-0 layers are recognized
* Restore the whole-List Transform variant so rank-1 content wires resolve again
* Register the Item wire forms for the Memoize and Context Modification infrastructure nodes
* Give every ranked connector a field adapter and add numeric cast variants for legacy wires
* Key a ranked param's type default off its Item wire form when no literal default exists
* Inherit the layer's content value when splicing a node into an empty chain
* Migrate stale List-form TypeDefault inputs to the definition's current default
* Generate the mapped wire variant only when the element-wise node has a frame source
* Let a bare wire feed a List connector via a wrap-raise adapter, costed as two rank steps
* Add a zip companion to the whole-List Transform so ranked List parameters pair per slot
* Add the Sum, Average, Minimum, Maximum, Any, and All list reducers
* Convert the measure family to element-wise Item kernels per the audit classification
* Prefer the bare element value over the Item type default so ranked params keep their widgets
* Rename GradientStopsUI to GradientUI
* Split Fill's optional transform into a _has_transform bool and a ranked _transform matrix
* Rename the migration-only OptionalDAffine2 TaggedValue to LegacyOptionalDAffine2
* Flow byte buffers as Item<Resource> instead of List<u8> across the byte nodes
* Macro-generate the list-content wire variant, retiring the hand-written Transform-zip, Area, and Centroid companions
* Let ()-primary generators take ranked params and frame over them via the mapped variant, ranking Circle's radius
* Rank the vector shape generators' params to Item, adding a rank-aware input grab to the introspection harness
* Rank the value, color, and text generator params to Item
* Rank the raster, web-request, and context-reader generator params to Item
* Fix the repeat and brush test wirings left behind by the param-ranking sweeps
* Delete the vestigial Some, Unwrap Option, and Size Of debug nodes
* Delete the Attach Attribute node, folding its role into Write Attribute
* Add the Filter and Sort list companion nodes
* Guard the removed-definition migration swap target with a test
* Add the Box Corners value type in place of the rectangle corner radius list
* Split Text to Vector's per-glyph mode into a Text to Vector Glyphs node
* Rank the Combine Channels node's channel connectors to Item
* Make Map Points an element-wise node
* Delete the deprecated Upload Texture node
* Update the implementation roadmap to reflect the landed stages
* Let monitor introspection read rank-0 wires, locking in the layer coercion promotion path
* Prefer the rank-0 default when disconnecting a rank-capable input
* Make Path Modify an element-wise node
* Wrap node paths in a NodeIdPath newtype so they flow as a single Item
* Give Item<Raster<CPU>> a default so an unconnected Brush background resolves
* Stop the Brush node from setting layer attributes its paint operation doesn't produce
* Present-gate Flatten Path's adopted layer path like its fill and stroke
* Gate carried layer attributes on static column presence, not runtime values
* Give the remaining graphic Item<T> types a default so unconnected primaries resolve
* Dispatch a ranked param's Properties widget from its rank-0 element type
* Make Extract Transform an element-wise node, restoring the Origins to Polyline body
* Rename Flatten Path to Combine Paths
* Stamp Legacy Layer Extend's adopted layer path as a readable NodeIdPath
* Drop the dead List<u8> and List<NodeId> wire rows
* Rank Flatten Graphic's Fully Flatten toggle to Item
* Update the implementation roadmap with the endgame scope
* Make Combine Paths a reducer that collapses the whole frame into one path
* Stop type-converter nodes from carrying the source's unrelated attributes
* Format the Origins to Polyline regression test
* Wrap the Brush node's trace in a BrushTrace newtype so it flows as one value
* Make Switch a framed element-wise select, bundling whole collections
* Widen and align element-type coverage across the list and graphic nodes
* Register the compiler's cache chain pair for every ranked enum and newtype wire
* Fix wire colors for Passthrough outputs, bundled lists, and bools, and widen list wires
* Represent List wire types structurally with Type::List, replacing name-parsed rank promotion
* Treat scope and data fields as environment, rank scope wires as Item, and feed the render boundary through a context vararg
* Delete the vestigial Clone debug node
* Reinstate Upload Texture as an element-wise node and fix the GPU variants' scope executor and rank adapters
* Rename Combine Paths back to Flatten Path, deferring that rename to its own PR
* Deduplicate the promotion adapter registrations into the field adapter macro
* Rank Write Attribute's value connector to Item<AttributeValueDyn>, retiring the UnwrapItem bridge
* Vertical wire styling
* Store the editor layer path attribute as a bare NodeIdPath, not an Item<NodeIdPath>
* Rank Context Modification's features connector to Item<ContextFeatures>, dropping the dead memoize row
* Rank Path Modify's modification parameter to Item<Box<VectorModification>>
* Rename the field adapter node family to input adapter
* Drop the dead bare scalar rows from Context Modification's implementations list
* Move the dynamic executor's test module into its own file
* Drop the registry's unreachable bare rows for Memoize, the cache chain, and ConvertNode
* Materialize stored TaggedValues as ranked Item wires at the source
* Remove the bare-wire promotion and adapter machinery made dead by ranked value materialization
* Plant the input adapter for List-only inputs, composing position conversion from standard rows
* Consolidate Into/Convert conversions into the input adapter umbrella and rename the rank adapter identifiers
* Fix grouped layers gaining a phantom None stack element from the FillChoice default hijacking every List<Graphic> disconnect
* Enforce ranked node inputs in the macro, rejecting bare wire declarations
* Remove the unit Context => () machinery rows, leaving () purely as the no-primary sentinel
* Add a --signatures rank-audit mode to node-docs for the ranked-wire migration
* Remove the node-docs --signatures rank-audit mode now that ranked wires are enforced
* Migrate legacy no-color values on the Black & White, Color Overlay, and Empty Image color inputs
* Rewrite the element-wise accessor wire type at the primary input, not raw index 0
* Register the cache chain for Resource wires, replacing the lone hand-written Monitor row
* Gate the remaining Raster<GPU> registry rows behind the gpu feature
* Let List<DVec2> wires erase to ListDyn for the attribute reader and element counter
* Rename Extract Element to Item at Index, Count Elements to List Length, and Omit Element to Remove at Index
* Store paint picks as plain color/gradient values, removing the FillChoice value type
* Code review restructuring
* Sort by the consumed sort_key attribute or natural element order, adding the Sort Key node
* Remove the new list-combinator and reducer nodes to defer them to a follow-up PR
* Parse Fill and Stroke color defaults through the paint wire's Graphic element
* Emit ranked implementation-row default types structurally so their element TypeIds survive to default-literal parsing
* Exempt the deliberate no-paint choice from the stale List-form TypeDefault migration
* Migrate the legacy 4-input Fill directly to the split has-transform shape
* Upgrade the demo artwork
* Fix the valid AI review findings: Item eq/hash contract, table-era no-paint migration, quantize List rows, and other smaller issues
* Remove the rank polymorphism working documents
* Hash Item attribute values directly instead of debug-formatting them, speeding up cached evaluation
* Replace the data panel's dead bare-wire downcast arms with full coverage of the ranked monitor row types
* Derive PartialEq for Item now that attributes participate in equality
* Extend the data panel's attribute dispatchers with the newly supported scalar and choice enum types
* Add List monitor rows for the framed numeric conversion outputs so inspecting them resolves, with matching data panel arms
This commit is contained in:
@@ -0,0 +1,36 @@
|
||||
[package]
|
||||
name = "graphite-proc-macros"
|
||||
publish = false
|
||||
version = "0.0.0"
|
||||
rust-version = "1.88"
|
||||
authors = ["Graphite Authors <contact@graphite.art>"]
|
||||
edition = "2024"
|
||||
readme = "../README.md"
|
||||
homepage = "https://graphite.art"
|
||||
repository = "https://github.com/GraphiteEditor/Graphite"
|
||||
license = "Apache-2.0"
|
||||
|
||||
[lib]
|
||||
path = "src/lib.rs"
|
||||
proc-macro = true
|
||||
|
||||
[features]
|
||||
default = ["serde-discriminant"]
|
||||
serde-discriminant = []
|
||||
|
||||
[dependencies]
|
||||
# Workspace dependencies
|
||||
proc-macro2 = { workspace = true }
|
||||
syn = { workspace = true }
|
||||
quote = { workspace = true }
|
||||
convert_case = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
# Local dependencies
|
||||
editor = { path = "../editor", package = "graphite-editor" }
|
||||
|
||||
# Workspace dependencies
|
||||
serde = { workspace = true }
|
||||
|
||||
[package.metadata.cargo-shear]
|
||||
ignored = ["graphite-editor"]
|
||||
@@ -0,0 +1,55 @@
|
||||
use proc_macro2::{Span, TokenStream};
|
||||
use syn::{Data, DeriveInput};
|
||||
|
||||
pub fn derive_as_message_impl(input_item: TokenStream) -> syn::Result<TokenStream> {
|
||||
let input = syn::parse2::<DeriveInput>(input_item).unwrap();
|
||||
|
||||
let data = match input.data {
|
||||
Data::Enum(data) => data,
|
||||
_ => return Err(syn::Error::new(Span::call_site(), "Tried to derive AsMessage for non-enum")),
|
||||
};
|
||||
|
||||
let input_type = input.ident;
|
||||
|
||||
let (globs, names) = data
|
||||
.variants
|
||||
.iter()
|
||||
.map(|var| {
|
||||
let var_name = &var.ident;
|
||||
let var_name_s = var.ident.to_string();
|
||||
if var.attrs.iter().any(|a| a.path().is_ident("child")) {
|
||||
(
|
||||
quote::quote! {
|
||||
#input_type::#var_name(child)
|
||||
},
|
||||
quote::quote! {
|
||||
format!("{}.{}", #var_name_s, child.local_name())
|
||||
},
|
||||
)
|
||||
} else {
|
||||
(
|
||||
quote::quote! {
|
||||
#input_type::#var_name { .. }
|
||||
},
|
||||
quote::quote! {
|
||||
#var_name_s.to_string()
|
||||
},
|
||||
)
|
||||
}
|
||||
})
|
||||
.unzip::<_, _, Vec<_>, Vec<_>>();
|
||||
|
||||
let res = quote::quote! {
|
||||
impl AsMessage for #input_type {
|
||||
fn local_name(self) -> String {
|
||||
match self {
|
||||
#(
|
||||
#globs => #names
|
||||
),*
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
Ok(res)
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
use crate::helpers::call_site_ident;
|
||||
use proc_macro2::Ident;
|
||||
use proc_macro2::TokenStream;
|
||||
use quote::ToTokens;
|
||||
use syn::Token;
|
||||
use syn::parse::{Parse, ParseStream};
|
||||
use syn::{ItemEnum, TypePath};
|
||||
|
||||
struct MessageArgs {
|
||||
pub _top_parent: TypePath,
|
||||
pub _comma1: Token![,],
|
||||
pub parent: TypePath,
|
||||
pub _comma2: Token![,],
|
||||
pub variant: Ident,
|
||||
}
|
||||
|
||||
impl Parse for MessageArgs {
|
||||
fn parse(input: ParseStream) -> syn::Result<Self> {
|
||||
Ok(Self {
|
||||
_top_parent: input.parse()?,
|
||||
_comma1: input.parse()?,
|
||||
parent: input.parse()?,
|
||||
_comma2: input.parse()?,
|
||||
variant: input.parse()?,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
struct TopLevelMessageArgs {
|
||||
pub parent: TypePath,
|
||||
pub _comma2: Token![,],
|
||||
pub variant: Ident,
|
||||
}
|
||||
|
||||
impl Parse for TopLevelMessageArgs {
|
||||
fn parse(input: ParseStream) -> syn::Result<Self> {
|
||||
Ok(Self {
|
||||
parent: input.parse()?,
|
||||
_comma2: input.parse()?,
|
||||
variant: input.parse()?,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub fn combined_message_attrs_impl(attr: TokenStream, input_item: TokenStream) -> syn::Result<TokenStream> {
|
||||
if attr.is_empty() {
|
||||
return top_level_impl(input_item);
|
||||
}
|
||||
|
||||
let mut input = syn::parse2::<ItemEnum>(input_item)?;
|
||||
|
||||
let (parent_is_top, parent, variant) = match syn::parse2::<MessageArgs>(attr.clone()) {
|
||||
Ok(x) => (false, x.parent, x.variant),
|
||||
Err(_) => {
|
||||
let x = syn::parse2::<TopLevelMessageArgs>(attr)?;
|
||||
(true, x.parent, x.variant)
|
||||
}
|
||||
};
|
||||
|
||||
let parent_discriminant = quote::quote! {
|
||||
<#parent as ToDiscriminant>::Discriminant
|
||||
};
|
||||
|
||||
input.attrs.push(syn::parse_quote! { #[derive(ToDiscriminant, TransitiveChild, HierarchicalTree)] });
|
||||
input.attrs.push(syn::parse_quote! { #[parent(#parent, #parent::#variant)] });
|
||||
if parent_is_top {
|
||||
input.attrs.push(syn::parse_quote! { #[parent_is_top] });
|
||||
}
|
||||
input
|
||||
.attrs
|
||||
.push(syn::parse_quote! { #[discriminant_attr(derive(Debug, Copy, Clone, PartialEq, Eq, Hash, AsMessage, TransitiveChild))] });
|
||||
input
|
||||
.attrs
|
||||
.push(syn::parse_quote! { #[discriminant_attr(parent(#parent_discriminant, #parent_discriminant::#variant))] });
|
||||
if parent_is_top {
|
||||
input.attrs.push(syn::parse_quote! { #[discriminant_attr(parent_is_top)] });
|
||||
}
|
||||
|
||||
for var in &mut input.variants {
|
||||
if let Some(attr) = var.attrs.iter_mut().find(|a| a.path().is_ident("child")) {
|
||||
let path = match &mut attr.meta {
|
||||
syn::Meta::Path(path) => path,
|
||||
syn::Meta::List(list) => &mut list.path,
|
||||
syn::Meta::NameValue(named_value) => &mut named_value.path,
|
||||
};
|
||||
let last_segment = path.segments.last_mut().unwrap();
|
||||
last_segment.ident = call_site_ident("sub_discriminant");
|
||||
var.attrs.push(syn::parse_quote! {
|
||||
#[discriminant_attr(child)]
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
Ok(input.into_token_stream())
|
||||
}
|
||||
|
||||
fn top_level_impl(input_item: TokenStream) -> syn::Result<TokenStream> {
|
||||
let mut input = syn::parse2::<ItemEnum>(input_item)?;
|
||||
|
||||
input.attrs.push(syn::parse_quote! { #[derive(ToDiscriminant, HierarchicalTree)] });
|
||||
input.attrs.push(syn::parse_quote! { #[discriminant_attr(derive(Debug, Copy, Clone, PartialEq, Eq, Hash, AsMessage))] });
|
||||
|
||||
for var in &mut input.variants {
|
||||
if let Some(attr) = var.attrs.iter_mut().find(|a| a.path().is_ident("child")) {
|
||||
let path = match &mut attr.meta {
|
||||
syn::Meta::Path(path) => path,
|
||||
syn::Meta::List(list) => &mut list.path,
|
||||
syn::Meta::NameValue(named_value) => &mut named_value.path,
|
||||
};
|
||||
let last_segment = path.segments.last_mut().unwrap();
|
||||
last_segment.ident = call_site_ident("sub_discriminant");
|
||||
var.attrs.push(syn::parse_quote! {
|
||||
#[discriminant_attr(child)]
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
let input_type = &input.ident;
|
||||
let discriminant = call_site_ident(format!("{input_type}Discriminant"));
|
||||
|
||||
Ok(quote::quote! {
|
||||
#input
|
||||
|
||||
impl TransitiveChild for #input_type {
|
||||
type TopParent = Self;
|
||||
type Parent = Self;
|
||||
}
|
||||
|
||||
impl TransitiveChild for #discriminant {
|
||||
type TopParent = Self;
|
||||
type Parent = Self;
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
use crate::helpers::call_site_ident;
|
||||
use proc_macro2::{Ident, Span, TokenStream};
|
||||
use syn::spanned::Spanned;
|
||||
use syn::{Attribute, Data, DeriveInput, Field, Fields, ItemEnum, MetaList};
|
||||
|
||||
pub fn derive_discriminant_impl(input_item: TokenStream) -> syn::Result<TokenStream> {
|
||||
let input = syn::parse2::<DeriveInput>(input_item).unwrap();
|
||||
|
||||
let mut data = match input.data {
|
||||
Data::Enum(data) => data,
|
||||
_ => return Err(syn::Error::new(Span::call_site(), "Tried to derive a discriminant for non-enum")),
|
||||
};
|
||||
|
||||
let mut is_sub_discriminant = vec![];
|
||||
let mut attr_errs = vec![];
|
||||
|
||||
for var in &mut data.variants {
|
||||
if var.attrs.iter().any(|a| a.path().is_ident("sub_discriminant")) {
|
||||
match var.fields.len() {
|
||||
1 => {
|
||||
let Field { ty, .. } = var.fields.iter_mut().next().unwrap();
|
||||
*ty = syn::parse_quote! {
|
||||
<#ty as ToDiscriminant>::Discriminant
|
||||
};
|
||||
is_sub_discriminant.push(true);
|
||||
}
|
||||
n => unimplemented!("#[sub_discriminant] on variants with {n} fields is not supported (for now)"),
|
||||
}
|
||||
} else {
|
||||
var.fields = Fields::Unit;
|
||||
is_sub_discriminant.push(false);
|
||||
}
|
||||
let mut retain = vec![];
|
||||
for (i, a) in var.attrs.iter_mut().enumerate() {
|
||||
if a.path().is_ident("discriminant_attr") {
|
||||
match a.meta.require_list() {
|
||||
Ok(MetaList { tokens, .. }) => {
|
||||
let attr: Attribute = syn::parse_quote! {
|
||||
#[#tokens]
|
||||
};
|
||||
*a = attr;
|
||||
retain.push(i);
|
||||
}
|
||||
Err(e) => {
|
||||
attr_errs.push(syn::Error::new(a.span(), e));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
var.attrs = var.attrs.iter().enumerate().filter(|(i, _)| retain.contains(i)).map(|(_, x)| x.clone()).collect();
|
||||
}
|
||||
|
||||
let attrs = input
|
||||
.attrs
|
||||
.iter()
|
||||
.cloned()
|
||||
.filter_map(|a| {
|
||||
let a_span = a.span();
|
||||
a.path()
|
||||
.is_ident("discriminant_attr")
|
||||
.then(|| match a.meta.require_list() {
|
||||
Ok(MetaList { tokens, .. }) => {
|
||||
let attr: Attribute = syn::parse_quote! {
|
||||
#[#tokens]
|
||||
};
|
||||
Some(attr)
|
||||
}
|
||||
Err(e) => {
|
||||
attr_errs.push(syn::Error::new(a_span, e));
|
||||
None
|
||||
}
|
||||
})
|
||||
.and_then(|opt| opt)
|
||||
})
|
||||
.collect::<Vec<Attribute>>();
|
||||
|
||||
if !attr_errs.is_empty() {
|
||||
return Err(attr_errs
|
||||
.into_iter()
|
||||
.reduce(|mut l, r| {
|
||||
l.combine(r);
|
||||
l
|
||||
})
|
||||
.unwrap());
|
||||
}
|
||||
|
||||
let discriminant = ItemEnum {
|
||||
attrs,
|
||||
vis: input.vis,
|
||||
enum_token: data.enum_token,
|
||||
ident: call_site_ident(format!("{}Discriminant", input.ident)),
|
||||
generics: input.generics,
|
||||
brace_token: data.brace_token,
|
||||
variants: data.variants,
|
||||
};
|
||||
|
||||
let input_type = &input.ident;
|
||||
let discriminant_type = &discriminant.ident;
|
||||
let variant = &discriminant.variants.iter().map(|var| &var.ident).collect::<Vec<&Ident>>();
|
||||
|
||||
let (pattern, value) = is_sub_discriminant
|
||||
.into_iter()
|
||||
.map(|b| {
|
||||
if b {
|
||||
(quote::quote! {(x)}, quote::quote! {(x.to_discriminant())})
|
||||
} else {
|
||||
(quote::quote! {{..}}, Default::default())
|
||||
}
|
||||
})
|
||||
.unzip::<_, _, Vec<_>, Vec<_>>();
|
||||
#[cfg(feature = "serde-discriminant")]
|
||||
let serde = quote::quote! {
|
||||
#[derive(serde::Serialize, serde::Deserialize)]
|
||||
};
|
||||
|
||||
#[cfg(not(feature = "serde-discriminant"))]
|
||||
let serde = quote::quote! {};
|
||||
|
||||
let res = quote::quote! {
|
||||
#serde
|
||||
#discriminant
|
||||
|
||||
impl ToDiscriminant for #input_type {
|
||||
type Discriminant = #discriminant_type;
|
||||
|
||||
fn to_discriminant(&self) -> #discriminant_type {
|
||||
match self {
|
||||
#(
|
||||
#input_type::#variant #pattern => #discriminant_type::#variant #value
|
||||
),*
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<&#input_type> for #discriminant_type {
|
||||
fn from(x: &#input_type) -> #discriminant_type {
|
||||
x.to_discriminant()
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
Ok(res)
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
use convert_case::{Case, Casing};
|
||||
use proc_macro2::TokenStream;
|
||||
use quote::{quote, quote_spanned};
|
||||
use syn::spanned::Spanned;
|
||||
use syn::{Error, FnArg, Ident, Item, ItemFn, ItemMod, ItemUse, Pat, Visibility};
|
||||
|
||||
pub fn editor_commands_impl(attr: TokenStream, module: ItemMod) -> syn::Result<TokenStream> {
|
||||
if !attr.is_empty() {
|
||||
return Err(Error::new(attr.span(), "#[editor_commands] takes no arguments"));
|
||||
}
|
||||
for attr in &module.attrs {
|
||||
if !attr.path().is_ident("doc") {
|
||||
return Err(Error::new(attr.span(), "the #[editor_commands] module may not have other attributes"));
|
||||
}
|
||||
}
|
||||
let Some((_, items)) = module.content else {
|
||||
return Err(Error::new(module.mod_token.span, "#[editor_commands] requires a module with an inline body"));
|
||||
};
|
||||
|
||||
let mut imports: Vec<ItemUse> = Vec::new();
|
||||
let mut functions: Vec<ItemFn> = Vec::new();
|
||||
for item in items {
|
||||
match item {
|
||||
Item::Use(import) => imports.push(import),
|
||||
Item::Fn(function) => functions.push(function),
|
||||
other => return Err(Error::new(other.span(), "only `use` imports and command functions may appear in an #[editor_commands] module")),
|
||||
}
|
||||
}
|
||||
|
||||
let mut variants = TokenStream::new();
|
||||
let mut stubs = TokenStream::new();
|
||||
let mut arms = TokenStream::new();
|
||||
|
||||
for function in &functions {
|
||||
for attr in &function.attrs {
|
||||
if !attr.path().is_ident("doc") {
|
||||
return Err(Error::new(
|
||||
attr.span(),
|
||||
"command functions may not have attributes; anything that doesn't fit the `fn name(args…) -> Message` contract belongs in a plain impl block",
|
||||
));
|
||||
}
|
||||
}
|
||||
if !matches!(function.vis, Visibility::Inherited) {
|
||||
return Err(Error::new(
|
||||
function.span(),
|
||||
"command functions have no visibility modifier; the macro generates the public JS-facing stub",
|
||||
));
|
||||
}
|
||||
|
||||
let signature = &function.sig;
|
||||
if let Some(receiver) = signature.receiver() {
|
||||
return Err(Error::new(receiver.span(), "command functions take no `self`; they are pure `args… -> Message` translations"));
|
||||
}
|
||||
if !signature.generics.params.is_empty() || signature.asyncness.is_some() || signature.unsafety.is_some() {
|
||||
return Err(Error::new(signature.span(), "command functions must be plain non-generic, non-async, safe functions"));
|
||||
}
|
||||
|
||||
let docs = &function.attrs;
|
||||
let fn_name = &signature.ident;
|
||||
let variant = Ident::new(&fn_name.to_string().to_case(Case::Pascal), fn_name.span());
|
||||
let js_name = Ident::new(&fn_name.to_string().to_case(Case::Camel), fn_name.span());
|
||||
|
||||
let mut param_names = Vec::new();
|
||||
let mut param_types = Vec::new();
|
||||
for parameter in &signature.inputs {
|
||||
let FnArg::Typed(pat_type) = parameter else { unreachable!("receiver is rejected above") };
|
||||
let Pat::Ident(pat_ident) = &*pat_type.pat else {
|
||||
return Err(Error::new(pat_type.span(), "command parameters must be plain identifiers"));
|
||||
};
|
||||
param_names.push(&pat_ident.ident);
|
||||
param_types.push(&*pat_type.ty);
|
||||
}
|
||||
|
||||
let return_type = &signature.output;
|
||||
let body = &function.block;
|
||||
|
||||
let span = fn_name.span();
|
||||
variants.extend(quote_spanned! {span=>
|
||||
#(#docs)*
|
||||
#variant { #(#param_names: #param_types,)* },
|
||||
});
|
||||
stubs.extend(quote_spanned! {span=>
|
||||
#(#docs)*
|
||||
#[cfg(not(feature = "native"))]
|
||||
#[wasm_bindgen(js_name = #js_name)]
|
||||
pub fn #fn_name(&self, #(#param_names: #param_types,)*) {
|
||||
self.dispatch((move || #return_type #body)())
|
||||
}
|
||||
#(#docs)*
|
||||
#[cfg(feature = "native")]
|
||||
#[wasm_bindgen(js_name = #js_name)]
|
||||
pub fn #fn_name(&self, #(#param_names: #param_types,)*) {
|
||||
self.send(EditorCommand::#variant { #(#param_names,)* })
|
||||
}
|
||||
});
|
||||
arms.extend(quote_spanned! {span=>
|
||||
EditorCommand::#variant { #(#param_names,)* } => #body,
|
||||
});
|
||||
}
|
||||
|
||||
Ok(quote! {
|
||||
#(
|
||||
#[cfg(feature = "editor")]
|
||||
#imports
|
||||
)*
|
||||
|
||||
#[cfg(any(feature = "native", not(target_family = "wasm")))]
|
||||
#[derive(serde::Serialize, serde::Deserialize)]
|
||||
pub enum EditorCommand {
|
||||
#variants
|
||||
}
|
||||
|
||||
#[cfg(all(feature = "editor", any(feature = "native", not(target_family = "wasm"))))]
|
||||
impl From<EditorCommand> for Message {
|
||||
fn from(command: EditorCommand) -> Self {
|
||||
match command {
|
||||
#arms
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_family = "wasm")]
|
||||
#[wasm_bindgen]
|
||||
impl EditorWrapper {
|
||||
#stubs
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
use crate::helpers::clean_rust_type_syntax;
|
||||
use proc_macro2::{Span, TokenStream};
|
||||
use quote::{ToTokens, format_ident, quote};
|
||||
use syn::{Data, DeriveInput, Fields, Type, parse2};
|
||||
|
||||
pub fn derive_extract_field_impl(input: TokenStream) -> syn::Result<TokenStream> {
|
||||
let input = parse2::<DeriveInput>(input)?;
|
||||
let struct_name = &input.ident;
|
||||
let generics = &input.generics;
|
||||
let (impl_generics, ty_generics, where_clause) = generics.split_for_impl();
|
||||
|
||||
let line_number = struct_name.span().start().line;
|
||||
|
||||
let fields = match &input.data {
|
||||
Data::Struct(data) => match &data.fields {
|
||||
Fields::Named(fields) => &fields.named,
|
||||
_ => return Err(syn::Error::new(Span::call_site(), "ExtractField only works on structs with named fields")),
|
||||
},
|
||||
_ => return Err(syn::Error::new(Span::call_site(), "ExtractField only works on structs")),
|
||||
};
|
||||
|
||||
let mut field_line = Vec::new();
|
||||
// Extract field names and types as strings at compile time
|
||||
let field_info = fields
|
||||
.iter()
|
||||
.map(|field| {
|
||||
let ident = field.ident.as_ref().unwrap();
|
||||
let name = ident.to_string();
|
||||
let ty = clean_rust_type_syntax(field.ty.to_token_stream().to_string());
|
||||
let line = ident.span().start().line;
|
||||
field_line.push(line);
|
||||
(name, ty)
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
let field_str = field_info.into_iter().map(|(name, ty)| (format!("{name}: {ty}")));
|
||||
|
||||
let res = quote! {
|
||||
impl #impl_generics ExtractField for #struct_name #ty_generics #where_clause {
|
||||
fn field_types() -> Vec<(String, usize)> {
|
||||
vec![
|
||||
#((String::from(#field_str), #field_line)),*
|
||||
]
|
||||
}
|
||||
|
||||
fn print_field_types() {
|
||||
for (field, line) in Self::field_types() {
|
||||
println!("{} at line {}", field, line);
|
||||
}
|
||||
}
|
||||
|
||||
fn path() -> &'static str {
|
||||
file!()
|
||||
}
|
||||
|
||||
fn line_number() -> usize {
|
||||
#line_number
|
||||
}
|
||||
|
||||
}
|
||||
};
|
||||
|
||||
Ok(res)
|
||||
}
|
||||
@@ -0,0 +1,199 @@
|
||||
use proc_macro2::{Ident, TokenStream};
|
||||
use std::collections::HashMap;
|
||||
use syn::parse::{Parse, ParseStream};
|
||||
use syn::punctuated::Punctuated;
|
||||
use syn::token::Paren;
|
||||
use syn::{LitStr, Token, parenthesized};
|
||||
|
||||
pub struct IdentList {
|
||||
pub parts: Punctuated<Ident, Token![,]>,
|
||||
}
|
||||
|
||||
impl Parse for IdentList {
|
||||
fn parse(input: ParseStream) -> syn::Result<Self> {
|
||||
let content;
|
||||
let _paren_token = parenthesized!(content in input);
|
||||
Ok(Self {
|
||||
parts: Punctuated::parse_terminated(&content)?,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Parses `("some text")`
|
||||
pub struct AttrInnerSingleString {
|
||||
_paren_token: Paren,
|
||||
pub content: LitStr,
|
||||
}
|
||||
|
||||
impl Parse for AttrInnerSingleString {
|
||||
fn parse(input: ParseStream) -> syn::Result<Self> {
|
||||
let content;
|
||||
let _paren_token = parenthesized!(content in input);
|
||||
Ok(Self {
|
||||
_paren_token,
|
||||
content: content.parse()?,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Parses `key="value"`
|
||||
pub struct KeyEqString {
|
||||
key: Ident,
|
||||
_eq_token: Token![=],
|
||||
lit: LitStr,
|
||||
}
|
||||
|
||||
impl Parse for KeyEqString {
|
||||
fn parse(input: ParseStream) -> syn::Result<Self> {
|
||||
Ok(Self {
|
||||
key: input.parse()?,
|
||||
_eq_token: input.parse()?,
|
||||
lit: input.parse()?,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Parses `(key="value", key="value", …)`
|
||||
pub struct AttrInnerKeyStringMap {
|
||||
parts: Punctuated<KeyEqString, Token![,]>,
|
||||
}
|
||||
|
||||
impl Parse for AttrInnerKeyStringMap {
|
||||
fn parse(input: ParseStream) -> syn::Result<Self> {
|
||||
Ok(Self {
|
||||
parts: Punctuated::parse_terminated(input)?,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl AttrInnerKeyStringMap {
|
||||
pub fn multi_into_iter(iter: impl IntoIterator<Item = Self>) -> impl Iterator<Item = (Ident, Vec<LitStr>)> {
|
||||
use std::collections::hash_map::Entry;
|
||||
|
||||
let mut res = Vec::<(Ident, Vec<LitStr>)>::new();
|
||||
let mut idx = HashMap::<Ident, usize>::new();
|
||||
|
||||
for part in iter.into_iter().flat_map(|x: Self| x.parts) {
|
||||
match idx.entry(part.key) {
|
||||
Entry::Occupied(occ) => {
|
||||
res[*occ.get()].1.push(part.lit);
|
||||
}
|
||||
Entry::Vacant(vac) => {
|
||||
let ident = vac.key().clone();
|
||||
vac.insert(res.len());
|
||||
res.push((ident, vec![part.lit]));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
res.into_iter()
|
||||
}
|
||||
}
|
||||
|
||||
/// Parses `(left, right)`
|
||||
pub struct Pair<F, S> {
|
||||
pub first: F,
|
||||
pub sep: Token![,],
|
||||
pub second: S,
|
||||
}
|
||||
|
||||
impl<F, S> Parse for Pair<F, S>
|
||||
where
|
||||
F: Parse,
|
||||
S: Parse,
|
||||
{
|
||||
fn parse(input: ParseStream) -> syn::Result<Self> {
|
||||
Ok(Self {
|
||||
first: input.parse()?,
|
||||
sep: input.parse()?,
|
||||
second: input.parse()?,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// parses `(...)`
|
||||
pub struct ParenthesizedTokens {
|
||||
pub paren: Paren,
|
||||
pub tokens: TokenStream,
|
||||
}
|
||||
|
||||
impl Parse for ParenthesizedTokens {
|
||||
fn parse(input: ParseStream) -> syn::Result<Self> {
|
||||
let content;
|
||||
let paren = parenthesized!(content in input);
|
||||
Ok(Self { paren, tokens: content.parse()? })
|
||||
}
|
||||
}
|
||||
|
||||
/// parses a comma-delimeted list of `T`s with optional trailing comma
|
||||
pub struct SimpleCommaDelimeted<T>(pub Vec<T>);
|
||||
|
||||
impl<T: Parse> Parse for SimpleCommaDelimeted<T> {
|
||||
fn parse(input: ParseStream) -> syn::Result<Self> {
|
||||
let punctuated = Punctuated::<T, Token![,]>::parse_terminated(input)?;
|
||||
Ok(Self(punctuated.into_iter().collect()))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn attr_inner_single_string() {
|
||||
let res = syn::parse2::<AttrInnerSingleString>(quote::quote! {
|
||||
("a string literal")
|
||||
});
|
||||
assert!(res.is_ok());
|
||||
assert_eq!(res.ok().unwrap().content.value(), "a string literal");
|
||||
|
||||
let res = syn::parse2::<AttrInnerSingleString>(quote::quote! {
|
||||
wrong, "stuff"
|
||||
});
|
||||
assert!(res.is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn key_eq_string() {
|
||||
let res = syn::parse2::<KeyEqString>(quote::quote! {
|
||||
key="value"
|
||||
});
|
||||
assert!(res.is_ok());
|
||||
let res = res.ok().unwrap();
|
||||
assert_eq!(res.key, "key");
|
||||
assert_eq!(res.lit.value(), "value");
|
||||
|
||||
let res = syn::parse2::<KeyEqString>(quote::quote! {
|
||||
wrong, "stuff"
|
||||
});
|
||||
assert!(res.is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn attr_inner_key_string_map() {
|
||||
let res = syn::parse2::<AttrInnerKeyStringMap>(quote::quote! {
|
||||
key="value", key2="value2"
|
||||
});
|
||||
assert!(res.is_ok());
|
||||
let res = res.ok().unwrap();
|
||||
for (item, (k, v)) in res.parts.into_iter().zip(vec![("key", "value"), ("key2", "value2")]) {
|
||||
assert_eq!(item.key, k);
|
||||
assert_eq!(item.lit.value(), v);
|
||||
}
|
||||
|
||||
let res = syn::parse2::<AttrInnerKeyStringMap>(quote::quote! {
|
||||
key="value", key2="value2",
|
||||
});
|
||||
assert!(res.is_ok());
|
||||
let res = res.ok().unwrap();
|
||||
for (item, (k, v)) in res.parts.into_iter().zip(vec![("key", "value"), ("key2", "value2")]) {
|
||||
assert_eq!(item.key, k);
|
||||
assert_eq!(item.lit.value(), v);
|
||||
}
|
||||
|
||||
let res = syn::parse2::<AttrInnerKeyStringMap>(quote::quote! {
|
||||
wrong, "stuff"
|
||||
});
|
||||
assert!(res.is_err());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
use proc_macro2::{Ident, Span};
|
||||
use syn::punctuated::Punctuated;
|
||||
use syn::{Path, PathArguments, PathSegment, Token};
|
||||
|
||||
/// Returns `Ok(Vec<T>)` if all items are `Ok(T)`, else returns a combination of every error encountered (not just the first one)
|
||||
// Allowing this lint because this is a false positive in this case. The fold can only be changed into a `try_fold` if the closure
|
||||
// doesn't have an error case. See for details: https://rust-lang.github.io/rust-clippy/master/index.html#/manual_try_fold.
|
||||
#[allow(clippy::manual_try_fold)]
|
||||
pub fn fold_error_iter<T>(iter: impl Iterator<Item = syn::Result<T>>) -> syn::Result<Vec<T>> {
|
||||
iter.fold(Ok(vec![]), |acc, x| match acc {
|
||||
Ok(mut v) => x.map(|x| {
|
||||
v.push(x);
|
||||
v
|
||||
}),
|
||||
Err(mut e) => match x {
|
||||
Ok(_) => Err(e),
|
||||
Err(e2) => {
|
||||
e.combine(e2);
|
||||
Err(e)
|
||||
}
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
/// Creates an ident at the call site
|
||||
pub fn call_site_ident<S: AsRef<str>>(s: S) -> Ident {
|
||||
Ident::new(s.as_ref(), Span::call_site())
|
||||
}
|
||||
|
||||
/// Creates the path `left::right` from the identifiers `left` and `right`
|
||||
pub fn two_segment_path(left_ident: Ident, right_ident: Ident) -> Path {
|
||||
let mut segments: Punctuated<PathSegment, Token![::]> = Punctuated::new();
|
||||
segments.push(PathSegment {
|
||||
ident: left_ident,
|
||||
arguments: PathArguments::None,
|
||||
});
|
||||
segments.push(PathSegment {
|
||||
ident: right_ident,
|
||||
arguments: PathArguments::None,
|
||||
});
|
||||
|
||||
Path { leading_colon: None, segments }
|
||||
}
|
||||
|
||||
pub fn clean_rust_type_syntax(input: String) -> String {
|
||||
let mut result = String::new();
|
||||
let mut chars = input.chars().peekable();
|
||||
|
||||
while let Some(c) = chars.next() {
|
||||
match c {
|
||||
'&' => {
|
||||
result.push('&');
|
||||
while let Some(' ') = chars.peek() {
|
||||
chars.next();
|
||||
}
|
||||
}
|
||||
'<' => {
|
||||
while let Some(' ') = result.chars().next_back() {
|
||||
result.pop();
|
||||
}
|
||||
result.push('<');
|
||||
while let Some(' ') = chars.peek() {
|
||||
chars.next();
|
||||
}
|
||||
}
|
||||
'>' => {
|
||||
while let Some(' ') = result.chars().next_back() {
|
||||
result.pop();
|
||||
}
|
||||
result.push('>');
|
||||
while let Some(' ') = chars.peek() {
|
||||
chars.next();
|
||||
}
|
||||
}
|
||||
'-' => {
|
||||
if let Some('>') = chars.peek() {
|
||||
while let Some(' ') = result.chars().next_back() {
|
||||
result.pop();
|
||||
}
|
||||
result.push_str(" -> ");
|
||||
chars.next();
|
||||
while let Some(' ') = chars.peek() {
|
||||
chars.next();
|
||||
}
|
||||
} else {
|
||||
result.push(c);
|
||||
}
|
||||
}
|
||||
':' => {
|
||||
if let Some(':') = chars.peek() {
|
||||
while let Some(' ') = result.chars().next_back() {
|
||||
result.pop();
|
||||
}
|
||||
}
|
||||
result.push(':');
|
||||
chars.next();
|
||||
result.push(':');
|
||||
while let Some(' ') = chars.peek() {
|
||||
chars.next();
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
result.push(c);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
result
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use quote::ToTokens;
|
||||
use syn::spanned::Spanned;
|
||||
|
||||
#[test]
|
||||
fn test_fold_error_iter() {
|
||||
let res = fold_error_iter(vec![Ok(()), Ok(())].into_iter());
|
||||
assert!(res.is_ok());
|
||||
|
||||
let _span = quote::quote! { "" }.span();
|
||||
let res = fold_error_iter(vec![Ok(()), Err(syn::Error::new(_span, "err1")), Err(syn::Error::new(_span, "err2"))].into_iter());
|
||||
assert!(res.is_err());
|
||||
let err = res.unwrap_err();
|
||||
let mut check_err = syn::Error::new(_span, "err1");
|
||||
check_err.combine(syn::Error::new(_span, "err2"));
|
||||
assert_eq!(err.to_compile_error().to_string(), check_err.to_compile_error().to_string());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_two_path() {
|
||||
let _span = quote::quote! { "" }.span();
|
||||
assert_eq!(two_segment_path(Ident::new("a", _span), Ident::new("b", _span)).to_token_stream().to_string(), "a :: b");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
use crate::helpers::clean_rust_type_syntax;
|
||||
use proc_macro2::{Span, TokenStream};
|
||||
use quote::{ToTokens, quote};
|
||||
use syn::{Data, DeriveInput, Fields, Type, parse2};
|
||||
|
||||
pub fn generate_hierarchical_tree(input: TokenStream) -> syn::Result<TokenStream> {
|
||||
let input = parse2::<DeriveInput>(input)?;
|
||||
let input_type = &input.ident;
|
||||
|
||||
let line_number = input_type.span().start().line;
|
||||
|
||||
let data = match &input.data {
|
||||
Data::Enum(data) => data,
|
||||
_ => return Err(syn::Error::new(Span::call_site(), "Tried to derive HierarchicalTree for non-enum")),
|
||||
};
|
||||
|
||||
let build_message_tree: Result<Vec<_>, syn::Error> = data
|
||||
.variants
|
||||
.iter()
|
||||
.map(|variant| {
|
||||
let variant_type = &variant.ident;
|
||||
|
||||
let has_child = variant
|
||||
.attrs
|
||||
.iter()
|
||||
.any(|attr| attr.path().get_ident().is_some_and(|ident| ident == "sub_discriminant" || ident == "child"));
|
||||
|
||||
match &variant.fields {
|
||||
Fields::Unit => Ok(quote! {
|
||||
message_tree.add_variant(DebugMessageTree::new(stringify!(#variant_type)));
|
||||
}),
|
||||
Fields::Unnamed(fields) => {
|
||||
if has_child {
|
||||
let field_type = &fields.unnamed.first().unwrap().ty;
|
||||
Ok(quote! {
|
||||
{
|
||||
let mut variant_tree = DebugMessageTree::new(stringify!(#variant_type));
|
||||
let field_name = stringify!(#field_type);
|
||||
const MESSAGE_SUFFIX: &str = "Message";
|
||||
if MESSAGE_SUFFIX == &field_name[field_name.len().saturating_sub(MESSAGE_SUFFIX.len())..] {
|
||||
// The field is a Message type, recursively build its tree
|
||||
let sub_tree = #field_type::build_message_tree();
|
||||
variant_tree.add_variant(sub_tree);
|
||||
} else {
|
||||
variant_tree.add_fields(vec![format!("{field_name}")]);
|
||||
}
|
||||
message_tree.add_variant(variant_tree);
|
||||
}
|
||||
})
|
||||
} else {
|
||||
let error_msg = match fields.unnamed.len() {
|
||||
0 => format!("Remove the unnecessary `()` from the `{variant_type}` message enum variant."),
|
||||
1 => {
|
||||
let field_type = &fields.unnamed.first().unwrap().ty;
|
||||
format!(
|
||||
"The `{variant_type}` message should be defined as a struct-style (not tuple-style) enum variant to maintain consistent formatting across all editor messages.\n\
|
||||
Replace `{}` with a named field using {{curly braces}} instead of a positional field using (parentheses).",
|
||||
field_type.to_token_stream()
|
||||
)
|
||||
}
|
||||
_ => {
|
||||
let field_types = fields.unnamed.iter().map(|f| f.ty.to_token_stream().to_string()).collect::<Vec<_>>().join(", ");
|
||||
format!(
|
||||
"The `{variant_type}` message should be defined as a struct-style (not tuple-style) enum variant to maintain consistent formatting across all editor messages.\n\
|
||||
Replace `{field_types}` with named fields using {{curly braces}} instead of positional fields using (parentheses)."
|
||||
)
|
||||
}
|
||||
};
|
||||
Err(syn::Error::new(Span::call_site(), error_msg))
|
||||
}
|
||||
}
|
||||
Fields::Named(fields) => {
|
||||
let names = fields.named.iter().map(|f| f.ident.as_ref().unwrap());
|
||||
let ty = fields.named.iter().map(|f| clean_rust_type_syntax(f.ty.to_token_stream().to_string()));
|
||||
Ok(quote! {
|
||||
{
|
||||
let mut field_names = Vec::new();
|
||||
#(field_names.push(format!("{}: {}",stringify!(#names), #ty));)*
|
||||
let mut variant_tree = DebugMessageTree::new(stringify!(#variant_type));
|
||||
variant_tree.add_fields(field_names);
|
||||
message_tree.add_variant(variant_tree);
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
let build_message_tree = build_message_tree?;
|
||||
|
||||
let res = quote! {
|
||||
impl HierarchicalTree for #input_type {
|
||||
fn build_message_tree() -> DebugMessageTree {
|
||||
let mut message_tree = DebugMessageTree::new(stringify!(#input_type));
|
||||
#(#build_message_tree)*
|
||||
|
||||
let message_handler_str = #input_type::message_handler_str();
|
||||
message_tree.add_message_handler_field(message_handler_str);
|
||||
|
||||
let message_handler_data_str = #input_type::message_handler_data_str();
|
||||
if message_handler_data_str.fields().len() > 0 {
|
||||
message_tree.add_message_handler_data_field(message_handler_data_str);
|
||||
}
|
||||
|
||||
message_tree.set_path(file!());
|
||||
|
||||
message_tree.set_line_number(#line_number);
|
||||
|
||||
message_tree
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
Ok(res)
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
use crate::helper_structs::AttrInnerKeyStringMap;
|
||||
use crate::helpers::{fold_error_iter, two_segment_path};
|
||||
use proc_macro2::{Span, TokenStream as TokenStream2};
|
||||
use syn::{Attribute, Data, DeriveInput, LitStr, Variant};
|
||||
|
||||
fn parse_hint_helper_attrs(attrs: &[Attribute]) -> syn::Result<(Vec<LitStr>, Vec<LitStr>)> {
|
||||
fold_error_iter(
|
||||
attrs
|
||||
.iter()
|
||||
.filter(|a| a.path().get_ident().is_some_and(|i| i == "hint"))
|
||||
.map(|attr| attr.parse_args::<AttrInnerKeyStringMap>()),
|
||||
)
|
||||
.and_then(|v: Vec<AttrInnerKeyStringMap>| {
|
||||
fold_error_iter(AttrInnerKeyStringMap::multi_into_iter(v).map(|(k, mut v)| match v.len() {
|
||||
0 => panic!("internal error: a key without values was somehow inserted into the hashmap"),
|
||||
1 => {
|
||||
let single_val = v.pop().unwrap();
|
||||
Ok((LitStr::new(&k.to_string(), Span::call_site()), single_val))
|
||||
}
|
||||
_ => {
|
||||
// the first value is ok, the other ones should error
|
||||
let after_first = v.into_iter().skip(1);
|
||||
// this call to fold_error_iter will always return Err with a combined error
|
||||
fold_error_iter(after_first.map(|lit| Err(syn::Error::new(lit.span(), format!("value for key {k} was already given"))))).map(|_: Vec<()>| unreachable!())
|
||||
}
|
||||
}))
|
||||
})
|
||||
.map(|v| v.into_iter().unzip())
|
||||
}
|
||||
|
||||
pub fn derive_hint_impl(input_item: TokenStream2) -> syn::Result<TokenStream2> {
|
||||
let input = syn::parse2::<DeriveInput>(input_item)?;
|
||||
|
||||
let ident = input.ident;
|
||||
|
||||
match input.data {
|
||||
Data::Enum(data) => {
|
||||
let variants = data.variants.iter().map(|var: &Variant| two_segment_path(ident.clone(), var.ident.clone())).collect::<Vec<_>>();
|
||||
|
||||
let hint_result = fold_error_iter(data.variants.into_iter().map(|var: Variant| parse_hint_helper_attrs(&var.attrs)));
|
||||
|
||||
hint_result.map(|hints: Vec<(Vec<LitStr>, Vec<LitStr>)>| {
|
||||
let (keys, values): (Vec<Vec<LitStr>>, Vec<Vec<LitStr>>) = hints.into_iter().unzip();
|
||||
let cap: Vec<usize> = keys.iter().map(|v| v.len()).collect();
|
||||
|
||||
quote::quote! {
|
||||
impl Hint for #ident {
|
||||
fn hints(&self) -> ::std::collections::HashMap<String, String> {
|
||||
match self {
|
||||
#(
|
||||
#variants { .. } => {
|
||||
let mut hm = ::std::collections::HashMap::with_capacity(#cap);
|
||||
#(
|
||||
hm.insert(#keys.to_string(), #values.to_string());
|
||||
)*
|
||||
hm
|
||||
}
|
||||
)*
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
Data::Struct(_) | Data::Union(_) => {
|
||||
let hint_result = parse_hint_helper_attrs(&input.attrs);
|
||||
|
||||
hint_result.map(|(keys, values)| {
|
||||
let cap = keys.len();
|
||||
|
||||
quote::quote! {
|
||||
impl Hint for #ident {
|
||||
fn hints(&self) -> ::std::collections::HashMap<String, String> {
|
||||
let mut hm = ::std::collections::HashMap::with_capacity(#cap);
|
||||
#(
|
||||
hm.insert(#keys.to_string(), #values.to_string());
|
||||
)*
|
||||
hm
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,426 @@
|
||||
#![allow(unused)]
|
||||
|
||||
mod as_message;
|
||||
mod combined_message_attrs;
|
||||
mod discriminant;
|
||||
mod editor_commands;
|
||||
mod extract_fields;
|
||||
mod helper_structs;
|
||||
mod helpers;
|
||||
mod hierarchical_tree;
|
||||
mod hint;
|
||||
mod message_handler_data_attr;
|
||||
mod transitive_child;
|
||||
mod widget_builder;
|
||||
|
||||
use crate::as_message::derive_as_message_impl;
|
||||
use crate::combined_message_attrs::combined_message_attrs_impl;
|
||||
use crate::discriminant::derive_discriminant_impl;
|
||||
use crate::editor_commands::editor_commands_impl;
|
||||
use crate::extract_fields::derive_extract_field_impl;
|
||||
use crate::helper_structs::AttrInnerSingleString;
|
||||
use crate::hierarchical_tree::generate_hierarchical_tree;
|
||||
use crate::hint::derive_hint_impl;
|
||||
use crate::message_handler_data_attr::message_handler_data_attr_impl;
|
||||
use crate::transitive_child::derive_transitive_child_impl;
|
||||
use crate::widget_builder::derive_widget_builder_impl;
|
||||
use proc_macro::TokenStream;
|
||||
|
||||
/// Derive the `ToDiscriminant` trait and create a `<Type Name>Discriminant` enum
|
||||
///
|
||||
/// This derive macro is enum-only.
|
||||
///
|
||||
/// The discriminant enum is a copy of the input enum with all fields of every variant removed.
|
||||
/// The exception to that rule is the `#[child]` attribute.
|
||||
///
|
||||
/// # Helper attributes
|
||||
/// - `#[sub_discriminant]`: only usable on variants with a single field; instead of no fields, the discriminant of the single field will be included in the discriminant,
|
||||
/// acting as a sub-discriminant.
|
||||
/// - `#[discriminant_attr(…)]`: usable on the enum itself or on any variant; applies `#[…]` in its place on the discriminant.
|
||||
///
|
||||
/// # Attributes on the Discriminant
|
||||
/// All attributes on variants and the type itself are cleared when constructing the discriminant.
|
||||
/// If the discriminant is supposed to also have an attribute, you must double it with `#[discriminant_attr(…)]`
|
||||
///
|
||||
/// # Example
|
||||
/// ```
|
||||
/// # use graphite_proc_macros::ToDiscriminant;
|
||||
/// # use editor::utility_traits::ToDiscriminant;
|
||||
/// # use std::ffi::OsString;
|
||||
///
|
||||
/// #[derive(ToDiscriminant)]
|
||||
/// #[discriminant_attr(derive(Debug, Eq, PartialEq))]
|
||||
/// pub enum EnumA {
|
||||
/// A(u8),
|
||||
/// #[sub_discriminant]
|
||||
/// B(EnumB)
|
||||
/// }
|
||||
///
|
||||
/// #[derive(ToDiscriminant)]
|
||||
/// #[discriminant_attr(derive(Debug, Eq, PartialEq))]
|
||||
/// #[discriminant_attr(repr(u8))]
|
||||
/// pub enum EnumB {
|
||||
/// Foo(u8),
|
||||
/// Bar(String),
|
||||
/// #[cfg(feature = "some-feature")]
|
||||
/// #[discriminant_attr(cfg(feature = "some-feature"))]
|
||||
/// WindowsBar(OsString)
|
||||
/// }
|
||||
///
|
||||
/// let a = EnumA::A(1);
|
||||
/// assert_eq!(a.to_discriminant(), EnumADiscriminant::A);
|
||||
/// let b = EnumA::B(EnumB::Bar("bar".to_string()));
|
||||
/// assert_eq!(b.to_discriminant(), EnumADiscriminant::B(EnumBDiscriminant::Bar));
|
||||
/// ```
|
||||
#[proc_macro_derive(ToDiscriminant, attributes(sub_discriminant, discriminant_attr))]
|
||||
pub fn derive_discriminant(input_item: TokenStream) -> TokenStream {
|
||||
TokenStream::from(derive_discriminant_impl(input_item.into()).unwrap_or_else(|err| err.to_compile_error()))
|
||||
}
|
||||
|
||||
/// Derive the `TransitiveChild` trait and generate `From` impls to convert into the parent, as well as the top parent type
|
||||
///
|
||||
/// This macro cannot be invoked on the top parent (which has no parent but itself). Instead, implement `TransitiveChild` manually
|
||||
/// like in the example.
|
||||
///
|
||||
/// # Helper Attributes
|
||||
/// - `#[parent(<Type>, <Expr>)]` (**required**): declare the parent type (`<Type>`)
|
||||
/// and a function (`<Expr>`, has to evaluate to a single arg function) for converting a value of this type to the parent type
|
||||
/// - `#[parent_is_top]`: Denote that the parent type has no further parent type (this is required because otherwise the `From` impls for parent and top parent would overlap)
|
||||
///
|
||||
/// # Example
|
||||
/// ```
|
||||
/// # use graphite_proc_macros::TransitiveChild;
|
||||
/// # use editor::utility_traits::TransitiveChild;
|
||||
///
|
||||
/// #[derive(Debug, Eq, PartialEq)]
|
||||
/// struct A { u: u8, b: B };
|
||||
///
|
||||
/// impl A {
|
||||
/// pub fn from_b(b: B) -> Self {
|
||||
/// Self { u: 7, b }
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// impl TransitiveChild for A {
|
||||
/// type Parent = Self;
|
||||
/// type TopParent = Self;
|
||||
/// }
|
||||
///
|
||||
/// #[derive(TransitiveChild, Debug, Eq, PartialEq)]
|
||||
/// #[parent(A, A::from_b)]
|
||||
/// #[parent_is_top]
|
||||
/// enum B {
|
||||
/// Foo,
|
||||
/// Bar,
|
||||
/// Child(C)
|
||||
/// }
|
||||
///
|
||||
/// #[derive(TransitiveChild, Debug, Eq, PartialEq)]
|
||||
/// #[parent(B, B::Child)]
|
||||
/// struct C(D);
|
||||
///
|
||||
/// #[derive(TransitiveChild, Debug, Eq, PartialEq)]
|
||||
/// #[parent(C, C)]
|
||||
/// struct D;
|
||||
///
|
||||
/// let d = D;
|
||||
/// assert_eq!(A::from(d), A { u: 7, b: B::Child(C(D)) });
|
||||
/// ```
|
||||
#[proc_macro_derive(TransitiveChild, attributes(parent, parent_is_top))]
|
||||
pub fn derive_transitive_child(input_item: TokenStream) -> TokenStream {
|
||||
TokenStream::from(derive_transitive_child_impl(input_item.into()).unwrap_or_else(|err| err.to_compile_error()))
|
||||
}
|
||||
|
||||
/// Derive the `AsMessage` trait
|
||||
///
|
||||
/// # Helper Attributes
|
||||
/// - `#[child]`: only on tuple variants with a single field; Denote that the message path should continue inside the variant
|
||||
///
|
||||
/// # Example
|
||||
/// See also [`TransitiveChild`]
|
||||
/// ```
|
||||
/// # use graphite_proc_macros::{TransitiveChild, AsMessage};
|
||||
/// # use editor::utility_traits::TransitiveChild;
|
||||
/// # use editor::messages::prelude::*;
|
||||
///
|
||||
/// #[derive(AsMessage)]
|
||||
/// pub enum TopMessage {
|
||||
/// A(u8),
|
||||
/// B(u16),
|
||||
/// #[child]
|
||||
/// C(MessageC),
|
||||
/// #[child]
|
||||
/// D(MessageD)
|
||||
/// }
|
||||
///
|
||||
/// impl TransitiveChild for TopMessage {
|
||||
/// type Parent = Self;
|
||||
/// type TopParent = Self;
|
||||
/// }
|
||||
///
|
||||
/// #[derive(TransitiveChild, AsMessage, Copy, Clone)]
|
||||
/// #[parent(TopMessage, TopMessage::C)]
|
||||
/// #[parent_is_top]
|
||||
/// pub enum MessageC {
|
||||
/// X1,
|
||||
/// X2
|
||||
/// }
|
||||
///
|
||||
/// #[derive(TransitiveChild, AsMessage, Copy, Clone)]
|
||||
/// #[parent(TopMessage, TopMessage::D)]
|
||||
/// #[parent_is_top]
|
||||
/// pub enum MessageD {
|
||||
/// Y1,
|
||||
/// #[child]
|
||||
/// Y2(MessageE)
|
||||
/// }
|
||||
///
|
||||
/// #[derive(TransitiveChild, AsMessage, Copy, Clone)]
|
||||
/// #[parent(MessageD, MessageD::Y2)]
|
||||
/// pub enum MessageE {
|
||||
/// Alpha,
|
||||
/// Beta
|
||||
/// }
|
||||
///
|
||||
/// let c = MessageC::X1;
|
||||
/// assert_eq!(c.local_name(), "X1");
|
||||
/// assert_eq!(c.global_name(), "C.X1");
|
||||
/// let d = MessageD::Y2(MessageE::Alpha);
|
||||
/// assert_eq!(d.local_name(), "Y2.Alpha");
|
||||
/// assert_eq!(d.global_name(), "D.Y2.Alpha");
|
||||
/// let e = MessageE::Beta;
|
||||
/// assert_eq!(e.local_name(), "Beta");
|
||||
/// assert_eq!(e.global_name(), "D.Y2.Beta");
|
||||
/// ```
|
||||
#[proc_macro_derive(AsMessage, attributes(child))]
|
||||
pub fn derive_message(input_item: TokenStream) -> TokenStream {
|
||||
TokenStream::from(derive_as_message_impl(input_item.into()).unwrap_or_else(|err| err.to_compile_error()))
|
||||
}
|
||||
|
||||
/// This macro is basically an abbreviation for the usual [ToDiscriminant], [TransitiveChild] and [AsMessage] invocations.
|
||||
///
|
||||
/// This macro is enum-only.
|
||||
///
|
||||
/// Also note that all three of those derives have to be in scope.
|
||||
///
|
||||
/// # Usage
|
||||
/// There are three possible argument syntaxes you can use:
|
||||
/// 1. no arguments: this is for the top-level message enum. It derives `ToDiscriminant`, `AsMessage` on the discriminant, and implements `TransitiveChild` on both
|
||||
/// (the parent and top parent being the respective types themselves).
|
||||
/// It also derives the following `std` traits on the discriminant: `Debug, Copy, Clone, PartialEq, Eq, Hash`.
|
||||
/// 2. two arguments: this is for message enums whose direct parent is the top level message enum. The syntax is `#[impl_message(<Type>, <Ident>)]`,
|
||||
/// where `<Type>` is the parent message type and `<Ident>` is the identifier of the variant used to construct this child.
|
||||
/// It derives `ToDiscriminant`, `AsMessage` on the discriminant, and `TransitiveChild` on both (adding `#[parent_is_top]` to both).
|
||||
/// It also derives the following `std` traits on the discriminant: `Debug, Copy, Clone, PartialEq, Eq, Hash`.
|
||||
/// 3. three arguments: this is for all other message enums that are transitive children of the top level message enum. The syntax is
|
||||
/// `#[impl_message(<Type>, <Type>, <Ident>)]`, where the first `<Type>` is the top parent message type, the second `<Type>` is the parent message type
|
||||
/// and `<Ident>` is the identifier of the variant used to construct this child.
|
||||
/// It derives `ToDiscriminant`, `AsMessage` on the discriminant, and `TransitiveChild` on both.
|
||||
/// It also derives the following `std` traits on the discriminant: `Debug, Copy, Clone, PartialEq, Eq, Hash`.
|
||||
/// **This third option will likely change in the future**
|
||||
#[proc_macro_attribute]
|
||||
pub fn impl_message(attr: TokenStream, input_item: TokenStream) -> TokenStream {
|
||||
TokenStream::from(combined_message_attrs_impl(attr.into(), input_item.into()).unwrap_or_else(|err| err.to_compile_error()))
|
||||
}
|
||||
|
||||
/// Derive the `Hint` trait
|
||||
///
|
||||
/// # Example
|
||||
/// ```
|
||||
/// # use graphite_proc_macros::Hint;
|
||||
/// # use editor::utility_traits::Hint;
|
||||
///
|
||||
/// #[derive(Hint)]
|
||||
/// pub enum StateMachine {
|
||||
/// #[hint(rmb = "foo", lmb = "bar")]
|
||||
/// Ready,
|
||||
/// #[hint(alt = "baz")]
|
||||
/// RMBDown,
|
||||
/// // no hint (also ok)
|
||||
/// LMBDown
|
||||
/// }
|
||||
/// ```
|
||||
#[proc_macro_derive(Hint, attributes(hint))]
|
||||
pub fn derive_hint(input_item: TokenStream) -> TokenStream {
|
||||
TokenStream::from(derive_hint_impl(input_item.into()).unwrap_or_else(|err| err.to_compile_error()))
|
||||
}
|
||||
|
||||
/// The `edge` proc macro does nothing, it is intended for use with an external tool
|
||||
///
|
||||
/// # Example
|
||||
/// ```ignore
|
||||
/// match (example_tool_state, event) {
|
||||
/// (ToolState::Ready, Event::PointerDown(mouse_state)) if *mouse_state == MouseState::Left => {
|
||||
/// #[edge("LMB Down")]
|
||||
/// ToolState::Pending
|
||||
/// }
|
||||
/// (SelectToolState::Pending, Event::PointerUp(mouse_state)) if *mouse_state == MouseState::Left => {
|
||||
/// #[edge("LMB Up: Select Object")]
|
||||
/// SelectToolState::Ready
|
||||
/// }
|
||||
/// (SelectToolState::Pending, Event::PointerMove(x,y)) => {
|
||||
/// #[edge("Mouse Move")]
|
||||
/// SelectToolState::TransformSelected
|
||||
/// }
|
||||
/// (SelectToolState::TransformSelected, Event::PointerMove(x,y)) => {
|
||||
/// #[edge("Mouse Move")]
|
||||
/// SelectToolState::TransformSelected
|
||||
/// }
|
||||
/// (SelectToolState::TransformSelected, Event::PointerUp(mouse_state)) if *mouse_state == MouseState::Left => {
|
||||
/// #[edge("LMB Up")]
|
||||
/// SelectToolState::Ready
|
||||
/// }
|
||||
/// (state, _) => {
|
||||
/// // Do nothing
|
||||
/// state
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
#[proc_macro_attribute]
|
||||
pub fn edge(attr: TokenStream, item: TokenStream) -> TokenStream {
|
||||
// to make sure that only `#[edge("string")]` is allowed
|
||||
let _verify = syn::parse_macro_input!(attr as AttrInnerSingleString);
|
||||
|
||||
item
|
||||
}
|
||||
|
||||
#[proc_macro_derive(WidgetBuilder, attributes(widget_builder))]
|
||||
pub fn derive_widget_builder(input_item: TokenStream) -> TokenStream {
|
||||
TokenStream::from(derive_widget_builder_impl(input_item.into()).unwrap_or_else(|err| err.to_compile_error()))
|
||||
}
|
||||
|
||||
#[proc_macro_derive(HierarchicalTree)]
|
||||
pub fn derive_hierarchical_tree(input_item: TokenStream) -> TokenStream {
|
||||
TokenStream::from(generate_hierarchical_tree(input_item.into()).unwrap_or_else(|err| err.to_compile_error()))
|
||||
}
|
||||
|
||||
#[proc_macro_derive(ExtractField)]
|
||||
pub fn derive_extract_field(input_item: TokenStream) -> TokenStream {
|
||||
TokenStream::from(derive_extract_field_impl(input_item.into()).unwrap_or_else(|err| err.to_compile_error()))
|
||||
}
|
||||
|
||||
#[proc_macro_attribute]
|
||||
pub fn message_handler_data(attr: TokenStream, input_item: TokenStream) -> TokenStream {
|
||||
TokenStream::from(message_handler_data_attr_impl(attr.into(), input_item.into()).unwrap_or_else(|err| err.to_compile_error()))
|
||||
}
|
||||
|
||||
#[proc_macro_attribute]
|
||||
pub fn editor_commands(attr: TokenStream, input_item: TokenStream) -> TokenStream {
|
||||
let module = syn::parse_macro_input!(input_item as syn::ItemMod);
|
||||
TokenStream::from(editor_commands_impl(attr.into(), module).unwrap_or_else(|err| err.to_compile_error()))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use proc_macro2::TokenStream as TokenStream2;
|
||||
|
||||
fn ts_assert_eq(l: TokenStream2, r: TokenStream2) {
|
||||
// not sure if this is the best way of doing things but if two TokenStreams are equal, their `to_string` is also equal
|
||||
// so there are at least no false negatives
|
||||
assert_eq!(l.to_string(), r.to_string());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_derive_hint() {
|
||||
let res = derive_hint_impl(quote::quote! {
|
||||
#[hint(key1="val1",key2="val2",)]
|
||||
struct S { a: u8, b: String, c: bool }
|
||||
});
|
||||
assert!(res.is_ok());
|
||||
ts_assert_eq(
|
||||
res.unwrap(),
|
||||
quote::quote! {
|
||||
impl Hint for S {
|
||||
fn hints(&self) -> ::std::collections::HashMap<String, String> {
|
||||
let mut hm = ::std::collections::HashMap::with_capacity(2usize);
|
||||
hm.insert("key1".to_string(), "val1".to_string());
|
||||
hm.insert("key2".to_string(), "val2".to_string());
|
||||
hm
|
||||
}
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
let res = derive_hint_impl(quote::quote! {
|
||||
enum E {
|
||||
#[hint(key1="val1",key2="val2",)]
|
||||
S { a: u8, b: String, c: bool },
|
||||
#[hint(key3="val3")]
|
||||
X,
|
||||
Y
|
||||
}
|
||||
});
|
||||
assert!(res.is_ok());
|
||||
ts_assert_eq(
|
||||
res.unwrap(),
|
||||
quote::quote! {
|
||||
impl Hint for E {
|
||||
fn hints(&self) -> ::std::collections::HashMap<String, String> {
|
||||
match self {
|
||||
E::S { .. } => {
|
||||
let mut hm = ::std::collections::HashMap::with_capacity(2usize);
|
||||
hm.insert("key1".to_string(), "val1".to_string());
|
||||
hm.insert("key2".to_string(), "val2".to_string());
|
||||
hm
|
||||
}
|
||||
E::X { .. } => {
|
||||
let mut hm = ::std::collections::HashMap::with_capacity(1usize);
|
||||
hm.insert("key3".to_string(), "val3".to_string());
|
||||
hm
|
||||
}
|
||||
E::Y { .. } => {
|
||||
let mut hm = ::std::collections::HashMap::with_capacity(0usize);
|
||||
hm
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
let res = derive_hint_impl(quote::quote! {
|
||||
union NoHint {}
|
||||
});
|
||||
assert!(res.is_ok());
|
||||
ts_assert_eq(
|
||||
res.unwrap(),
|
||||
quote::quote! {
|
||||
impl Hint for NoHint {
|
||||
fn hints(&self) -> ::std::collections::HashMap<String, String> {
|
||||
let mut hm = ::std::collections::HashMap::with_capacity(0usize);
|
||||
hm
|
||||
}
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
let res = derive_hint_impl(quote::quote! {
|
||||
#[hint(a="1", a="2")]
|
||||
struct S;
|
||||
});
|
||||
assert!(res.is_err());
|
||||
|
||||
let res = derive_hint_impl(quote::quote! {
|
||||
#[hint(a="1")]
|
||||
#[hint(b="2")]
|
||||
struct S;
|
||||
});
|
||||
assert!(res.is_ok());
|
||||
ts_assert_eq(
|
||||
res.unwrap(),
|
||||
quote::quote! {
|
||||
impl Hint for S {
|
||||
fn hints(&self) -> ::std::collections::HashMap<String, String> {
|
||||
let mut hm = ::std::collections::HashMap::with_capacity(2usize);
|
||||
hm.insert("a".to_string(), "1".to_string());
|
||||
hm.insert("b".to_string(), "2".to_string());
|
||||
hm
|
||||
}
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
// note: edge needs no testing since AttrInnerSingleString has testing and that's all you'd need to test with edge
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
use crate::helpers::{call_site_ident, clean_rust_type_syntax};
|
||||
use proc_macro2::{Span, TokenStream};
|
||||
use quote::{ToTokens, quote};
|
||||
use syn::{ItemImpl, Type, parse2, spanned::Spanned};
|
||||
|
||||
pub fn message_handler_data_attr_impl(attr: TokenStream, input_item: TokenStream) -> syn::Result<TokenStream> {
|
||||
// Parse the input as an impl block
|
||||
let impl_block = parse2::<ItemImpl>(input_item.clone())?;
|
||||
|
||||
let self_ty = &impl_block.self_ty;
|
||||
|
||||
let path = match &**self_ty {
|
||||
Type::Path(path) => &path.path,
|
||||
_ => return Err(syn::Error::new(Span::call_site(), "Expected impl implementation")),
|
||||
};
|
||||
|
||||
let input_type = path.segments.last().map(|s| &s.ident).unwrap();
|
||||
|
||||
let handler_line_number = input_type.span().start().line;
|
||||
|
||||
// Extract the message type from the trait path
|
||||
let trait_path = match &impl_block.trait_ {
|
||||
Some((_, path, _)) => path,
|
||||
None => return Err(syn::Error::new(Span::call_site(), "Expected trait implementation")),
|
||||
};
|
||||
|
||||
// Get the trait generics (should be MessageHandler<M, C>)
|
||||
if let Some(segment) = trait_path.segments.last() {
|
||||
if segment.ident != "MessageHandler" {
|
||||
return Err(syn::Error::new(segment.ident.span(), "Expected MessageHandler trait"));
|
||||
}
|
||||
if let syn::PathArguments::AngleBracketed(args) = &segment.arguments {
|
||||
if args.args.len() >= 2 {
|
||||
// Extract the message type (M) and context struct type (C) from the trait params
|
||||
let message_type = &args.args[0];
|
||||
let data_type = &args.args[1];
|
||||
|
||||
let impl_item = match data_type {
|
||||
syn::GenericArgument::Type(t) => {
|
||||
match t {
|
||||
syn::Type::Path(type_path) if !type_path.path.segments.is_empty() => {
|
||||
// Get just the base identifier (ToolMessageData) without generics
|
||||
let type_name = &type_path.path.segments.first().unwrap().ident;
|
||||
|
||||
let handler_data_line_number = type_name.span().start().line;
|
||||
|
||||
quote! {
|
||||
#input_item
|
||||
impl #message_type {
|
||||
pub fn message_handler_data_str() -> MessageData {
|
||||
MessageData::new(format!("{}", stringify!(#type_name)), #type_name::field_types(), #type_name::path(), #type_name::line_number())
|
||||
}
|
||||
pub fn message_handler_str() -> MessageData {
|
||||
MessageData::new(format!("{}", stringify!(#input_type)), #input_type::field_types(), #input_type::path(), #input_type::line_number())
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
syn::Type::Tuple(_) => quote! {
|
||||
#input_item
|
||||
impl #message_type {
|
||||
pub fn message_handler_str() -> MessageData {
|
||||
MessageData::new(format!("{}", stringify!(#input_type)), #input_type::field_types(), #input_type::path(), #input_type::line_number())
|
||||
}
|
||||
}
|
||||
},
|
||||
syn::Type::Reference(type_reference) => {
|
||||
let message_type = call_site_ident(format!("{input_type}Message"));
|
||||
let type_ident = match &*type_reference.elem {
|
||||
syn::Type::Path(type_path) => &type_path.path.segments.first().unwrap().ident,
|
||||
_ => return Err(syn::Error::new(type_reference.elem.span(), "Expected type path")),
|
||||
};
|
||||
|
||||
let type_line_number = type_ident.span().start().line;
|
||||
|
||||
let tr = clean_rust_type_syntax(type_reference.to_token_stream().to_string());
|
||||
quote! {
|
||||
#input_item
|
||||
impl #message_type {
|
||||
pub fn message_handler_data_str() -> MessageData {
|
||||
MessageData::new(format!("{}", #tr), #type_ident::field_types(), #type_ident::path(), #type_ident::line_number())
|
||||
}
|
||||
|
||||
pub fn message_handler_str() -> MessageData {
|
||||
MessageData::new(format!("{}", stringify!(#input_type)), #input_type::field_types(), #input_type::path(), #input_type::line_number())
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => return Err(syn::Error::new(t.span(), "Unsupported type format")),
|
||||
}
|
||||
}
|
||||
|
||||
_ => quote! {
|
||||
#input_item
|
||||
},
|
||||
};
|
||||
return Ok(impl_item);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(input_item)
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
use crate::helper_structs::Pair;
|
||||
use proc_macro2::{Span, TokenStream};
|
||||
use syn::{DeriveInput, Expr, Type};
|
||||
|
||||
pub fn derive_transitive_child_impl(input_item: TokenStream) -> syn::Result<TokenStream> {
|
||||
let input = syn::parse2::<DeriveInput>(input_item).unwrap();
|
||||
|
||||
let attribute = input
|
||||
.attrs
|
||||
.iter()
|
||||
.find(|a| a.path().is_ident("parent"))
|
||||
.ok_or_else(|| syn::Error::new(Span::call_site(), format!("tried to derive TransitiveChild without a #[parent] attribute (on {})", input.ident)))?;
|
||||
|
||||
let parent_is_top = input.attrs.iter().any(|a| a.path().is_ident("parent_is_top"));
|
||||
|
||||
let Pair {
|
||||
first: parent_type,
|
||||
second: to_parent,
|
||||
..
|
||||
} = attribute.parse_args::<Pair<Type, Expr>>()?;
|
||||
|
||||
let top_parent_type: Type = syn::parse_quote! { <#parent_type as TransitiveChild>::TopParent };
|
||||
|
||||
let input_type = &input.ident;
|
||||
|
||||
let trait_impl = quote::quote! {
|
||||
impl TransitiveChild for #input_type {
|
||||
type Parent = #parent_type;
|
||||
type TopParent = #top_parent_type;
|
||||
}
|
||||
};
|
||||
|
||||
let from_for_parent = quote::quote! {
|
||||
impl From<#input_type> for #parent_type {
|
||||
fn from(x: #input_type) -> #parent_type {
|
||||
(#to_parent)(x)
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
let from_for_top = quote::quote! {
|
||||
impl From<#input_type> for #top_parent_type {
|
||||
fn from(x: #input_type) -> #top_parent_type {
|
||||
#top_parent_type::from((#to_parent)(x))
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
Ok(if parent_is_top {
|
||||
quote::quote! { #trait_impl #from_for_parent }
|
||||
} else {
|
||||
quote::quote! { #trait_impl #from_for_parent #from_for_top }
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,177 @@
|
||||
use proc_macro2::{Ident, Literal, TokenStream as TokenStream2};
|
||||
use quote::ToTokens;
|
||||
use syn::spanned::Spanned;
|
||||
use syn::{Attribute, Data, DeriveInput, Field, PathArguments, Type};
|
||||
|
||||
/// Check if a specified `#[widget_builder target]` attribute can be found in the list
|
||||
fn has_attribute(attrs: &[Attribute], target: &str) -> bool {
|
||||
attrs
|
||||
.iter()
|
||||
.filter(|attr| attr.path().to_token_stream().to_string() == "widget_builder")
|
||||
.any(|attr| attr.meta.require_list().is_ok_and(|list| list.tokens.to_string() == target))
|
||||
}
|
||||
|
||||
/// Make setting strings easier by allowing all types that `impl Into<String>`
|
||||
///
|
||||
/// Returns the new input type and a conversion to the original.
|
||||
fn easier_string_assignment(field: &Field, field_ty: &Type, field_ident: &Ident) -> (TokenStream2, TokenStream2) {
|
||||
let has_string_attr = has_attribute(&field.attrs, "string");
|
||||
|
||||
if let Type::Path(type_path) = field_ty
|
||||
&& let Some(last_segment) = type_path.path.segments.last()
|
||||
{
|
||||
// Check for `Option<String>` or `Option<StringAlias>` with `#[widget_builder(string)]`
|
||||
if last_segment.ident == Ident::new("Option", last_segment.ident.span())
|
||||
&& let PathArguments::AngleBracketed(generic_args) = &last_segment.arguments
|
||||
{
|
||||
let inner_is_string = generic_args.args.first().is_some_and(|arg| {
|
||||
matches!(arg, syn::GenericArgument::Type(Type::Path(inner_path))
|
||||
if inner_path.path.segments.last().is_some_and(|seg| seg.ident == Ident::new("String", seg.ident.span())))
|
||||
});
|
||||
if inner_is_string || has_string_attr {
|
||||
return (
|
||||
quote::quote_spanned!(field_ty.span()=> impl Into<String>),
|
||||
quote::quote_spanned!(field_ident.span()=> Some(#field_ident.into())),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Check if this type is a `String`
|
||||
// Based on https://stackoverflow.com/questions/66906261/rust-proc-macro-derive-how-do-i-check-if-a-field-is-of-a-primitive-type-like-b
|
||||
if last_segment.ident == Ident::new("String", last_segment.ident.span()) || has_string_attr {
|
||||
return (
|
||||
quote::quote_spanned!(field_ty.span()=> impl Into<String>),
|
||||
quote::quote_spanned!(field_ident.span()=> #field_ident.into()),
|
||||
);
|
||||
}
|
||||
}
|
||||
(quote::quote_spanned!(field_ty.span()=> #field_ty), quote::quote_spanned!(field_ident.span()=> #field_ident))
|
||||
}
|
||||
|
||||
/// Extract the identifier of the field (which should always be present)
|
||||
fn extract_ident(field: &Field) -> syn::Result<&Ident> {
|
||||
field
|
||||
.ident
|
||||
.as_ref()
|
||||
.ok_or_else(|| syn::Error::new_spanned(field, "Constructing a builder not supported for unnamed fields"))
|
||||
}
|
||||
|
||||
/// Find the type passed into the builder and the right hand side of the assignment.
|
||||
///
|
||||
/// Applies special behavior for easier String and WidgetCallback assignment.
|
||||
fn find_type_and_assignment(field: &Field) -> syn::Result<(TokenStream2, TokenStream2)> {
|
||||
let field_ty = &field.ty;
|
||||
let field_ident = extract_ident(field)?;
|
||||
|
||||
let (mut function_input_ty, mut assignment) = easier_string_assignment(field, field_ty, field_ident);
|
||||
|
||||
// Check if type is `WidgetCallback`
|
||||
if let Type::Path(type_path) = field_ty
|
||||
&& let Some(last_segment) = type_path.path.segments.last()
|
||||
&& let PathArguments::AngleBracketed(generic_args) = &last_segment.arguments
|
||||
&& let Some(first_generic) = generic_args.args.first()
|
||||
&& last_segment.ident == Ident::new("WidgetCallback", last_segment.ident.span())
|
||||
{
|
||||
// Assign builder pattern to assign the closure directly
|
||||
function_input_ty = quote::quote_spanned!(field_ty.span()=> impl Fn(&#first_generic) -> crate::messages::message::Message + 'static + Send + Sync);
|
||||
assignment = quote::quote_spanned!(field_ident.span()=> crate::messages::layout::utility_types::layout_widget::WidgetCallback::new(#field_ident));
|
||||
}
|
||||
Ok((function_input_ty, assignment))
|
||||
}
|
||||
|
||||
// Construct a builder function for a specific field in the struct
|
||||
fn construct_builder(field: &Field) -> syn::Result<TokenStream2> {
|
||||
// Check if this field should be skipped with `#[widget_builder(skip)]`
|
||||
if has_attribute(&field.attrs, "skip") {
|
||||
return Ok(Default::default());
|
||||
}
|
||||
let field_ident = extract_ident(field)?;
|
||||
|
||||
// Create a doc comment literal describing the behaviour of the function
|
||||
let doc_comment = Literal::string(&format!("Set the `{field_ident}` field using a builder pattern."));
|
||||
|
||||
let (function_input_ty, assignment) = find_type_and_assignment(field)?;
|
||||
|
||||
// Create builder function
|
||||
Ok(quote::quote_spanned!(field.span()=>
|
||||
#[doc = #doc_comment]
|
||||
pub fn #field_ident(mut self, #field_ident: #function_input_ty) -> Self{
|
||||
self.#field_ident = #assignment;
|
||||
self
|
||||
}
|
||||
))
|
||||
}
|
||||
|
||||
pub fn derive_widget_builder_impl(input_item: TokenStream2) -> syn::Result<TokenStream2> {
|
||||
let input = syn::parse2::<DeriveInput>(input_item)?;
|
||||
|
||||
let struct_name_ident = input.ident;
|
||||
|
||||
// Extract the struct fields
|
||||
let fields = match &input.data {
|
||||
Data::Enum(enum_data) => return Err(syn::Error::new_spanned(enum_data.enum_token, "Derive widget builder is not supported for enums")),
|
||||
Data::Union(union_data) => return Err(syn::Error::new_spanned(union_data.union_token, "Derive widget builder is not supported for unions")),
|
||||
Data::Struct(struct_data) => &struct_data.fields,
|
||||
};
|
||||
|
||||
// Create functions based on each field
|
||||
let builder_functions = fields.iter().map(construct_builder).collect::<Result<Vec<_>, _>>()?;
|
||||
|
||||
// Check if this should not have the `widget_instance()` function due to a `#[widget_builder(not_widget_instance)]` attribute
|
||||
let widget_instance_fn = if !has_attribute(&input.attrs, "not_widget_instance") {
|
||||
// A doc comment for the widget_instance function
|
||||
let widget_instance_doc_comment = Literal::string(&format!("Wrap {struct_name_ident} as a WidgetInstance."));
|
||||
|
||||
// Construct the `widget_instance` function
|
||||
quote::quote! {
|
||||
#[doc = #widget_instance_doc_comment]
|
||||
pub fn widget_instance(self) -> crate::messages::layout::utility_types::layout_widget::WidgetInstance {
|
||||
crate::messages::layout::utility_types::layout_widget::WidgetInstance::new( crate::messages::layout::utility_types::layout_widget::Widget::#struct_name_ident(self))
|
||||
}
|
||||
}
|
||||
} else {
|
||||
quote::quote!()
|
||||
};
|
||||
|
||||
// The new function takes any fields tagged with `#[widget_builder(constructor)]` as arguments.
|
||||
let new_fn = {
|
||||
// A doc comment for the new function
|
||||
let new_doc_comment = Literal::string(&format!("Create a new {struct_name_ident}, based on default values."));
|
||||
|
||||
let is_constructor = |field: &Field| has_attribute(&field.attrs, "constructor");
|
||||
|
||||
let idents = fields.iter().filter(|field| is_constructor(field)).map(extract_ident).collect::<Result<Vec<_>, _>>()?;
|
||||
let types_and_assignments = fields.iter().filter(|field| is_constructor(field)).map(find_type_and_assignment).collect::<Result<Vec<_>, _>>()?;
|
||||
let (types, assignments): (Vec<_>, Vec<_>) = types_and_assignments.into_iter().unzip();
|
||||
|
||||
let construction = if idents.is_empty() {
|
||||
quote::quote!(Default::default())
|
||||
} else {
|
||||
let default = (idents.len() != fields.len()).then_some(quote::quote!(..Default::default())).unwrap_or_default();
|
||||
quote::quote! {
|
||||
Self {
|
||||
#(#idents: #assignments,)*
|
||||
#default
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
quote::quote! {
|
||||
#[doc = #new_doc_comment]
|
||||
pub fn new(#(#idents: #types),*) -> Self {
|
||||
#construction
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// Construct the code block
|
||||
Ok(quote::quote! {
|
||||
impl #struct_name_ident {
|
||||
#new_fn
|
||||
|
||||
#(#builder_functions)*
|
||||
|
||||
#widget_instance_fn
|
||||
}
|
||||
})
|
||||
}
|
||||
Reference in New Issue
Block a user