-- | Interned names backed by a C hash table.---- Attribute names are the most repeated data in Nix evaluation.-- This module interns them via a C-side hash table ('cbits/nn_symbol.c'),-- replacing O(n) string comparison with O(1) integer comparison.---- The table holds names alone: attribute names, formals, variables and-- the names interned at startup, as upstream's symbol table does-- (@SymbolTable@, symbol-table.hh at 2.24.9). A name's place is the order-- it was interned in, which decides the order of a set's attributes, so-- a string value is never interned: its bytes live in "Nix.Eval.CStr".---- In an evaluation session ('Nix.Eval.IO.withEvalSession'):---- @-- sym <- symbolIntern "name"-- symbolText sym -- "name"-- @module Nix.Eval.Symbol ( -- * Symbol type Symbol (..), invalidSymbolId, -- * Core operations symbolIntern, symbolText, symbolLen, -- * Diagnostics symbolCount, )whereimport Control.Exception (throwIO)import Data.Text (Text)import qualified Data.Text as Timport qualified Data.Text.Foreign as TFimport Data.Word (Word32)import Foreign.C.Types (CChar, CSize (..))import Foreign.Ptr (Ptr, nullPtr)import Nix.Eval.CData (MonadCData, cdataIO, readImmutable)import Nix.Eval.CStatus (CStatusError (..), arenaLive, cInvariantViolated, cStatusFailure)-- | An interned symbol - a 'Word32' index into the global symbol table.-- Two symbols are equal iff their indices are equal (O(1) comparison).-- 0 is the invalid sentinel.newtype Symbol = Symbol {unSymbol :: Word32} deriving (Eq, Ord, Show)-- | @NN_SYMBOL_INVALID@: the interner's failure sentinel, and the index-- no symbol ever has. Must stay in lockstep with @cbits\/nn_symbol.h@.invalidSymbolId :: Word32invalidSymbolId = 0-- ----------------------------------------------------------------------------- FFI imports (unsafe - these never call back to Haskell)-- ---------------------------------------------------------------------------foreign import ccall unsafe "nn_symbol_intern" c_nn_symbol_intern :: Ptr CChar -> CSize -> IO Word32foreign import ccall unsafe "nn_symbol_text" c_nn_symbol_text :: Word32 -> IO (Ptr CChar)foreign import ccall unsafe "nn_symbol_len" c_nn_symbol_len :: Word32 -> IO CSizeforeign import ccall unsafe "nn_symbol_count" c_nn_symbol_count :: IO Word32-- ----------------------------------------------------------------------------- Core operations-- ----------------------------------------------------------------------------- | Intern a name, returning its t'Symbol'.-- If the name was already interned, returns the existing symbol. The-- table stores the name's UTF-8 bytes.symbolIntern :: (MonadCData m) => Text -> m SymbolsymbolIntern txt = cdataIO . TF.withCStringLen txt $ \(ptr, len) -> checkedSymbol =<< c_nn_symbol_intern ptr (fromIntegral len)-- | Reject the interner's failure sentinel before it can become a-- t'Symbol': wrapped it would read back as the empty string. The table-- answers it outside its init .. destroy window, and inside it for a-- string it cannot hold: one that would take the string arena past its-- 4 GiB of uint32 offsets, or a growth the allocator refuses.checkedSymbol :: Word32 -> IO SymbolcheckedSymbol sid | sid == invalidSymbolId = cStatusFailure "nn_symbol_intern" "the symbol table cannot hold the string (allocation failure or its 4 GiB arena limit)" | otherwise = pure (Symbol sid)-- The reads below are pure ('readImmutable'): a symbol's bytes do not-- change once interned, until arena teardown. They can move, since the-- table grows its byte storage with @realloc@ as later strings are-- interned, and a read takes their address before it copies them, so no-- intern may run between the two: the layer is used from one thread at a-- time.-- | The text of an interned symbol, copied out of the table. The-- invalid id reads as no name; an id the table does not hold raises-- 'CInvariantViolated' in an evaluation session and-- 'ArenaNotInitialized' outside one.symbolText :: Symbol -> TextsymbolText (Symbol sid) | sid == invalidSymbolId = T.empty | otherwise = readImmutable . cdataIO $ do ptr <- c_nn_symbol_text sid if ptr == nullPtr then unheldSymbol "nn_symbol_text" sid else do len <- c_nn_symbol_len sid TF.peekCStringLen (ptr, fromIntegral len)-- | Byte length of a symbol's string: 0 for the invalid id, and for an-- id the table does not hold the failure 'symbolText' raises.symbolLen :: Symbol -> IntsymbolLen (Symbol sid) | sid == invalidSymbolId = 0 | otherwise = fromIntegral . readImmutable . cdataIO $ do len <- c_nn_symbol_len sid -- The table answers 0 for an id it does not hold, which an empty -- name's length also is, so only a 0 asks the table's count. held <- if len /= 0 then pure True else (sid <=) <$> c_nn_symbol_count if held then pure len else unheldSymbol "nn_symbol_len" sid-- | Fail for a symbol id the table does not hold, which it reads as an-- empty name. Outside an evaluation session the table holds none, and-- the failure is 'ArenaNotInitialized'; within one only a defect makes-- such an id, and the failure is 'CInvariantViolated', where the name-- would otherwise be wrong far from its cause.unheldSymbol :: String -> Word32 -> IO aunheldSymbol site sid = do live <- arenaLive if live then cInvariantViolated site ("no symbol " ++ show sid ++ " in the table") else throwIO (ArenaNotInitialized site)-- ----------------------------------------------------------------------------- Diagnostics-- ----------------------------------------------------------------------------- | Number of unique symbols currently interned.symbolCount :: IO Word32symbolCount = c_nn_symbol_count