ingraph-codegen 0.1.0

The emission engine behind ingraph-derive: a plain declaration model in, the ingraph framework faces out.
Documentation
//! The MIRROR MODE: what `#[ingraph::flags(u32, remote = "…")]` adds to a flags declaration.
//!
//! A mirror is a flags set somebody ELSE declared, RESTATED here so this framework has a local type
//! to write impls on. The declaration writes the bits out — names AND numbers, both — and this
//! module writes the crossing between the two types and the pin that keeps the restatement honest.
//!
//! ```ignore
//! // `upstream::Disposition` is the `bitflags!` set another crate declares.
//! // `ingraph-derive/tests/flags_remote.rs` declares one and COMPILES this example, which is what
//! // makes it an example rather than a sketch.
//! #[ingraph::flags(u32, remote = "upstream::Disposition")]
//! #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
//! pub enum Disposition {
//!   Default = 0x1,
//!   Forced = 0x2,
//!   #[ingraph(rename = "HEARING_IMPAIRED")]
//!   Hi = 0x4,
//! }
//! ```
//!
//! # The RESTATEMENT is names AND numbers, where a vocabulary's mirror restates names alone
//!
//! [`enumeration::remote`](crate::enumeration::remote) restates IDENTIFIERS and delegates every
//! word to the upstream's own `Display` and `FromStr`, because a vocabulary's stored form IS a word
//! and two tables over one grammar are two things that can come to disagree. A flags set stores a
//! BIT PATTERN, so the number is the thing that crosses and the word never leaves this crate: the
//! text form is read off THIS declaration's bit table, the wire fields are this declaration's, and
//! the upstream's spelling of a bit is its own business.
//!
//! That inverts what a restatement can get wrong, and the enforcement follows it:
//!
//! | mode | restates | what a mistake IS | who catches it |
//! |---|---|---|---|
//! | `derive(Enum)` mirror | identifiers | a name the upstream has not got | `E0599` at the arm |
//! | `flags` mirror | names and NUMBERS | a number the upstream does not hold | the DRIFT PIN, at compile time |
//!
//! `#[ingraph(rename = "…")]` therefore names the upstream `const` — the same reading the vocabulary
//! mirror's `rename` takes — rather than moving a word, and a mirror's own words stay its own.
//!
//! # The DRIFT PIN is the whole point, and it is a `const`
//!
//! ```ignore
//! const _: () = assert!(Disposition::DEFAULT.bits() as u128 == upstream::Disposition::DEFAULT.bits() as u128);
//! ```
//!
//! One per restated bit. An upstream release that RENUMBERS a bit is a compile error here, in the
//! declaring crate, at the bit that drifted — where without it a mirror would keep crossing values
//! and quietly mean something else, since both sides are just integers and nothing about the
//! crossing could notice.
//!
//! The two sides are cast to [`u128`](core::primitive::u128) rather than compared at their own
//! types, and that is a diagnostic decision rather than arithmetic: an upstream of a DIFFERENT width
//! would otherwise make every pin an `E0308` beside the one named refusal the width law already
//! produces, and a reader would be told the same thing once per bit. Cast, the pin is
//! width-agnostic — so a width fault earns exactly the width sentence and a drift fault earns
//! exactly the drift one.
//!
//! # ABSORPTION: a bit this mirror does not restate is KEPT
//!
//! Both legs of the crossing are `from_bits_retain`, so an upstream value carrying a bit this
//! declaration never named crosses in, survives, and crosses back out as the same number. That is
//! the same posture the vocabulary mirror's escape variant takes and it exists for the same reason:
//! an upstream release that GROWS a bit must not break a build.
//!
//! What names the absence is a TEST-time pin, and this kind gets one for free where the vocabulary
//! kind had to wait for a roster: `<Remote as bitflags::Flags>::FLAGS` is the upstream's own bit
//! table, published by `bitflags!` itself, so a mirror's completeness is walkable without the
//! upstream declaring anything for us. `ingraph-derive/tests/flags_remote.rs` carries that pin,
//! written generically so a mirror arriving in a later commit takes it by naming its own types.
//!
//! **The strict doors are unmoved by any of it**, and the line is *which door*: absorption is what
//! the CROSSING does, and a value reaching this framework from OUTSIDE — an operand a client wrote,
//! a number a row holds, a cursor a process handed back — is still refused when it carries a bit
//! this declaration never named. A mirror is therefore lossless across the crossing and loud at
//! every entrance, which is the posture that keeps an upstream's new bit a thing somebody fixes
//! rather than a thing that decodes into a value this vocabulary cannot spell.
//!
//! The strict TEXT form is the one place an absorbed bit is visible, and `bitflags`' own renderer
//! is what makes it so: a bit with no name renders as a trailing `0x…` token, which the operand
//! grammar already reads back.
//!
//! # What it emits
//!
//! | item | condition |
//! |---|---|
//! | `From<Remote>` and `From<Self> for Remote`, both `from_bits_retain` | always |
//! | one drift pin per restated bit | per bit |
//! | the width obligation below | always |
//!
//! and NOTHING ELSE — no materialization gate, no reference family, no second wire face. The
//! vocabulary mirror emits a `remote()` because its escape holds a WORD and turning one back into an
//! upstream value is real work; here the crossing is a number, `From` is total in both directions,
//! and a gate beside it would be a second name for one conversion.
//!
//! # FOUR things a declaration can get wrong, and whose words say so
//!
//! None of them is checkable at the door — a proc macro cannot see the upstream's declaration — so
//! each is a claim spent against the upstream where the compiler settles it.
//!
//! | the mistake | the refusal | whose words |
//! |---|---|---|
//! | the upstream is not a `bitflags!` set | `E0277` on `bitflags::Flags`, at the `remote = "…"` token | `bitflags`' |
//! | it is one, at another WIDTH | `E0277` on `__IngraphMirrorWidth`, at the same token | this framework's |
//! | a bit's number has DRIFTED | `E0080` at the pin, spanned at the bit | this framework's |
//! | a `rename` names no upstream `const` | `E0599`, spanned at the `rename` literal | rustc's |
//!
//! **The first row was measured rather than settled for.** A marker wrapping the `Flags` bound — a
//! trait carrying `#[diagnostic::on_unimplemented]`, blanket-implemented over it — was written,
//! compiled and thrown away: rustc reports the LEAF obligation, so the headline stayed the foreign
//! trait's and the marker's own sentence never rendered, in either arrangement of
//! `#[diagnostic::do_not_recommend]`. What rustc prints instead names precisely the thing to fix,
//! and `bitflags::Flags` is the honest word for it — the trait `bitflags!` writes, and the one this
//! crate reads every bit table through.
//!
//! The WIDTH row is this framework's because its leaf IS: `__IngraphMirrorWidth` is implemented for
//! exactly one primitive, the declared width, so a differently-carried upstream is an unsatisfied
//! bound on a trait this expansion owns. It is local to the anonymous `const`, so nothing here
//! reaches the framework's shelf for a trait whose whole life is one declaration's expansion.

