ingraph 0.1.0

A declaration-driven indexing framework: records and nodes are written as Rust types, and the storage rows, the dataflow between them and the GraphQL query surface are emitted from the declaration.
Documentation
//! The FLAGS VOCABULARY — a bit set a column holds, and what this crate needs to know about one.
//!
//! A flags type is the ENUM kind's sister and not a new universe. Both are a closed set of names a
//! declaration writes down; what differs is the arity of an answer. An enum column holds ONE of the
//! names, so its whole question is membership and its wire form is a value. A flags column holds a
//! SUBSET of them, so its questions are the set-theoretic ones and its wire form has more than one
//! reading to publish — which is the whole of why [the output face is an
//! object](crate::graphql::FlagsView) where a vocabulary's is a scalar.
//!
//! # The bit table is `bitflags`' and never a second one
//!
//! [`FlagsValue`] sits on [`bitflags::Flags`], and everything a bit set can be asked — the declared
//! bits with their words, `bits`, `from_bits`, `contains`, `intersects`, the four set operators and
//! `complement` — is read off that trait rather than restated here. The reason is the one
//! `enumeration`'s reverse maps give: two tables over one vocabulary are two things that can come
//! to disagree, and the disagreement is invisible because each is correct in isolation.
//!
//! What this trait adds is the two facts `bitflags` has no reason to carry — the name a SCHEMA
//! publishes the type under, and the wire FIELD each bit takes — and nothing else.
//!
//! # Undeclared bits are refused at BOTH doors, and that is load-bearing
//!
//! `bitflags` is deliberately permissive about bits outside the declared set: `from_bits_retain`
//! keeps them, `parser::from_str` retains them, and `to_writer` renders them as a trailing hex
//! token. This crate is not. An operand carrying an undeclared bit is refused at the wire with the
//! bit and the legal mask both named, and a stored value carrying one refuses the ROW rather than
//! decoding to something the declaration cannot spell — which is the same posture a vocabulary
//! takes when the stored discriminant names no variant.
//!
//! Two filter words are exact BECAUSE of that strictness rather than in spite of it.
//! `bitflags::Flags::is_all` asks whether every declared bit is set and tolerates extra ones, and
//! `contains(all())` says the same; with no value that came through a DOOR able to carry an extra
//! bit, both are `bits == ALL`, which is an EQUALITY and therefore lowers through the integer family
//! with no bitwise word of its own. [`FlagsFilter`](crate::FlagsFilter)'s `isAll` sugar is written
//! on that identity, and it is why the sugar needs four hard words and not five.
//!
//! *A door* rather than *the system*, and the difference is one declaration wide: a MIRRORED flags
//! set — `#[ingraph::flags(u32, remote = "…")]` — crosses to its upstream by `from_bits_retain`, so
//! a bit that declaration never restated survives the crossing rather than being truncated away.
//! Such a value reaches no sugar: the fold lives at the WIRE PARSE, where the operand arrived
//! through a door, and every other door refuses one on the way in exactly as before.

use bitflags::{
  Flags,
  parser::{ParseHex, WriteHex},
};
use smol_bytes::Utf8Bytes;

use crate::graphql::ToGraphqlOutput;

#[cfg(test)]
mod tests;

