packages feed

nano-ui-0.2.0.0: lib/NanoUI/Internal/Id.hs

{-# LANGUAGE StrictData #-}
{-# OPTIONS_HADDOCK not-home #-}

-- | Widget ids and the id context they are derived from. See the
-- "Widget identity" section of "NanoUI" for how ids are assigned.
module NanoUI.Internal.Id
  ( WidgetId (..)
  , mkWidgetId
  , IdContext (..)
  , initialIdContext
  , idContextWidgetId
  , scopeIdContext
  , widgetId
  , hashWidgetId
  , mix64
  , mixFnv
  , scopeTag
  , keyedTag
  , enterScope
  , enterKeyed
  )
where

import Data.Bits (shiftR, xor)
import Data.Char (ord)
import Data.Hashable (Hashable)
import Data.Primitive.Types (Prim)
import Data.Word (Word64, Word8)
import GHC.Stack (HasCallStack, SrcLoc (..), callStack, getCallStack)

-- | Stable store and interaction identity. Zero is reserved for no widget.
-- Make one from a hash with 'mkWidgetId', which keeps it in the range an
-- 'Int' holds.
newtype WidgetId = WidgetId Word64
  deriving stock (Eq, Ord, Show)
  deriving newtype (Hashable, Prim)

-- | The id for a hash. The node arena and the store keep ids in 'Int'
-- slots, so an id must come back unchanged from a trip through 'Int'. On a
-- 64-bit target that holds for every hash, and this is the hash itself. On a
-- target whose 'Int' is 32 bits (wasm32) the id is the hash's low 32 bits,
-- sign-extended as converting that 'Int' back does.
{-# INLINE mkWidgetId #-}
mkWidgetId :: Word64 -> WidgetId
mkWidgetId h = WidgetId (fromIntegral (fromIntegral h :: Int))

-- | Parent-path hash, the next sibling widget's position within that path,
-- and the next positional Var's position, counted separately so widgets
-- that come and go never move a Var.
data IdContext = IdContext
  { currentId :: {-# UNPACK #-} !Word64
  , siblingId :: {-# UNPACK #-} !Word64
  , varSiblingId :: {-# UNPACK #-} !Word64
  }
  deriving stock (Eq, Show)

-- | Root path and sibling position used at the start of each view pass.
initialIdContext :: IdContext
initialIdContext = IdContext 0x243F6A8885A308D3 0 0

-- | A fresh scope at path @p@, with both counts at zero.
{-# INLINE scopeIdContext #-}
scopeIdContext :: Word64 -> IdContext
scopeIdContext p = IdContext p 0 0

-- | Id of the next sibling in this context. A zero id becomes 1, so
-- @WidgetId 0@ never names a real widget.
{-# INLINE idContextWidgetId #-}
idContextWidgetId :: IdContext -> WidgetId
idContextWidgetId (IdContext cid sid _) =
  let
    wid = mkWidgetId (mix64 cid sid)
   in
    if wid == WidgetId 0 then WidgetId 1 else wid

-- | Hash salt distinguishing an ordinary child scope from a keyed scope.
scopeTag :: Word64
scopeTag = 0x9E3779B185EBCA87

-- | Hash salt distinguishing a keyed child scope from a positional scope.
keyedTag :: Word64
keyedTag = 0xC2B2AE3D27D4EB4F

-- | Return the advanced parent and a fresh child context derived from its
-- sibling position and the supplied tag.
{-# INLINE enterScope #-}
enterScope :: Word64 -> IdContext -> (IdContext, IdContext)
enterScope tag parent = enterChild (siblingId parent) tag parent

-- | Return the parent unchanged and a child path derived from the key, not
-- the sibling position. Keys must be unique within the parent. A keyed scope
-- takes no sibling position, so the widgets after a keyed list keep their ids
-- when the list grows or shrinks.
{-# INLINE enterKeyed #-}
enterKeyed :: Word64 -> IdContext -> (IdContext, IdContext)
enterKeyed tag parent@(IdContext pid _ _) = (parent, scopeIdContext (mix64 (mix64 pid tag) keyedTag))

-- | Advance the parent's sibling counter and derive a child path from the
-- parent path, @seed@ and @tag@. The child starts both counts at zero; the
-- parent's Var count is untouched, so a scope takes no Var position.
{-# INLINE enterChild #-}
enterChild :: Word64 -> Word64 -> IdContext -> (IdContext, IdContext)
enterChild seed tag (IdContext pid sib vs) = (IdContext pid (sib + 1) vs, scopeIdContext (mix64 (mix64 pid seed) tag))

-- | Hash the call site's package, module, file, line, and column. Repeated
-- calls at one source location return the same id; this is not a list-item key.
-- Throws if the call stack is empty.
{-# INLINE widgetId #-}
widgetId :: HasCallStack => WidgetId
widgetId =
  let
    stack = getCallStack callStack
    loc = case stack of
      (_, loc') : _ -> loc'
      [] -> error "widgetId: empty CallStack"
   in
    hashSrcLoc loc

hashSrcLoc :: SrcLoc -> WidgetId
hashSrcLoc loc =
  mkWidgetId $
    fnv1a (srcLocPackage loc)
      `mixFnv` fnv1a (srcLocModule loc)
      `mixFnv` fnv1a (srcLocFile loc)
      `mixFnv` fromIntegral (srcLocStartLine loc)
      `mixFnv` fromIntegral (srcLocStartCol loc)

-- | Unwrap the id's existing hash without hashing it again.
{-# INLINE hashWidgetId #-}
hashWidgetId :: WidgetId -> Word64
hashWidgetId (WidgetId w) = w

-- | FNV-1a over the low byte of each character. Intended for identifier seeds,
-- not general Unicode hashing or cryptography.
{-# INLINE fnv1a #-}
fnv1a :: String -> Word64
fnv1a s =
  foldl'
    (\acc c -> (fromIntegral @Word8 @Word64 (fromIntegral (ord c)) `xor` acc) * 0x00000100000001B3)
    0xcbf29ce484222325
    s

-- | Mix two 64-bit identifier components with wrapping arithmetic.
-- This is a non-cryptographic hash combiner.
{-# INLINE mix64 #-}
mix64 :: Word64 -> Word64 -> Word64
mix64 x y =
  let
    z = x + (y * 0x9E3779B97F4A7C15)
    z1 = z `xor` (z `shiftR` 30)
    z2 = z1 * 0xBF58476D1CE4E5B9
    z3 = z2 `xor` (z2 `shiftR` 27)
   in
    z3 * 0x94D049BB133111EB

-- | Combine two hash words with an FNV xor-and-multiply step.
{-# INLINE mixFnv #-}
mixFnv :: Word64 -> Word64 -> Word64
mixFnv x y = (x `xor` y) * 1099511628211