use quote::{format_ident, quote, quote_spanned};
use syn::spanned::Spanned as _;

use super::{FlagBit, FlagsModel};

#[cfg(test)]
mod tests;

impl FlagsModel {
  /// The whole of what `remote = "…"` adds — one anonymous `const`, written LAST.
  ///
  /// Last, and that is the two-mode law rather than a layout: everything in front of it is what a
  /// flags declaration emits whether or not it mirrors, so a declaration naming no upstream reaches
  /// this method not at all and its expansion is unchanged to the token.
  pub(super) fn mirror(&self, path: &syn::Path) -> proc_macro2::TokenStream {
    let obligation = self.obligation(path);
    let crossing = self.crossing(path);
    let pins = self.bits.iter().map(|bit| self.drift_pin(path, bit));
    quote! {
      const _: () = {
        #obligation

        #crossing

        #(#pins)*
      };
    }
  }

  /// The ONE claim this crate can put its own sentence on: the integer the upstream carries its
  /// bits in is the one this declaration is declared at.
  ///
  /// # The SHAPE claim is `bitflags::Flags` itself, and a marker around it was MEASURED and dropped
  ///
  /// *This is not a flags set* is the other thing a `remote = "…"` can get wrong, and it is reported
  /// as `bitflags::Flags` being unimplemented, at the author's own token. A marker wrapping that
  /// bound — a trait carrying `#[diagnostic::on_unimplemented]`, blanket-implemented over `Flags` —
  /// was written, compiled and thrown away: rustc reports the LEAF obligation, so the headline stayed
  /// the foreign trait's either way and the marker's own sentence never rendered. With
  /// `#[diagnostic::do_not_recommend]` it became a `help:` line naming the marker; without it, a
  /// `note: required for … to implement …`. Neither is worth a trait, and the sentence rustc does
  /// print names precisely the thing a declaration has to fix.
  ///
  /// The WIDTH is different because its leaf is OURS: the trait below is implemented for exactly one
  /// primitive — the declared width — so an upstream of another width is an unsatisfied bound on a
  /// trait this expansion owns, and the message is this framework's. That is the same construction
  /// the vocabulary mirror's totality bound uses, and it is measured in the goldens both times.
  fn obligation(&self, path: &syn::Path) -> proc_macro2::TokenStream {
    let name = &self.name;
    let width = self.width_marker();
    let primitive = format_ident!("{}", self.width.as_str());
    let declared = self.width.as_str();
    let rendered = path_text(path);
    let message = format!(
      "`{{Self}}` is the integer `{rendered}` carries its bits in, and `{name}` is declared at \
       `{declared}`"
    );
    let label =
      format!("a mirror is declared at its upstream's own width, which is not `{declared}`");
    let note = format!(
      "a mirror's declared width is not a choice: both legs of the crossing are `from_bits_retain` \
       over one number, so a narrower declaration would silently drop the upstream's high bits and \
       a wider one would claim a range no upstream value can hold. Write \
       `#[ingraph::flags(<the upstream's own width>, remote = \"{rendered}\")]`"
    );

    quote! {
      // Two methods rather than a bare marker, and that is the diagnostic rather than taste: a bare
      // bound would leave this sentence BESIDE the `E0308` it exists to replace, where a crossing
      // that goes THROUGH the trait has no other way to fail.
      #[diagnostic::on_unimplemented(
        message = #message,
        label = #label,
        note = #note,
      )]
      trait #width: ::core::marker::Sized {
        fn __ingraph_declared(self) -> ::core::primitive::#primitive;

