ingraph-codegen 0.1.0

The emission engine behind ingraph-derive: a plain declaration model in, the ingraph framework faces out.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
//! What an interface's PAGE is made of: the cursor value one resumes at, and the predicate one is
//! filtered by.
//!
//! # Both are per DATABASE, for the projection row's reason
//!
//! A cursor slot holds a STORED value and a predicate compares one, so both are about the types this
//! database keeps the shared columns at — which is the interface's own pin, the very thing
//! [`equations`](super::equations) discharged at every member's row. So there is one of each per SQL
//! database, exactly as there is one projection row.
//!
//! # The cursor's two SYNTHESIZED slots wear a fence a declaration cannot reach
//!
//! A record's cursor is a variant per stored column. An interface's is that plus TWO: the
//! discriminant and the address, which are the tail of every interface's total order. Their variants
//! are `__IgKind` and `__IgAddress`, and the leading underscores are load-bearing —
//! [`upper_camel`](crate::emit::upper_camel) never produces one, because it treats `_` as a case
//! break and drops it, so no declared field's variant can be spelled either way. That closes a hole
//! the ROW deliberately leaves open: a shared field called `id` collides with the row's address
//! field, as two columns of one name collide anywhere, and it collides with nothing here.
//!
//! # The ADDRESS slot is one variant carrying `<I>Id`, and never one per member
//!
//! The members disagree about what an id IS, and `<I>Id` is already the sum that says so. Folding
//! its variants into the cursor would be that sum written twice — and the codec's tag would then
//! encode WHICH MEMBER in a byte the framework owns, where `<I>Id`'s own codec is the one place a
//! member's id is written and read.
//!
//! # What a HETEROGENEOUS address costs, and which dialect pays
//!
//! `UNION ALL` requires the arms' columns to have compatible types. SQLite has no such rule — a
//! column's type is a value's — so an integer id beside a text one is one union there. PostgreSQL
//! and MySQL refuse it AT THE STATEMENT. Nothing here narrows the sum, because the sum is what the
//! declaration said; what it means is that an interface whose members are keyed differently is a
//! SQLite interface, and the refusal is the engine's own and arrives with the statement.

use quote::{format_ident, quote};

use crate::{
  emit::{leading, parameter},
  interface::{InterfaceField, InterfaceModel},
  model::DatabaseKind,
  unit,
};

/// The cursor variant the DISCRIMINANT rides in.
///
/// A leading `__` is what a declared field's variant cannot have — see the module note.
const KIND_VARIANT: &str = "__IgKind";

/// The cursor variant the ADDRESS rides in.
const ADDRESS_VARIANT: &str = "__IgAddress";

impl InterfaceModel {
  /// What one database's CURSOR VALUE is called: `<I><Db>Cursor`.
  #[must_use]
  pub fn cursor_name(&self, kind: DatabaseKind) -> syn::Ident {
    format_ident!("{}{}Cursor", self.name, kind.suffix())
  }

  /// What one database's PREDICATE is called: `<I><Db>Comparison`.
  #[must_use]
  pub fn comparison_name(&self, kind: DatabaseKind) -> syn::Ident {
    format_ident!("{}{}Comparison", self.name, kind.suffix())
  }

  /// The page's two types per SQL database, plus the address sum's own codec and binding.
  pub(crate) fn page(&self) -> proc_macro2::TokenStream {
    if !self.projects() {
      return quote!();
    }
    let address = self.address_carrier();
    let databases = self.sql_databases().into_iter().map(|kind| {
      let cursor = self.cursor_value(kind);
      let comparison = self.comparison(kind);
      quote! {
        #cursor
        #comparison
      }
    });
    quote! {
      #address
      #(#databases)*
    }
  }

