toolkit_contract_macros/lib.rs
1#![cfg_attr(coverage_nightly, feature(coverage_attribute))]
2
3use proc_macro::TokenStream;
4use syn::parse_macro_input;
5
6/// Code generation for the `#[contract]` trait expansion.
7mod codegen;
8mod consumes;
9mod contract_error;
10mod grpc_contract;
11mod grpc_contract_parse;
12/// Code generation for `#[derive(ContractError)]`.
13mod model;
14/// Code generation for the `#[grpc_contract]` projection.
15mod parse;
16mod projection;
17mod proto_bridge;
18mod provides;
19mod query_params;
20mod rest_contract;
21mod rest_contract_parse;
22mod stream_attr;
23mod support;
24
25#[proc_macro_attribute]
26pub fn contract(attr: TokenStream, item: TokenStream) -> TokenStream {
27 let contract_attr = parse_macro_input!(attr as parse::ContractAttr);
28 let item_trait = parse_macro_input!(item as syn::ItemTrait);
29
30 match parse::parse_trait(contract_attr, &item_trait) {
31 Ok(model) => codegen::generate(&model).into(),
32 Err(err) => err.to_compile_error().into(),
33 }
34}
35
36#[proc_macro_attribute]
37pub fn rest_contract(attr: TokenStream, item: TokenStream) -> TokenStream {
38 let attr = parse_macro_input!(attr as rest_contract_parse::RestContractAttr);
39 let item = parse_macro_input!(item as syn::ItemTrait);
40
41 match rest_contract_parse::parse(attr, item) {
42 Ok(model) => rest_contract::generate(&model).into(),
43 Err(err) => err.to_compile_error().into(),
44 }
45}
46
47#[proc_macro_attribute]
48pub fn grpc_contract(attr: TokenStream, item: TokenStream) -> TokenStream {
49 let attr = parse_macro_input!(attr as grpc_contract_parse::GrpcContractAttr);
50 let item = parse_macro_input!(item as syn::ItemTrait);
51
52 match grpc_contract_parse::parse(attr, item) {
53 Ok(model) => grpc_contract::generate(&model).into(),
54 Err(err) => err.to_compile_error().into(),
55 }
56}
57
58/// `#[toolkit::provides(contract = ..., local = ..., transports = [...])]` —
59/// auto-wire a generated contract client into the host `ClientHub`.
60///
61/// Applied on a module struct in the provider crate; generates an inherent
62/// `wire_<contract_snake>` async method that validates the contract IR,
63/// reads typed wiring config, and registers the appropriate Local/REST/gRPC
64/// client. `contract = [sdk::Api(local = ...), sdk::OtherApi(...)]` provides
65/// several contracts from one attribute. See `toolkit_contract_macros::provides`
66/// for the full attribute surface.
67#[proc_macro_attribute]
68pub fn provides(attr: TokenStream, item: TokenStream) -> TokenStream {
69 let attr = parse_macro_input!(attr as provides::ProvidesAttr);
70 let item = parse_macro_input!(item as syn::ItemStruct);
71 match provides::generate(&attr, &item) {
72 Ok(tokens) => tokens.into(),
73 Err(err) => err.to_compile_error().into(),
74 }
75}
76
77/// `#[toolkit::consumes(contract = ..., from = "gear")]` — declare a contract
78/// dependency wired via eventual-readiness directory discovery.
79///
80/// Applied on the gear struct (alongside `#[toolkit::gear]`). Emits a
81/// `ConsumerRegistration` that the runtime's
82/// proxy-wiring phase replays: a compile-time local impl wins, otherwise a
83/// directory-resolving REST client is registered.
84/// `contract = [sdk::Api, sdk::OtherApi(from = "other")]` consumes several
85/// contracts from one attribute. Does NOT inject a topo-sort dependency — see
86/// `toolkit_contract_macros::consumes` docs.
87#[proc_macro_attribute]
88pub fn consumes(attr: TokenStream, item: TokenStream) -> TokenStream {
89 let attr = parse_macro_input!(attr as consumes::ConsumesAttr);
90 let item = parse_macro_input!(item as syn::ItemStruct);
91 match consumes::generate(&attr, &item) {
92 Ok(tokens) => tokens.into(),
93 Err(err) => err.to_compile_error().into(),
94 }
95}
96
97#[proc_macro_derive(ProtoBridge, attributes(proto_bridge))]
98pub fn derive_proto_bridge(input: TokenStream) -> TokenStream {
99 let input = parse_macro_input!(input as syn::DeriveInput);
100 match proto_bridge::generate(&input) {
101 Ok(tokens) => tokens.into(),
102 Err(err) => err.to_compile_error().into(),
103 }
104}
105
106/// `#[derive(QueryParams)]` — mark a struct as a REST query parameter.
107///
108/// Generates `impl QueryParams`, whose `openapi_params()` describes each field
109/// for the `OpenAPI` document. The generated route registers those parameters, so
110/// the spec is derived from the same declaration that determines the wire
111/// format instead of being inferred separately.
112///
113/// Field rules, both enforced at compile time:
114/// - every field's leaf type must implement
115/// [`QueryScalar`](toolkit_contract::query::QueryScalar) — scalars,
116/// `Option<scalar>`, and `Vec<scalar>`. Nested structs are rejected: a query
117/// string is a flat key/value list and cannot represent them unambiguously.
118/// - a `Vec<..>` field must carry `#[serde(default)]`, since an empty vector
119/// emits no key and would otherwise fail to deserialize.
120///
121/// `#[serde(rename = "...")]` and `#[serde(skip)]` are honoured so the spec
122/// matches what serde actually puts on the wire.
123#[proc_macro_derive(QueryParams)]
124pub fn derive_query_params(input: TokenStream) -> TokenStream {
125 let input = parse_macro_input!(input as syn::DeriveInput);
126 match query_params::generate(&input) {
127 Ok(tokens) => tokens.into(),
128 Err(err) => err.to_compile_error().into(),
129 }
130}
131
132/// `#[derive(ContractError)]` — wire a typed Rust error enum into the
133/// PRD #1536 RFC 9457 envelope.
134///
135/// Per-variant attributes:
136/// - `#[error_code("INSUFFICIENT_FUNDS")]` (required)
137/// - `#[error_domain("billing.v1")]` (required, or set once on the enum)
138/// - `#[canonical(FailedPrecondition)]` (required — one of the 16
139/// `ProblemCategory` variants)
140///
141/// Generates `From<MyError> for Problem` (server-side) and
142/// `TryFrom<Problem> for MyError` (client-side); unknown
143/// `error_code`/`error_domain` pairs round-trip back as the original
144/// `Problem` so callers can still handle them as generic envelopes.
145///
146/// Mark exactly one variant `#[contract_error(fallback)]` (unit, or a single
147/// named field receiving the original `Problem`) to additionally generate a
148/// **total** `From<TransportError> for MyError`, gated on the SDK having either
149/// the `rest-client` or the `grpc-client` feature. Both generated clients call
150/// that conversion on every failure, and they use it to reconstruct typed
151/// variants from an RFC 9457 envelope — the response body over HTTP, the
152/// `x-toolkit-problem-bin` trailer over gRPC — and to route
153/// un-reconstructable transport/protocol failures into the fallback variant.
154///
155/// **Declare a `ContractError` enum as a contract method's error type whenever
156/// the caller branches on a typed variant's payload.** `CanonicalError` cannot
157/// carry one: it has no field for `error_code`, `error_domain` or
158/// `context["data"]`, so converting through it strips the domain identity in
159/// both directions, and for the categories whose context type has required
160/// fields (`FailedPrecondition`, `ResourceExhausted`, `InvalidArgument`,
161/// `Aborted`) it also loses or corrupts the *category*.
162///
163/// The fallback field may be `Problem` **or** `Box<Problem>`. Prefer the boxed
164/// form: a `Problem` is ~208 bytes and the fallback variant sets the size of
165/// the whole enum, hence of every `Result<_, MyError>` the contract returns,
166/// which trips `clippy::result_large_err` on each generated method.
167#[proc_macro_derive(
168 ContractError,
169 attributes(error_code, error_domain, canonical, contract_error)
170)]
171pub fn derive_contract_error(input: TokenStream) -> TokenStream {
172 let input = parse_macro_input!(input as syn::DeriveInput);
173 match contract_error::generate(input) {
174 Ok(tokens) => tokens.into(),
175 Err(err) => err.to_compile_error().into(),
176 }
177}