/// What a `#[ingraph::flags(…)]` declaration IS, as every layer of this crate reads one.
///
/// # The supertrait carries the vocabulary; this trait carries the wire
///
/// [`bitflags::Flags`] is where the bits live — `FLAGS` is the declared table, one
/// [`Flag`](bitflags::Flag) per bit with its word and its value, in declaration order — and every
/// question this crate asks of a flags value goes through it. A hand-written implementer therefore
/// writes a `bitflags!` type and two constants, and nothing here asks it to restate a bit twice.
///
/// # The four bounds on `Bits`, each spent
///
/// - [`ParseHex`] and [`WriteHex`] are the STRICT TEXT FORM's — `bitflags::parser`'s own grammar is
///   what `text` renders and what the operand's text door parses, and both functions ask for one of
///   the pair. Taking the grammar rather than inventing one is what makes a value this crate writes
///   a value that crate reads.
/// - [`ToGraphqlOutput`] is the `bits` field's. A width publishes under its own scalar — `u32` as
///   `U32` — so the number a client reads out of a flags object is the same form it would read out
///   of a plain `u32` column, rather than a second numeric spelling minted for this face.
/// - `Send` and `Sync` are the OBJECT FACE's: `bits` resolves through a value of this type held
///   across an await, and async-graphql's own `OutputType` asks for both of the form it renders.
///
/// The bounds sit on the SUPERTRAIT's associated type rather than on this trait's own body so that
/// every one of them is available wherever `F: FlagsValue` is written, without a `where` clause
/// repeated at each use.
///
/// # `Copy`, `Send` and `Sync`
///
/// A flags value is a register. `Copy` is what lets the object face hand a derived value —
/// `complement`, `union(other)` — to a nested selection without borrowing anything, and the two
/// auto traits are what an `async fn resolve` holding one across an await needs. Every type
/// `bitflags!` mints satisfies all three; a declaration that declines one gets `E0277` naming this
/// trait at the type, which is the same posture `#[derive(ingraph::Enum)]` takes towards
/// async-graphql's `EnumType: Copy` bound.
pub trait FlagsValue:
  Flags<Bits: ParseHex + WriteHex + ToGraphqlOutput + Send + Sync> + Copy + Send + Sync + 'static
{
  /// The name a SCHEMA publishes this type under.
  ///
  /// The OBJECT face takes it verbatim and the operand scalar takes it with `Input` behind, so the
  /// two seats a flags type occupies are one word apart and neither is spelled twice.
  const GRAPHQL_NAME: &'static str;

  /// The wire FIELD each declared bit takes, parallel to [`Flags::FLAGS`].
  ///
  /// Two lists rather than one struct, because the first of them is the vendored crate's and this
  /// crate has no way to add a column to it. They are built by one loop in one emission, and
  /// [`bits`] is the only thing that reads them — it zips, so a hand-written implementer whose
  /// lists disagree in LENGTH loses the tail rather than indexing out of bounds.
  ///
  /// A bit's word and its field are two different casings of one declaration — `HEARING_IMPAIRED`
  /// is what the text form and the name list spell, `hearingImpaired` is what a selection set
  /// writes — because the two grammars they answer to are different: `bitflags`' text form is a
  /// list of Rust constants, and a GraphQL field is camelCase by that ecosystem's convention.
  const FIELDS: &'static [&'static str];
}

/// One declared bit: the word it is spelled with, the field it is asked for by, and its value.
///
/// The join of [`Flags::FLAGS`] and [`FlagsValue::FIELDS`], built where a caller needs both halves
/// at once — which is every wire face, since a schema publishes the field and an answer carries the
/// word.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct FlagBit<F> {
  /// The bit's word — what the text form and the name list spell it as.
  pub word: &'static str,
  /// The bit's wire field — what a selection set and the per-flag filter fan write.
  pub field: &'static str,
  /// The bit itself, as a flags value with exactly that one bit set.
  pub value: F,
}

/// Every declared bit of `F`, in DECLARATION order.
///
/// A ZIP and not an index, for [`FlagsValue::FIELDS`]' reason: the two lists are built together but
/// live in two traits, and truncating is the failure a hand-written implementer can survive.
///
/// UNNAMED bits are skipped. `bitflags` lets a declaration write `const _ = !0;` to widen the known
/// mask without minting a name, and such an entry has an empty word — there is no field for it and
/// nothing for a client to ask, so it contributes to [`all`] through `Flags::all` and to nothing
/// here. No emission of this crate's writes one.
pub fn bits<F: FlagsValue>() -> impl Iterator<Item = FlagBit<F>> {
  F::FLAGS
    .iter()
    .zip(F::FIELDS)
    .filter(|(flag, _)| !flag.name().is_empty())
    .map(|(flag, field)| FlagBit {
      word: flag.name(),
      field,
      value: F::from_bits_retain(flag.value().bits()),
    })
}

