ingraph_codegen/search.rs
1//! What a SEARCH RECIPE declared: the members it fuses, the towers it binds to them, and the seats
2//! a caller broadcasts one question into.
3//!
4//! ```ignore
5//! #[ingraph::search(shared(text(type = "String")), dedup(hash), limit = 20)]
6//! pub struct TravelSearch {
7//! #[ingraph(weight = 1.0, depth = 50, tower(zh(type = "crate::ZhQuery", shared)))]
8//! subs: Subs,
9//! #[ingraph(weight = 2.0, depth = 100,
10//! tower(text(type = "crate::ClipText", shared, floor = "crate::floors::SEM_TEXT")),
11//! tower(image(type = "crate::ClipImage", shared)))]
12//! shots: Shots,
13//! }
14//! ```
15//!
16//! # FIELDS ARE MEMBERS, which is what deleted the word-count door laws
17//!
18//! A recipe LISTS what it fuses. A field's NAME is the member's name and its TYPE is the index that
19//! member reads, so there is nothing here that mints a name, nothing that counts words to decide how
20//! many members a door has, and nothing to trim: the arity is the declaration's own field list. That
21//! is the same collapse the tower grammar made one layer down, where fields became steps.
22//!
23//! # THE MODEL IS ONE CLOCK, and the compiler is the other
24//!
25//! Everything here is what the DECLARATION SAID. A tower is carried as the TYPE PATH the word
26//! named, never as a name this pass mangled out of one and never as a fact it went looking for:
27//! whether that type is a tower, what it is asked, what it answers and what knobs it seats are
28//! questions only the compiler can answer, and the emission asks them as projections off
29//! `DeclaredTower` and `SearchTower` where it can see them. A model that resolved a path would be
30//! guessing across the expansion wall — the wall the `Declared…` record family exists to be
31//! shouted over.
32//!
33//! # ABSENCE IS A ROAD at every number here
34//!
35//! `weight`, `depth`, `limit` and both `floor`s are [`Option`], and [`None`] never means a value
36//! this pass invented. It means the declaration named none, and the tier below it answers: the
37//! resolution order is request > this recipe > the election's own field > its container > the
38//! framework's own number. A model that defaulted a number here would be a recipe silently
39//! outranking an election that had a better answer.
40
41use core::num::NonZeroU32;
42
43use quote::quote;
44
45use crate::index::Dedup;
46
47mod bind;
48mod fuse;
49mod record;
50#[cfg(test)]
51mod tests;
52mod wire;
53
54/// A validated search recipe, ready to emit.
55///
56/// PLAIN — no `Copy`, no comparison — for [`super::tower::TowerModel`]'s reason: a model is carried
57/// once, from the pass that validated it to the pass that emits it.
58#[derive(Debug, Clone)]
59pub struct SearchModel {
60 /// The path to the `ingraph` crate itself — `::ingraph` unless `#[ingraph(crate = "…")]` named
61 /// another.
62 pub krate: syn::Path,
63 /// The declared type — what the recipe's own faces are minted on.
64 pub name: syn::Ident,
65 /// The declaration's own visibility, which everything minted beside it takes.
66 pub vis: syn::Visibility,
67 /// **THE BROADCAST SEATS** — `shared(text(type = "String"), …)`, in declaration order.
68 ///
69 /// EMPTY where the head wrote no `shared(…)` at all, which is the recipe whose arms are each
70 /// asked their own question. A seat is what a caller fills once for the whole recipe, and the
71 /// arms that read it say so with their own `shared` word.
72 ///
73 /// SEVERAL are a CHOICE and never a companion: the published field asks with one `@oneOf` object
74 /// and a client fills exactly one seat, so a value that rides WITH a question — a language tag, a
75 /// locale — is a field of a seat's own TYPE rather than a seat beside it. Written as a seat it
76 /// would be unaskable beside the question it belongs to. The grammar's own note carries the
77 /// boundary in full; see `ingraph-derive`'s `search` module.
78 pub seats: Vec<SeatModel>,
79 /// How this recipe's fused doors tell two roots apart — `dedup(hash)`.
80 ///
81 /// NOT an [`Option`], and that is the graph root's own shape one grain down: the absent word is
82 /// [`Dedup::Hash`] rather than a deferral, because every key an emitted node mints derives
83 /// [`Hash`](core::hash::Hash) and the join a recipe has always had is the one an unwritten word
84 /// still names.
85 pub dedup: Dedup,
86 /// How many roots the recipe's own door answers with when nothing asks otherwise — `limit = 20`.
87 ///
88 /// [`None`] where the word was OMITTED, and it is a deferral rather than a default: the tier
89 /// order is request > recipe > election field > container > the framework's own number, so a
90 /// recipe that names none lets the declaration below it answer. Writing the framework's 20 in
91 /// here would make an unwritten word outrank an election that wrote its own.
92 pub limit: Option<NonZeroU32>,
93 /// WHICH BACKEND DRESSES THIS RECIPE — `graphql(async_graphql)`, or [`None`] where it named none.
94 ///
95 /// The retrieving family's presence law at the recipe grain: a recipe with no block emits its
96 /// whole Rust surface — the record, the packages, the evidence enums and the door — and mints no
97 /// schema. That is what a fused read a deployment drives from Rust wants, and it is also what
98 /// keeps the wire face's own demands off a recipe that publishes nothing: the seams a resolver
99 /// reaches its members through ([`FusedEngine`], [`FusedCitizen`], [`WireRoot`]) are asked for
100 /// only where a field is published.
101 ///
102 /// [`FusedEngine`]: https://docs.rs/ingraph
103 /// [`FusedCitizen`]: https://docs.rs/ingraph
104 /// [`WireRoot`]: https://docs.rs/ingraph
105 pub graphql: Option<crate::model::GraphqlKind>,
106 /// The members, in declaration order. NEVER EMPTY: a recipe with no member is refused at the
107 /// front end, there being nothing to ask and nothing to fuse.
108 pub members: Vec<MemberModel>,
109}
110
111impl SearchModel {
112 /// EVERYTHING a recipe mints: the record it states across the expansion wall, and the fusion unit
113 /// its door runs.
114 ///
115 /// The recipe REPLACES its own declaration, as every attribute macro does, so the host struct is
116 /// echoed by the front end and what arrives here is only what is added beside it.
117 #[must_use]
118 pub fn emit(&self) -> proc_macro2::TokenStream {
119 let record = self.record();
120 let seats = self.seat_markers();
121 let bindings = self.bindings();
122 let fuse = self.fuse();
123 let wire = self.wire();
124 quote! {
125 #record
126 #seats
127 #bindings
128 #fuse
129 #wire
130 }
131 }
132
133 /// **WHETHER THIS RECIPE PUBLISHES A QUERY FIELD AT ALL.**
134 ///
135 /// Two conditions, and neither counts past zero. A recipe has to have NAMED a backend — the
136 /// presence law — and it has to broadcast into AT LEAST ONE seat, because the wire road's question
137 /// is the seat a client fills and a recipe with none has nothing for that argument to be.
138 ///
139 /// SEVERAL seats used to fail here too, and the `@oneOf` member seats are what retired that arm:
140 /// the published field's question becomes a choice — one input field per seat, exactly one filled —
141 /// and the members whose arms bought that seat answer the request. A recipe with ONE seat publishes
142 /// the bare argument it always did, which is the additive law read at the schema.
143 #[must_use]
144 pub fn mounts(&self) -> bool {
145 self.graphql.is_some() && !self.seats.is_empty()
146 }
147
148 /// **WHETHER THE PUBLISHED QUESTION IS A CHOICE** — several declared seats, so the field asks with
149 /// one `@oneOf` argument rather than with the seat itself.
150 ///
151 /// The fork every wire-side emitter reads, written once: a single-seat recipe's whole face is what
152 /// it was before the choice existed, byte for byte, and this is the one predicate that says so.
153 #[must_use]
154 pub fn chooses(&self) -> bool {
155 self.seats.len() > 1
156 }
157
158 /// Whether any member binds any tower at all.
159 ///
160 /// The question the question layer asks first: a recipe whose members are all plain coordinate
161 /// members has no arm to publish and no tower to walk, and is the one-member text search the
162 /// retiring `ask` family used to spell.
163 #[must_use]
164 pub fn bound(&self) -> bool {
165 self.members.iter().any(|member| !member.arms.is_empty())
166 }
167}
168
169/// ONE BROADCAST SEAT — the head's `shared(<name>(type = "…"))`.
170///
171/// The name and the type are the whole of it, and they answer two different parties: the NAME is
172/// what an arm writes `shared` against, and the TYPE is what a caller of the whole recipe hands
173/// over once.
174#[derive(Debug, Clone)]
175pub struct SeatModel {
176 /// The seat's name, as the head wrote it — the word an arm's `shared` is resolved against.
177 pub name: syn::Ident,
178 /// What a caller hands this seat, as the word named it.
179 ///
180 /// A TYPE and never a kind: a seat is a question a caller asks, and this framework's questions
181 /// are the application's own types.
182 pub ty: syn::Type,
183}
184
185/// ONE MEMBER — the field, the index it reads, and the defaults the recipe declares for its route.
186#[derive(Debug, Clone)]
187pub struct MemberModel {
188 /// The field that names this member — its ONE name, and the span every refusal about it is
189 /// reported at.
190 pub field: syn::Ident,
191 /// The INDEX this member reads, as the field declared it.
192 ///
193 /// Carried as the type it was written as and never resolved: whether it is an index, what it is
194 /// addressed by and whether its coordinates meet this member's arms are the emission's questions,
195 /// asked where the compiler can answer them.
196 pub ty: syn::Type,
197 /// This member's coefficient in the recipe's fold — `weight = 2.0`, and this word's FIRST
198 /// declaration-side home.
199 ///
200 /// [`None`] where the word was omitted, under which the member takes the request layer's own
201 /// `Route::DEFAULT_WEIGHT` — the multiplicative identity, so a recipe where nobody weighted
202 /// anything runs the unweighted fold exactly rather than an approximation of it.
203 pub weight: Option<f64>,
204 /// How deep this member's route is asked when nothing asks otherwise — `depth = 100`.
205 ///
206 /// [`None`] where the word was omitted, on [`SearchModel::limit`]'s road: it defers rather than
207 /// defaults, and a declared ceiling CAPS whatever it says wherever it is spent.
208 pub depth: Option<NonZeroU32>,
209 /// The FLOOR this member's route is read at, as a const PATH — `floor = "crate::floors::SEM"`.
210 ///
211 /// A PATH and never a literal, which is §4's law rather than this grammar's taste: a floor is a
212 /// value in the ENGINE's own currency, an open type this framework never sees, so there is
213 /// nothing here that could parse one. A const is a value its own crate already built.
214 ///
215 /// [`None`] where the word was omitted, under which the read has no declared floor and whatever
216 /// the request names is the only one.
217 pub floor: Option<syn::Path>,
218 /// The towers bound to this member, in declaration order — EMPTY for a plain coordinate member.
219 ///
220 /// Each is one ARM of this member's question, and its name is that arm's name.
221 pub arms: Vec<ArmModel>,
222}
223
224/// ONE BOUND TOWER — `tower(text(type = "crate::ClipText", shared, floor = "…"))`.
225///
226/// The arm of a member's question that carries a tower's own question, and the row the emission
227/// spends every projection off: what the tower is asked, what it answers, whether its walk is
228/// awaited and what it seats are all read through [`ArmModel::tower`] rather than guessed from
229/// [`ArmModel::name`].
230#[derive(Debug, Clone)]
231pub struct ArmModel {
232 /// The arm's name, as the word named it — the variant this arm mints, and the seat name its
233 /// `shared` is resolved against.
234 pub name: syn::Ident,
235 /// The TOWER this arm walks, as the `type = "…"` word wrote it.
236 ///
237 /// A TYPE PATH, and the whole reason the record family exists: the recipe's own expansion cannot
238 /// see this tower's fields, so what it does with the path is project off it —
239 /// `<Ty as SearchTower>::Question`, `<Ty as DeclaredTower>::StepOptions` — and the compiler resolves
240 /// what neither declaration could.
241 pub tower: syn::Type,
242 /// Where this arm's question comes from when the caller broadcast one — the `shared` word.
243 ///
244 /// [`None`] where the arm wrote no `shared`, under which the arm is asked its own question and
245 /// nothing else.
246 pub shared: Option<SharedBinding>,
247 /// The FLOOR this arm's read is taken at, as a const PATH — [`MemberModel::floor`]'s law at the
248 /// arm's own grain.
249 pub floor: Option<syn::Path>,
250}
251
252/// WHERE AN ARM'S QUESTION COMES FROM when the recipe was asked once — the resolved `shared` word.
253///
254/// Two halves, because the word decides two things: WHICH seat feeds this arm, and HOW the seat's
255/// type becomes the tower's question.
256#[derive(Debug, Clone)]
257pub struct SharedBinding {
258 /// The head seat this arm reads, resolved from the declaration's OWN tokens.
259 ///
260 /// By NAME where a seat of the arm's name exists, and the SOLE seat where a recipe declared
261 /// exactly one — the resource axis's own sole-default law, one layer up. It is a resolution and
262 /// not a derivation: both halves are written in this declaration, so nothing here reaches past
263 /// the expansion wall, and a `shared` that matches no seat is refused rather than resolved.
264 pub seat: syn::Ident,
265 /// HOW the seat's type becomes this tower's question.
266 pub bridge: SharedBridge,
267}
268
269/// THE BRIDGE a broadcast seat crosses to reach one arm's question — the word inside `shared`.
270///
271/// A CLOSED framework vocabulary, because what it names is which of two conversions the emission
272/// demands and which of two shapes a hook has. The types on either side are the application's and
273/// stay open; the crossing is the framework's.
274///
275/// The variants are NOT called `From` and `TryFrom`, and the reason is measured rather than stylistic
276/// — see the runtime record's own `Bridge`, whose note carries the six goldens that moved on that
277/// word. One vocabulary across the two crates, so the reason lands once and the names never diverge.
278#[derive(Debug, Clone)]
279pub enum SharedBridge {
280 /// `shared` — the crossing that cannot fail, demanded as [`From`].
281 Total,
282 /// `shared(try)` — the crossing that can, demanded as [`TryFrom`], whose failure surfaces through
283 /// the member's own refusal variant.
284 Fallible,
285 /// `shared(with = "path::to::hook")` — a function of the author's, taking the seat and answering
286 /// this arm's question.
287 ///
288 /// HOOKS BEAT TRAITS: a crossing an application wrote is not obliged to be expressible as an impl
289 /// it is allowed to write, the orphan rule being what it is.
290 Hook(syn::Path),
291 /// `shared(try_with = "path::to::hook")` — the fallible hook, [`Hook`](Self::Hook)'s twin.
292 FallibleHook(syn::Path),
293}
294
295impl SharedBridge {
296 /// The WORD this bridge was written as, for the refusals and the record that spell it.
297 #[must_use]
298 pub const fn word(&self) -> &'static str {
299 match self {
300 Self::Total => "shared",
301 Self::Fallible => "try",
302 Self::Hook(_) => "with",
303 Self::FallibleHook(_) => "try_with",
304 }
305 }
306
307 /// Whether this crossing can FAIL — the half the emission spends on the refusal variant.
308 #[must_use]
309 pub const fn fallible(&self) -> bool {
310 matches!(self, Self::Fallible | Self::FallibleHook(_))
311 }
312
313 /// The author's own function where the word named one.
314 #[must_use]
315 pub const fn hook(&self) -> Option<&syn::Path> {
316 match self {
317 Self::Hook(path) | Self::FallibleHook(path) => Some(path),
318 Self::Total | Self::Fallible => None,
319 }
320 }
321}