packages feed

pykinos-penelope-0.1.1.0: src/Pykinos/Penelope/EffectProfile.hs

{-# LANGUAGE DerivingStrategies #-}

-- | Module: Pykinos.Penelope.EffectProfile
-- Description: Static effect usage profiles and dynamic reader carrier selection
--
-- Analyzes compile-time or pipeline-level effect requirements to choose the
-- optimal physical carrier strategy for reader/environment effects.
module Pykinos.Penelope.EffectProfile
  ( -- * Static Effect Profile
    StaticEffectProfile(..)
  , defaultProfile
    -- * Reader Strategy
  , ReaderStrategy(..)
  , selectReaderStrategy
  ) where

-- | Static summary of effect usage characteristics within an execution pipeline.
data StaticEffectProfile = StaticEffectProfile
  { sepUsesLocal         :: !Bool
    -- ^ Whether reader environment modification ('local') is invoked.
  , sepUsesMultiShot     :: !Bool
    -- ^ Whether continuations may be invoked multiple times (e.g. non-determinism).
  , sepUsesCatchRollback :: !Bool
    -- ^ Whether transactional rollback or exception recovery is needed.
  , sepUsesParallelRace  :: !Bool
    -- ^ Whether concurrent branches race over the environment.
  , sepUsesListenCensor  :: !Bool
    -- ^ Whether writer introspection ('listen' / 'censor') is active.
  } deriving stock (Eq, Show)

-- | Conservative default effect profile assuming only single-shot linear execution.
defaultProfile :: StaticEffectProfile
defaultProfile = StaticEffectProfile
  { sepUsesLocal         = False
  , sepUsesMultiShot     = False
  , sepUsesCatchRollback = False
  , sepUsesParallelRace  = False
  , sepUsesListenCensor  = False
  }

-- | Physical representation strategy for reader environment state.
data ReaderStrategy
  = StrategyFrozenFast
    -- ^ Pure immutable single-reference pointer (fastest when no 'local' is used).
  | StrategyShallowUndoTrail
    -- ^ In-place mutable environment with an undo log for scoped lexical restoration.
  | StrategyPersistentART
    -- ^ Persistent radix-tree environment supporting branching, backtracking, and races.
  deriving stock (Eq, Ord, Show, Enum, Bounded)

-- | Selects the optimal reader strategy based on the static effect profile.
selectReaderStrategy :: StaticEffectProfile -> ReaderStrategy
selectReaderStrategy prof
  | not (sepUsesLocal prof) = StrategyFrozenFast
  | sepUsesMultiShot prof || sepUsesParallelRace prof = StrategyPersistentART
  | otherwise = StrategyShallowUndoTrail