/// The whole declared mask — every bit this vocabulary has a name for.
///
/// [`Flags::all`], under a name that says what it is at the call sites that spend it: it is the
/// operand `isAll` compares against, the mask a refusal quotes back, and the set `complement` is
/// taken within.
#[inline]
#[must_use]
pub fn all<F: FlagsValue>() -> F {
  F::all()
}

/// The value with no bit set.
#[inline]
#[must_use]
pub fn empty<F: FlagsValue>() -> F {
  F::empty()
}

/// One flags value in the STRICT TEXT FORM — `bitflags`' own grammar, which is this vocabulary's
/// exemplar in both directions.
///
/// `DEFAULT | FORCED` for two bits, the empty string for none. The words are the declared ones in
/// declaration order and the separator is ` | `, which is what [`bitflags::parser::to_writer`]
/// writes and what [`bitflags::parser::from_str`] reads — so a text this function renders is a text
/// the operand door accepts, and the round trip is the vendored crate's property rather than an
/// agreement between two functions here.
///
/// # [`Utf8Bytes`] and the allocation it does not always make
///
/// A single-bit value is the common case — a per-flag answer, a mask quoted back in a refusal — and
/// its whole text is one declared word, which is `&'static str`. That case takes
/// [`Utf8Bytes::from_static`], which inlines a short word and borrows a long one and allocates in
/// neither. Only a value with two or more bits assembles, and it assembles once.
#[must_use]
pub fn text<F: FlagsValue>(value: &F) -> Utf8Bytes {
  let mut named = value.iter_names();
  let (Some((word, _)), None) = (named.next(), named.next()) else {
    return Utf8Bytes::from(rendered(value));
  };
  // One declared bit and nothing else set — including no undeclared remainder, which `iter_names`
  // does not yield and `remaining` would still hold.
  if named.remaining().bits() == F::empty().bits() {
    return Utf8Bytes::from_static(word);
  }
  Utf8Bytes::from(rendered(value))
}

/// The text form, assembled.
///
/// [`bitflags::parser::to_writer`] cannot fail against a [`String`] — its refusal is
/// [`core::fmt::Error`], which `String`'s `Write` never returns — so the result is discarded rather
/// than propagated into a signature no caller could act on.
fn rendered<F: FlagsValue>(value: &F) -> String {
  let mut out = String::new();
  let _ = bitflags::parser::to_writer(value, &mut out);
  out
}

/// The WORDS of the bits set in `value`, in declaration order.
///
/// Every word is a declared `&'static str`, so the list allocates its spine and not one character —
/// which is the whole reason the text seat is [`Utf8Bytes`] rather than [`String`].
///
/// Undeclared bits contribute NOTHING here, where [`text`] renders them as a hex token. The
/// asymmetry is deliberate and it is `bitflags`' own: a name list is a list of names, and a bit with
/// no name has none. Nothing in this crate can hand either function a value carrying one — both
/// doors refuse it — so the difference is visible only to a hand-written implementer that reached
/// past them.
#[must_use]
pub fn names<F: FlagsValue>(value: &F) -> Vec<Utf8Bytes> {
  value
    .iter_names()
    .map(|(word, _)| Utf8Bytes::from_static(word))
    .collect()
}

/// One flags value read from the declared bits' WORDS — the operand's list form.
///
/// # Errors
///
/// [`UnknownFlag`] naming the first word that is not one of this vocabulary's, with the legal set
/// beside it. First rather than all, because the list form is written by hand and a reader fixes
/// one word at a time; the message carries the whole vocabulary, so the second mistake is visible
/// from the first message.
pub fn of_words<'a, F: FlagsValue>(
  words: impl IntoIterator<Item = &'a str>,
) -> Result<F, UnknownFlag> {
  let mut value = F::empty();
  for word in words {
    let Some(bit) = F::from_name(word) else {
      return Err(UnknownFlag {
        word: Utf8Bytes::from(word.to_owned()),
      });
    };
    value.insert(bit);
  }
  Ok(value)
}