        fn __ingraph_carried(__ingraph_bits: ::core::primitive::#primitive) -> Self;
      }

      impl #width for ::core::primitive::#primitive {
        #[inline]
        fn __ingraph_declared(self) -> ::core::primitive::#primitive {
          self
        }

        #[inline]
        fn __ingraph_carried(__ingraph_bits: ::core::primitive::#primitive) -> Self {
          __ingraph_bits
        }
      }
    }
  }

  /// Both directions of the crossing, and the ONE conversion this mode has.
  ///
  /// `from_bits_retain` on both legs, which is the absorption law: a bit this declaration never
  /// named survives the round trip rather than being truncated away. The alternative — `from_bits`,
  /// refusing — would make an upstream release that grows a bit a runtime failure at the crossing,
  /// which is the failure the whole mirror mode exists to prevent.
  ///
  /// Both legs are spanned WHOLE at the `remote = "…"` path, marker mentions included, and that is
  /// what collapses the two into ONE diagnostic: rustc emits a diagnostic identical in message and
  /// span once, so a width fault earns one sentence rather than one per direction. The marker's
  /// identifier is re-spanned for the same reason — an identifier interpolated into
  /// [`quote_spanned!`] keeps its OWN span, so a marker built at the call site would drag one of the
  /// two mentions back to the whole attribute.
  fn crossing(&self, path: &syn::Path) -> proc_macro2::TokenStream {
    let name = &self.name;
    let flags = self.framework(&["bitflags"], "Flags");
    let mut width = self.width_marker();
    width.set_span(path.span());
    let inbound = quote_spanned! {path.span()=>
      #width::__ingraph_declared(<#path as #flags>::bits(&__ingraph_value))
    };
    let outbound = quote_spanned! {path.span()=>
      <#path as #flags>::from_bits_retain(
        #width::__ingraph_carried(#name::bits(&__ingraph_value)),
      )
    };
    quote! {
      #[automatically_derived]
      impl ::core::convert::From<#path> for #name {
        #[inline]
        fn from(__ingraph_value: #path) -> Self {
          #name::from_bits_retain(#inbound)
        }
      }

      #[automatically_derived]
      impl ::core::convert::From<#name> for #path {
        #[inline]
        fn from(__ingraph_value: #name) -> Self {
          #outbound
        }
      }
    }
  }

  /// ONE bit's drift pin — the restated number, checked against the `const` it restates.
  ///
  /// TWO spans, because the pin has two ways to fail and they are the author's in two different
  /// places. The whole `const` sits at the BIT, so a number that has drifted reports `E0080` under
  /// the line the author would edit; the upstream path inside it sits at whatever NAMED it — the
  /// bit's own identifier where the two spell it alike, and the `rename = "…"` literal where the
  /// declaration spelled the upstream's differently — so a `const` the upstream has not got is
  /// `E0599` under the token that claimed it.
  ///
  /// Both sides go through `bits()`, which `bitflags!` mints as a `const fn` on either type — the
  /// reason this pin can be a `const` at all rather than a test somebody has to remember to run.
  fn drift_pin(&self, path: &syn::Path, bit: &FlagBit) -> proc_macro2::TokenStream {
    let name = &self.name;
    let constant = bit.constant();
    let upstream = bit.upstream();
    let span = bit
      .upstream
      .as_ref()
      .map_or_else(|| bit.ident.span(), syn::Ident::span);
    // RE-SPANNED rather than interpolated as it stands: an identifier keeps its OWN span through
    // `quote_spanned!`, and the fallback one is built here at the call site — so an upstream `const`
    // this declaration merely inherits would report at the whole attribute instead of at the bit.
    let mut named = upstream.clone();
    named.set_span(span);
    let named = quote_spanned!(span=> #path::#named);
    let rendered = path_text(path);
    let drifted = format!(
      "`{name}::{constant}` restates `{rendered}::{upstream}` and declares `{:#x}`, which is not the \
       bit that `const` holds. A mirrored bit carries its UPSTREAM's own number — both legs of the \
       crossing are the bit pattern itself — so a declaration that disagrees with it crosses values \
       that mean something else on the other side. Write the number the upstream holds, or name a \
       different `const` with `#[ingraph(rename = \"…\")]`",
      bit.value
    );
    quote_spanned! {bit.ident.span()=>
      const _: () = ::core::assert!(
        #name::#constant.bits() as ::core::primitive::u128
          == #named.bits() as ::core::primitive::u128,
        #drifted
      );
    }
  }

  /// What the WIDTH obligation is called. Inside the anonymous `const`, so it collides with nothing.
  fn width_marker(&self) -> syn::Ident {
    format_ident!("__IngraphMirrorWidth")
  }
}

/// A path as a declaration WROTE it, for the sentences that quote one back.
fn path_text(path: &syn::Path) -> String {
  quote!(#path).to_string().replace(' ', "")
}