  /// `<I>Id`'s own codec and binding — how the ADDRESS slot of a cursor is written, read and bound.
  ///
  /// DB-LESS for the codec and generic for the binding, which is the shape the sum has: what a
  /// member's id encodes to is the member's own business and the same in every database, and what it
  /// BINDS as is the dialect's. One tag per member, in declaration order, and a tag naming no member
  /// is refused rather than read as the nearest one — the bytes are a client's.
  fn address_carrier(&self) -> proc_macro2::TokenStream {
    let name = super::default_id_name(&self.name);
    let identifiable = self.framework(&["transform"], "Identifiable");
    let cursor_value = self.framework(&["cursor"], "CursorValue");
    let carrier = self.framework(&["comparison", "sql"], "Carrier");
    let database = self.framework(&["sqlx"], "Database");
    let held = self.framework(&["sqlx"], "QueryBuilder");
    let db = parameter("DB");

    let writes = self.members.iter().enumerate().map(|(tag, member)| {
      let variant = &member.ident;
      let tag = u8::try_from(tag).unwrap_or(u8::MAX);
      quote! {
        Self::#variant(__ingraph_value) => {
          __ingraph_out.push(#tag);
          #cursor_value::write_cursor(__ingraph_value, __ingraph_out);
        }
      }
    });
    let reads = self.members.iter().enumerate().map(|(tag, member)| {
      let (variant, ty) = (&member.ident, &member.ty);
      let tag = u8::try_from(tag).unwrap_or(u8::MAX);
      quote! {
        #tag => ::core::option::Option::map(
          <<#ty as #identifiable>::Id as #cursor_value>::read_cursor(__ingraph_rest),
          Self::#variant,
        ),
      }
    });
    let binds = self.members.iter().map(|member| {
      let variant = &member.ident;
      quote!(Self::#variant(__ingraph_value) => #carrier::push_bind(__ingraph_value, __ingraph_qb),)
    });
    let codecs = self.members.iter().map(|member| {
      let ty = &member.ty;
      quote!(<#ty as #identifiable>::Id: #cursor_value,)
    });
    let bounds = self.members.iter().map(|member| {
      let ty = &member.ty;
      quote!(<#ty as #identifiable>::Id: #carrier<#db>,)
    });

    let write_doc = leading("Append this address's member tag and that member's own id bytes.");
    let read_doc = leading("The address `bytes` hold, or `None` where they name no member.");
    let bind_doc = leading("Bind this address, in the type its own member's table stores.");
    quote! {
      #[automatically_derived]
      impl #cursor_value for #name
      where
        #(#codecs)*
      {
        #[doc = #write_doc]
        fn write_cursor(&self, __ingraph_out: &mut ::std::vec::Vec<::core::primitive::u8>) {
          match self {
            #(#writes)*
          }
        }

        #[doc = #read_doc]
        fn read_cursor(__ingraph_bytes: &[::core::primitive::u8]) -> ::core::option::Option<Self> {
          let (__ingraph_tag, __ingraph_rest) =
            <[::core::primitive::u8]>::split_first(__ingraph_bytes)?;
          match *__ingraph_tag {
            #(#reads)*
            _ => ::core::option::Option::None,
          }
        }
      }

      #[automatically_derived]
      impl<#db> #carrier<#db> for #name
      where
        #db: #database,
        #(#bounds)*
      {
        #[doc = #bind_doc]
        fn push_bind(&self, __ingraph_qb: &mut #held<#db>) {
          match self {
            #(#binds)*
          }
        }
      }
    }
  }

  /// `<I><Db>Cursor` — one slot of a cursor over this interface's page in one database.
  ///
  /// A variant per SHARED column at the type this database pins it to, then the two the framework
  /// synthesizes. The tag is the variant's POSITION, so a slot read back carries which column it was
  /// written from and a forged frame cannot move a text value into an integer column's slot.
  ///
  /// The DISCRIMINANT's slot holds the vocabulary rather than its word, and writes the word: what a
  /// statement compares is the projected string, so the codec and the bind are both over
  /// `as_str`, and reading one back goes through `parse` — a word naming no member is refused there
  /// exactly as it is at the row's decode.
  fn cursor_value(&self, kind: DatabaseKind) -> proc_macro2::TokenStream {
    let vis = &self.vis;
    let interface = &self.name;
    let name = self.cursor_name(kind);
    let vocabulary = super::default_kind_name(interface);
    let address = super::default_id_name(interface);
    let kind_variant = format_ident!("{KIND_VARIANT}");
    let address_variant = format_ident!("{ADDRESS_VARIANT}");

    let cursor_value = self.framework(&["cursor"], "CursorValue");
    // The SLOT is reached at THIS dialect — see `emit::query`'s own note for the ruling: a page
    // cursor is session-lived state, so a value's bytes may be the engine's. The blanket over
    // `CursorValue` answers for everything whose bytes are the same everywhere, which is every slot
    // this seat had before the seam existed.
    let dialect_cursor = self.framework(&["cursor"], "DialectCursor");
    let (module, item) = kind.dialect();
    let backend = self.framework(module, item);
    let carrier = self.framework(&["comparison", "sql"], "Carrier");
    let capability = self.framework(&["interface"], "InterfaceKind");
    let database = self.framework(&["sqlx"], "Database");
    let held = self.framework(&["sqlx"], "QueryBuilder");
    let db = parameter("DB");

    // [`InterfaceModel::projected`] and not the whole stored tier: a cursor's slot is a value the
    // statement can hand back and the carrier can bind, and a COLLECTION is neither here. It is the
    // same fence `DatabaseBackend::paged_columns` states for a record's own cursor, WITHOUT that
    // one's per-dialect fork: a record asks `edge_stored` and may answer *array*, where an
    // interface's collection is edge-form on every backend, so no arm of a union can project one.
    // Here it is not even a narrowing of what the union hands back: a collection is no column of
    // the union's output either, so there is nothing decoded for a slot to hold.
    let stored: Vec<&InterfaceField> = self.projected().collect();
    let variants = stored.iter().map(|field| {
      let variant = variant_of(field);
      let ty = self.stored_at(field, kind);
      let doc = leading(&format!("The `{}` column's value.", field.name));
      quote! {
        #[doc = #doc]
        #variant(#ty),
      }
    });
    let writes = stored.iter().enumerate().map(|(tag, field)| {
      let variant = variant_of(field);
      let ty = self.stored_at(field, kind);
      let tag = u8::try_from(tag).unwrap_or(u8::MAX);
      quote! {
        Self::#variant(__ingraph_value) => {
          __ingraph_out.push(#tag);
          <#ty as #dialect_cursor<#backend>>::write_cursor_at(__ingraph_value, __ingraph_out);
        }
      }
    });
    let reads = stored.iter().enumerate().map(|(tag, field)| {
      let variant = variant_of(field);
      let ty = self.stored_at(field, kind);
      let tag = u8::try_from(tag).unwrap_or(u8::MAX);
      quote! {
        #tag => ::core::option::Option::map(
          <#ty as #dialect_cursor<#backend>>::read_cursor_at(__ingraph_rest),
          Self::#variant,
        ),
      }
    });
    let binds = stored.iter().map(|field| {
      let variant = variant_of(field);
      quote!(Self::#variant(__ingraph_value) => #carrier::push_bind(__ingraph_value, __ingraph_qb),)
    });
    let codecs = stored.iter().map(|field| {
      let ty = self.stored_at(field, kind);
      quote!(#ty: #dialect_cursor<#backend>,)
    });
    let bounds = stored.iter().map(|field| {
      let ty = self.stored_at(field, kind);
      quote!(#ty: #carrier<#db>,)
    });
    // The two synthesized tags sit ABOVE the shared columns', so adding a field to the contract
    // moves no existing slot's tag and every cursor a deployment already handed out still reads.
    let kind_tag = u8::try_from(stored.len()).unwrap_or(u8::MAX);
    let address_tag = kind_tag.saturating_add(1);

    let what = super::row::what(kind);
    let doc = leading(&format!(
      "One slot of a cursor over a page of [`{interface}`] in {what} — which column, and the value \
       it held at the boundary row.\n\nThe last two are the framework's own: an interface's total \
       order ends `…, __ig_kind__, id`, because an id is `UNIQUE` only within its own member's \
       table and the discriminant is what tells two members' rows apart."
    ));
    let kind_doc = leading(
      "The DISCRIMINANT the boundary row carried. Minted from the address rather than carried \
       beside it, so the pair cannot disagree.",
    );
    let address_doc =
      leading("The boundary row's ADDRESS — which member, and that member's own id.");
    let write_doc = leading("Append this slot's tag and its value's own bytes.");
    let read_doc = leading("The slot `bytes` hold, or `None` where they name no column.");
    let bind_doc = leading("Bind this slot's value, in the type this database stores.");
    quote! {
      #[doc = #doc]
      #[derive(::core::fmt::Debug, ::core::clone::Clone, ::core::cmp::PartialEq)]
      #vis enum #name {
        #(#variants)*
        #[doc = #kind_doc]
        #kind_variant(#vocabulary),
        #[doc = #address_doc]
        #address_variant(#address),
      }

      #[automatically_derived]
      impl #cursor_value for #name
      where
        #(#codecs)*
        #address: #cursor_value,
      {
        #[doc = #write_doc]
        fn write_cursor(&self, __ingraph_out: &mut ::std::vec::Vec<::core::primitive::u8>) {
          match self {
            #(#writes)*
            Self::#kind_variant(__ingraph_value) => {
              __ingraph_out.push(#kind_tag);
              #cursor_value::write_cursor(
                &::std::borrow::ToOwned::to_owned(#capability::as_str(*__ingraph_value)),
                __ingraph_out,
              );
            }
            Self::#address_variant(__ingraph_value) => {
              __ingraph_out.push(#address_tag);
              #cursor_value::write_cursor(__ingraph_value, __ingraph_out);
            }
          }
        }

        #[doc = #read_doc]
        fn read_cursor(__ingraph_bytes: &[::core::primitive::u8]) -> ::core::option::Option<Self> {
          let (__ingraph_tag, __ingraph_rest) =
            <[::core::primitive::u8]>::split_first(__ingraph_bytes)?;
          match *__ingraph_tag {
            #(#reads)*
            #kind_tag => ::core::option::Option::map(
              ::core::result::Result::ok(<#vocabulary as #capability>::parse(
                &<::std::string::String as #cursor_value>::read_cursor(__ingraph_rest)?,
              )),
              Self::#kind_variant,
            ),
            #address_tag => ::core::option::Option::map(
              <#address as #cursor_value>::read_cursor(__ingraph_rest),
              Self::#address_variant,
            ),
            _ => ::core::option::Option::None,
          }
        }
      }

      #[automatically_derived]
      impl<#db> #carrier<#db> for #name
      where
        #db: #database,
        #(#bounds)*
        ::std::string::String: #carrier<#db>,
        #address: #carrier<#db>,
      {
        #[doc = #bind_doc]
        fn push_bind(&self, __ingraph_qb: &mut #held<#db>) {
          match self {
            #(#binds)*
            // The WORD rather than the vocabulary, because the word is what the arms project and
            // therefore what the resume predicate compares against.
            Self::#kind_variant(__ingraph_value) => #carrier::push_bind(
              &::std::borrow::ToOwned::to_owned(#capability::as_str(*__ingraph_value)),
              __ingraph_qb,
            ),
            Self::#address_variant(__ingraph_value) =>
              #carrier::push_bind(__ingraph_value, __ingraph_qb),
          }
        }
      }
    }
  }