/// One flags value read from the STRICT TEXT FORM.
///
/// # Errors
///
/// [`UnknownFlag`] for a word this vocabulary does not have, and [`ill_formed`] for a text the
/// grammar does not accept at all. `bitflags`' own parser is what reads it — the grammar is that
/// crate's, so a text form this crate renders is one it reads back — and what this function adds is
/// the refusal of an UNDECLARED BIT, which that parser retains and this vocabulary does not allow:
/// a `0x…` token naming a bit outside the declared mask is a bit no answer could ever spell.
pub fn of_text<F: FlagsValue>(text: &str) -> Result<F, UnknownFlag> {
  let value: F = bitflags::parser::from_str(text).map_err(|_| ill_formed(text))?;
  refuse_unknown_bits(value)
}

/// One flags value read from a raw BIT PATTERN — the operand's integer form, and the form a stored
/// column decodes through.
///
/// # Errors
///
/// [`UnknownFlag`] carrying the undeclared bits, rendered as a hex token beside the legal mask.
pub fn of_bits<F: FlagsValue>(bits: F::Bits) -> Result<F, UnknownFlag> {
  refuse_unknown_bits(F::from_bits_retain(bits))
}

/// The strictness both doors share: a value that reached here through a RETAINING constructor,
/// checked for bits this vocabulary never declared.
fn refuse_unknown_bits<F: FlagsValue>(value: F) -> Result<F, UnknownFlag> {
  if !value.contains_unknown_bits() {
    return Ok(value);
  }
  let mut word = String::from("0x");
  let _ = value.unknown_bits().write_hex(&mut word);
  Err(UnknownFlag {
    word: Utf8Bytes::from(word),
  })
}

/// The refusal for a text the grammar does not accept — quoted whole, because what is wrong with it
/// is its shape rather than one token.
fn ill_formed(text: &str) -> UnknownFlag {
  UnknownFlag {
    word: Utf8Bytes::from(text.to_owned()),
  }
}

/// What a word, a token or a bit outside a vocabulary is refused with.
///
/// It carries the OFFENDING SPELLING and not the vocabulary, because the vocabulary is a property
/// of the type the caller was parsing INTO and every caller of these functions knows it — so the
/// sentence a client reads is assembled where both halves are in hand, which is
/// [`FlagsInput`](crate::graphql::FlagsInput)'s parse, and this type carries no copy of a table it
/// would then have to keep in step.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct UnknownFlag {
  word: Utf8Bytes,
}

impl UnknownFlag {
  /// The spelling that was refused — a word, a hex token or, where the grammar itself was broken,
  /// the whole text.
  #[inline]
  #[must_use]
  pub fn word(&self) -> &str {
    self.word.as_str()
  }
}

impl core::fmt::Display for UnknownFlag {
  fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
    write!(
      f,
      "`{}` names no flag of this vocabulary",
      self.word.as_str()
    )
  }
}

impl core::error::Error for UnknownFlag {}

/// The legal set, as a refusal lists it: every declared word, then the whole mask in the text form.
///
/// Written once and spent by every door, so a client refused at the list form and a client refused
/// at the text form are told the same thing about the same vocabulary.
#[must_use]
pub fn vocabulary<F: FlagsValue>() -> String {
  let words = bits::<F>()
    .map(|bit| format!("`{}`", bit.word))
    .collect::<Vec<_>>()
    .join(", ");
  if words.is_empty() {
    return format!("`{}` declares no flag", F::GRAPHQL_NAME);
  }
  format!(
    "`{}` declares {words} — the whole mask is `{}`",
    F::GRAPHQL_NAME,
    text(&all::<F>()).as_str()
  )
}