{-# LANGUAGE UndecidableInstances, FlexibleInstances #-}


{-
--------------------------------------------------------------------------------
--
-- Copyright (C) 2008 Martin Sulzmann, Edmund Lam. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.

    * Redistributions in binary form must reproduce the above
      copyright notice, this list of conditions and the following
      disclaimer in the documentation and/or other materials provided
      with the distribution.

    * Neither the name of Isaac Jones nor the names of other
      contributors may be used to endorse or promote products derived
      from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

-}

module Actor.ActorBase where

{-
Provides basic functionality such as

 - fresh variable, tag creation,
   we use tags to check if a variable has been bound to a value

 - generic pattern matcher, needs to be extended for each specific message type
 
 - internal matcher uses tags to keep track of already matched messages
   (we assume multi-set matching!)


-}

import IO
import Monad
import Data.IORef
import Control.Concurrent
import Control.Concurrent.STM


-- tags, a unique tag is attached to each variable and (internal) message

type Tag = IORef ()

newTag :: IO (IORef ())
newTag = newIORef ()

lookupTag :: [Tag] -> Tag -> Bool
lookupTag tags tag = or (map (\t -> t == tag) tags)

-- pattern variables

data VAR a = VAR { variable :: (IORef a), var_tag :: Tag } 
           | DontCare deriving Eq

data L a = Val a  
         | Var (VAR a) deriving Eq


-- dont care vars are convenient and avoid to generate "too many" annonymous variables
dontCareVar :: IO (VAR a)
dontCareVar = return DontCare

newVar :: IO (VAR a)
newVar = do { var <- newIORef undefined
            ; tag <- newIORef ()
            ; return (VAR { variable = var, var_tag = tag})
            }
readVar :: VAR a -> IO a
readVar (VAR {variable = var}) = readIORef var

writeVar :: VAR a -> a -> IO ()
writeVar (VAR {variable = var}) x = writeIORef var x

-- matching of ground messages against patterns
-- we thread through the set of already bound variables,
-- identified via their tags, and already matched messages

-- external matcher, untagged message against pattern messages
class EMatch a where
   match :: [Tag] -> a -> a -> IO (Bool,[Tag])

-- generic instance, remaining instances depend on (external) message
instance (Eq a, EMatch a,Show a) => EMatch (L a) where
  match tags (Val x) (Val y) = match tags x y
  match tags (Val x) (Var DontCare) = return (True, tags)
  match tags (Val x) (Var (y@(VAR {var_tag = tag}))) = 
         if lookupTag tags tag
         then -- y already bound
              do { v <- readVar y
                 -- ; putStr "Debug: match \n"
                 -- ; putStr ("x= " ++ (show x) ++ " \n")
                 -- ; putStr ("v= " ++ (show v) ++ " \n")
                 ; return (x==v,tags) }
         else -- y not bound yet
              do { writeVar y x
                 -- ; putStr "Debug2: match \n"
                 -- ; putStr ("x= " ++ (show x) ++ " \n") 
                 ; return (True,tag:tags) }
  match tags (Var _) _ = error "the impossible has happened"


-- internal matcher, tagged messages against pattern message
class Match a where
   internal_match :: [Tag] -> (InternalMsg a) -> a -> IO (Bool,[Tag])

-- each message carries a tag, so we can identify already matched messages
-- (we assume multi-set matching, ie a message is a resource and can only be matched once)

data InternalMsg a = InternalMsg { message :: a, msg_tag :: Tag } deriving Eq

instance Show a => Show (InternalMsg a) where
    show (InternalMsg {message = msg}) = show msg

-- the only generic instance
instance EMatch a => Match a where
   internal_match tags (InternalMsg {message = msg1, msg_tag = msgtag}) msg2 =
     if lookupTag tags msgtag
     then -- msg already matched, multi-set matching
          return (False,tags)
     else do { (b,tags2) <- match tags msg1 msg2
             ; if b
                then return (b,msgtag:tags2)  -- we remember the tag of the match 
                else return (False,tags) }