  /// `<I><Db>Comparison` — a predicate over the interface's OWN vocabulary, in the types this
  /// database stores.
  ///
  /// It is [`unit::comparison`](crate::unit::comparison) and
  /// [`unit::comparison_lowering`](crate::unit::comparison_lowering)'s own walks and no longer a
  /// second copy of them. The struct, the constructor, the borrow per column and the
  /// `ComplexComparison` half are ONE emitter, shared with a record's predicate and a standalone
  /// `#[derive(ingraph::Comparison)]`; what an interface supplies is the rows, the noun that says
  /// each column is a SHARED one, and the paragraph a contract's predicate carries where a record's
  /// has nothing to add.
  ///
  /// **Two ROW LISTS rather than one walk with a mode in it**, which is what let the collapse
  /// happen at all: the struct's list is `stored()` and the lowering's is `projected()`, a subset,
  /// and the lowering unit already takes its own list rather than narrowing the struct's — see the
  /// two walks below.
  ///
  /// One field per shared column, each the comparison that column's filter crosses into — the record
  /// comparison's shape exactly, over the contract's fields instead of a row's columns. What differs
  /// is where it is APPLIED: a record's lands at its own table, and this one lands at the union's
  /// derived table, where every arm has already aliased its member's column to the name this
  /// predicate speaks.
  fn comparison(&self, kind: DatabaseKind) -> proc_macro2::TokenStream {
    let interface = &self.name;
    let name = self.comparison_name(kind);
    let db = parameter("DB");

    let to_comparison = self.framework(&["comparison"], "ToDatabaseComparison");
    let crossings = self.crossings(kind);

    // The WHOLE stored tier holds a field here, collections included: a predicate over one is a real
    // question and the crossing that builds it is the same crossing every other column takes. What
    // differs is WHERE it is applied — see the two walks below.
    let rows: Vec<unit::ComparisonColumn> = self
      .stored()
      .map(|field| {
        let (filter, stored) = (self.filter_of(field), self.stored_at(field, kind));
        unit::ComparisonColumn {
          // An INTERFACE's fields carry no condition seat — the `#[cfg]` word is the
          // record family's, and this model has no field to hold one.
          gate: proc_macro2::TokenStream::new(),
          member: field.name.clone(),
          name: format!("shared `{}` column", field.name),
          held: quote!(<#filter as #to_comparison<#stored, #db>>::Comparison),
        }
      })
      .collect();
    let header = unit::UnitHeader {
      vis: &self.vis,
      name: name.clone(),
      subject: format!("[`{interface}`]"),
      note: Some(
        "Written in the INTERFACE's vocabulary and lowered ONCE, above the union — a member that \
         calls a shared column something else has already aliased it in its own arm, so one \
         predicate answers whichever member the row came from."
          .to_owned(),
      ),
    };
    let (declaration, methods) = unit::comparison(&header, &db, &crossings, &rows);

    // `ComplexComparison` is the ABOVE-THE-UNION half and it counts and renders the PROJECTED
    // columns alone. A collection has no column in the union's output to compare — no backend keeps
    // every collection in a column of the row, and the choice is the MEMBER's — so its conjuncts are
    // rendered per ARM, at that member's own edge table, through `SqlInterface::collections`. Two
    // walks over one struct, and the struct is the whole predicate either way.
    let seats = unit::LoweringSeats {
      backend: self.framework(&["comparison"], "Backend"),
      complex: self.framework(&["comparison"], "ComplexComparison"),
      frame: self.framework(&["comparison"], "Frame"),
      at: self.framework(&["comparison"], "At"),
      field_name: self.framework(&["field"], "FieldName"),
    };
    // `flatten` is FALSE at every column and is not a fork this side has: the word that sets it is a
    // record's `persist(flatten)`, over a column whose comparison occupies more than one of its
    // table's. An interface owns no table, and what it renders against is the union's derived one —
    // where a column exists because an arm aliased it, which is one name and one segment.
    let lowered: Vec<unit::LoweringColumn> = self
      .projected()
      .map(|field| unit::LoweringColumn {
        // An INTERFACE's fields carry no condition seat — the `#[cfg]` word is the
        // record family's, and this model has no field to hold one.
        gate: proc_macro2::TokenStream::new(),
        member: field.name.clone(),
        rendered: field.name.to_string(),
        flatten: false,
        through: None,
      })
      .collect();
    let lowering = unit::comparison_lowering(&name, &db, &crossings, &seats, &lowered);

    quote! {
      #declaration
      #methods
      #lowering
    }
  }

  /// What a predicate over these shared columns ASSUMES, and what every item naming it repeats
  /// verbatim: that the database is a backend at all, and that each column's filter crosses into
  /// something for it.
  ///
  /// One function rather than one per item, for the record comparison's reason: the struct's `where`
  /// clause is the whole of what makes its field types well formed, so an impl asserting anything
  /// more would report a missing crossing twice.
  fn crossings(&self, kind: DatabaseKind) -> proc_macro2::TokenStream {
    let db = parameter("DB");
    let backend = self.framework(&["comparison"], "Backend");
    let to_comparison = self.framework(&["comparison"], "ToDatabaseComparison");
    let crossings = self.stored().map(|field| {
      let (filter, stored) = (self.filter_of(field), self.stored_at(field, kind));
      quote!(#filter: #to_comparison<#stored, #db>,)
    });
    quote! {
      #db: #backend,
      #(#crossings)*
    }
  }

  /// The FILTER one shared field is asked for by — the PIN's own word where the declaration wrote
  /// one, and the type's own registry row where it did not. Never a name this crate builds.
  ///
  /// The interface grammar carries interpretation words now, so both paths a record's emission has
  /// are here and they are the SAME function: [`crate::emit::filter_of`], which is where the routing
  /// is written down once. A pin with no word takes the type's row, and a type with no row is
  /// `E0277` at the declaration naming it.
  ///
  /// THREE readers, and that is what makes the crossing writable at all: the predicate's own field
  /// types, the wire filter's, and the leg that carries one into the other. A filter asked for twice
  /// is a filter two answers can disagree about, and between those two there is no conversion.
  pub(super) fn filter_of(&self, field: &InterfaceField) -> proc_macro2::TokenStream {
    // The STORED face: an interface's own filter is projected into `ToDatabaseComparison` at
    // three seats, and that row is the column face's alone.
    crate::emit::filter_of(
      &self.krate,
      &field.ty,
      field.marker.as_ref(),
      crate::emit::FilterFace::Column,
    )
  }
}

/// The cursor variant ONE shared column rides in — the field's name in upper camel case, which is
/// the record cursor's own convention read through the contract's fields instead of a row's columns.
fn variant_of(field: &InterfaceField) -> syn::Ident {
  crate::emit::upper_camel(&field.name.to_string())
}