|
| 1 | +{-# LANGUAGE FlexibleInstances #-} |
| 2 | +{-# LANGUAGE GADTs #-} |
| 3 | +{-# LANGUAGE GeneralizedNewtypeDeriving #-} |
| 4 | +{-# LANGUAGE MultiParamTypeClasses #-} |
| 5 | +{-# LANGUAGE TypeOperators #-} |
| 6 | +{-# LANGUAGE UndecidableInstances #-} |
| 7 | +module Analysis.Exception |
| 8 | +( Exception(..) |
| 9 | +, ExcSet(..) |
| 10 | +, fromExceptions |
| 11 | +, var |
| 12 | +, exc |
| 13 | + -- * Exception tracing analysis |
| 14 | +, ExcC(..) |
| 15 | +) where |
| 16 | + |
| 17 | +import Analysis.Effect.Domain |
| 18 | +import Analysis.Name |
| 19 | +import Control.Algebra |
| 20 | +import Control.Applicative (Alternative (..)) |
| 21 | +import qualified Data.Foldable as Foldable |
| 22 | +import qualified Data.Set as Set |
| 23 | + |
| 24 | +-- | Names of exceptions thrown in the guest language and recorded by this analysis. |
| 25 | +-- |
| 26 | +-- Not to be confused with exceptions thrown in Haskell itself. |
| 27 | +newtype Exception = Exception { exceptionName :: Name } |
| 28 | + deriving (Eq, Ord, Show) |
| 29 | + |
| 30 | +-- | Sets whose elements are each a variable or an exception. |
| 31 | +data ExcSet = ExcSet { freeVariables :: Set.Set Name, exceptions :: Set.Set Exception } |
| 32 | + deriving (Eq, Ord, Show) |
| 33 | + |
| 34 | +instance Semigroup ExcSet where |
| 35 | + ExcSet v1 e1 <> ExcSet v2 e2 = ExcSet (v1 <> v2) (e1 <> e2) |
| 36 | + |
| 37 | +instance Monoid ExcSet where |
| 38 | + mempty = ExcSet mempty mempty |
| 39 | + |
| 40 | +fromExceptions :: Foldable t => t Exception -> ExcSet |
| 41 | +fromExceptions = ExcSet mempty . Set.fromList . Foldable.toList |
| 42 | + |
| 43 | +var :: Name -> ExcSet |
| 44 | +var v = ExcSet (Set.singleton v) mempty |
| 45 | + |
| 46 | +exc :: Exception -> ExcSet |
| 47 | +exc e = ExcSet mempty (Set.singleton e) |
| 48 | + |
| 49 | + |
| 50 | +newtype ExcC m a = ExcC { runExcC :: m a } |
| 51 | + deriving (Alternative, Applicative, Functor, Monad) |
| 52 | + |
| 53 | +instance (Algebra sig m, Alternative m) => Algebra (Dom ExcSet :+: sig) (ExcC m) where |
| 54 | + alg hdl sig ctx = ExcC $ case sig of |
| 55 | + L dom -> case dom of |
| 56 | + DVar n -> pure $ var n <$ ctx |
| 57 | + DAbs _ b -> runExcC (hdl (b mempty <$ ctx)) |
| 58 | + DApp f a -> pure $ f <> a <$ ctx |
| 59 | + DInt _ -> pure nil |
| 60 | + DUnit -> pure nil |
| 61 | + DBool _ -> pure nil |
| 62 | + DIf c t e -> fmap (mappend c) <$> runExcC (hdl (t <$ ctx) <|> hdl (e <$ ctx)) |
| 63 | + DString _ -> pure nil |
| 64 | + DDie e -> pure $ e <> fromExceptions [Exception n | n <- Set.toList (freeVariables e)] <$ ctx |
| 65 | + where |
| 66 | + nil = (mempty :: ExcSet) <$ ctx |
| 67 | + |
| 68 | + R other -> alg (runExcC . hdl) other ctx |
0 commit comments