typeshaper
typeshaper lets you derive new struct types from existing ones in a single expression — omit fields, pick fields, merge two structs, make all fields optional, or restore them as required. Every generated type automatically receives conversion impls and can feed into further expressions.
Have you ever written code like this?
The API layer needs it, but password_hash must not be exposed, so you duplicate:
The search endpoint only needs id and name, so you duplicate again:
// ... another From ...
The patch endpoint requires all fields to be optional, so you duplicate once more:
// ... another From ...
Add one field to User and you must update UserPublic, UserPatch, UserSummary — structs, From impls, and every test you might have missed.
And that's just User. You still have Order, Product, Article, Comment…
A different approach
[]
= "0.1"
use ;
// Remove two fields
typex!;
// Keep only two fields
typex!;
// Make all fields optional
typex!;
Conversions just work:
let user: User = /* from the database */;
let public: UserPublic = user.clone.project; // drops password_hash, created_at
let summary: UserSummary = user.clone.project; // only id and name
let patch = from; // all fields become Option
Add a field to User — the three typex!() lines stay unchanged, and the new field propagates automatically.
Going further: merge two sources into one
An order snapshot needs both user and address information:
// Merge User and Address into a new type
typex!;
let snapshot = from;
// or via .project() on a tuple:
let snapshot = .;
Keep only the fields that are in User but not in Address:
typex!; // Diff
Expressions compose
// Remove password_hash, then make remaining fields optional
typex!;
// Remove password_hash, then pick summary fields
typex!;
// Parentheses control associativity: Partial then Required (round-trip)
typex!;
Full patch round-trip
// Optional version for update endpoints
typex!;
// Restore to required after validation
typex!;
// ---
let patch = UserPatch ;
// Recover the fully-typed version if all fields are present
match try_from
Cross-crate: define models once
Define the domain model in one crate; derive views in another without copying structs:
// core-crate/src/lib.rs
// export generates a companion macro
// automatically exports: pub macro typeshaper_import_User!()
// api-crate/src/lib.rs
use ;
typeshaper_import_User!; // registers User's field metadata in this crate
// works exactly like a locally annotated type
typex!;
typex!;
Re-export with new attributes
Sometimes you need to annotate a struct you didn't write — and cannot touch.
A typical case is FFI. The napi-rs framework requires #[napi] on every struct it exposes to Node.js. Your domain model lives in core-crate; the FFI crate must not modify it — adding attributes directly to someone else's package crosses crate boundaries and won't compile.
With typeshaper, a bare source expression (T with no operator) rebuilds the struct verbatim so you can attach new attributes:
// napi-crate/src/lib.rs
use ;
typeshaper_import_User!;
// Exact same fields as User — zero manual duplication
typex!;
// Drop sensitive fields first, then expose via napi
typex!;
The User → UserNapi conversion impl is generated automatically. The domain struct stays clean; the FFI crate owns the annotation.
The same pattern applies whenever an attribute can't live in the source crate: #[repr(C)] for C FFI, #[pyclass] for PyO3, a custom #[derive] from a third-party crate, and so on.
Generic types
When a source struct has type parameters, you must declare them explicitly in typex!() — on the target name and on each generic source node. This is intentional: implicit inheritance would silently produce the wrong struct when multiple type parameters come from different sources.
Basic type parameter
// <T> is declared on both the target name and the source node
typex!;
typex!;
typex!;
let w = Wrapper ;
let no_label: = w.project;
Multiple type parameters (Merge)
When merging two generic types, the target declares all parameters; each source node uses its own:
// T comes from Person, U comes from Addr — both declared on the target
typex!;
let full = from;
Inline trait bounds and where clauses
typex!;
typex!;
Lifetime parameters
typex!;
Cross-crate generic types
Generic parameter metadata is encoded in the companion macro and fully restored on import:
// core-crate
// app-crate
typeshaper_import_GenericModel!;
typex!;
typex!;
Compile-error guard: forgetting type parameters is caught at compile time:
typex!(Bad = Wrapper - [label]); // ^^^^^^^ error: type `Wrapper` has generic parameters; // declare them explicitly, e.g. `Target<T> = Wrapper<T>`
Reference
Installation
[]
= "0.1"
Source annotation: #[typeshaper]
Add once to a source struct. Field metadata is written to the compile-time registry; the struct itself is left unchanged.
| Form | Effect |
|---|---|
#[typeshaper] |
Use within the same crate |
#[typeshaper(export)] |
Use within the same crate + generates typeshaper_import_T!() for other crates |
#[typeshaper] stacks on top of any other attributes without affecting existing behavior.
Operator reference
| Syntax | Name | Meaning | Generated impl |
|---|---|---|---|
T |
Rebuild | Copy all fields unchanged; apply new attributes | TypeshaperInto<Target> for T |
T - [f1, f2] |
Omit | Remove listed fields | TypeshaperInto<Target> for T |
T & [f1, f2] |
Pick | Keep only listed fields | TypeshaperInto<Target> for T |
A + B |
Merge | Combine all fields of A and B (no duplicates) | From<(A, B)> for Target + TypeshaperInto<Target> for (A, B) |
T? |
Partial | Wrap every field in Option<_> |
From<T> for Target |
T! |
Required | Unwrap Option<_> from a Partial type |
TryFrom<T> for Target (or From<T> when the source has no Option fields) |
A % B |
Diff | Fields present in A but absent in B (matched on both field name and type) | TypeshaperInto<Target> for A |
Composition rules
Operators are left-associative; parentheses change precedence:
// User - [age] & [id, name] means (User - [age]) & [id, name]
typex!;
// Parentheses make the right side evaluate first
typex!;
// Postfix chaining
typex!;
typex!;
typex!() syntax
typex!( [#[attr...]] [vis] TargetName[<Params>] [where ...] = Expr );
- Attributes (optional): placed before
TargetName, forwarded verbatim to the generated struct; multiple attributes can be stacked.typex!()never adds any#[derive]on its own. - Visibility (optional):
pub,pub(crate),pub(super), etc. Defaults to private when omitted — the generated struct is only accessible within the same module. Write explicitpubfor types intended to be used outside the declaring module. - TargetName: the name of the generated struct; also registered in the compile-time table so it can be used as a source in subsequent
typex!()calls. <Params>(optional): explicit generic or lifetime parameters for the target type — required when any source inExpris a generic type. Inline bounds (T: Clone + Debug) and separatewhereclauses are both accepted.- Expr: a type-algebra expression — see the table above. Each source node that refers to a generic type must carry matching type arguments:
Source<T>,Source<'a>, etc.
typex!;
Conversion methods
TypeshaperExt is blanket-implemented for all types; the target is inferred from the binding:
let public: UserPublic = user.project; // equivalent to user.typeshaper_into()
Merge uses tuple From or .project(), Partial uses From, Required uses TryFrom:
let snapshot = from;
let snapshot = .; // also works
let draft = from;
let verified = try_from?;
Cross-crate usage
Exporting crate
// core-crate/src/lib.rs
use typeshaper;
// automatically exports: pub macro typeshaper_import_User!()
Importing crate
// app-crate/src/lib.rs
use typex;
use ;
typeshaper_import_User!; // call once at module top-level
typex!;
typex!;
Multiple types each get their own companion macro; cross-crate Merge and Diff are fully supported:
use ;
typeshaper_import_User!;
typeshaper_import_Address!;
typex!;
typex!;
| Same crate | Cross-crate | |
|---|---|---|
| Source annotation | #[typeshaper] |
#[typeshaper(export)] |
| Caller prerequisite | none | typeshaper_import_T!() |
typex!() syntax |
identical | identical |
Supported operations
- Omit —
T - [fields] - Pick —
T & [fields] - Merge —
A + B - Partial —
T? - Required —
T! - Diff —
A % B - Expression composition and chaining
- Attribute forwarding
- Cross-crate export / import
- Generics, lifetimes, and trait bounds — explicit type parameters required
License
Licensed under either of Apache License, Version 2.0 or MIT license at your option.