{-# OPTIONS -fglasgow-exts    #-}
module Data.Serialize where
import GHC.Exts
import Unsafe.Coerce
import Data.List(isPrefixOf,insertBy,elem)
import Data.Char(isAlpha,isAlphaNum,isSpace,isUpper)
import qualified Data.Map as M
import System.Mem.StableName
import System.IO.Unsafe
import Control.Monad (MonadPlus(..))

import Debug.Trace

debug a b= trace b a

type MFun=  Char -- usafeCoherced to char to store simply the address of the function
type VarName = String
type ShowF= String
type Context =  M.Map Int (MFun,ShowF)

data Error= Error String
data Stat= Stat (Context, String, String)

readContext pattern str= readContext1 "" str where
 readContext1 s str| null str = (s,"")
                   | pattern `isPrefixOf` str = (s,drop n str)
                   | otherwise=   readContext1 (s++[head str]) (tail str)
                    where n= length pattern

hasht x=  (hashStableName . unsafePerformIO . makeStableName) x

-- !  two variables that point to the same address will have identical varname (derived from import System.Mem.StableName)
varName:: a -> String
varName x= "v"++ (show . hasht) x

numVar :: String -> Int
numVar var= read $ tail var