summaryrefslogtreecommitdiffhomepage
path: root/Runnable.hs
blob: c51d17349745ca22e5967e37106c004daf49f4f1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
{-# OPTIONS -fglasgow-exts #-}
-----------------------------------------------------------------------------
-- |
-- Module      :  Xmobar.Runnable
-- Copyright   :  (c) Andrea Rossato
-- License     :  BSD-style (see LICENSE)
-- 
-- Maintainer  :  Andrea Rossato <andrea.rossato@unibz.it>
-- Stability   :  unstable
-- Portability :  unportable
--
-- The existential type to store the list of commands to be executed.
-- I must thank Claus Reinke for the help in understanding the mysteries of
-- reading existential types. The Read instance of Runnable must be credited to 
-- him. 
-- 
-- See here:
-- http:\/\/www.haskell.org\/pipermail\/haskell-cafe\/2007-July\/028227.html
--
-----------------------------------------------------------------------------

module Runnable where

import Control.Monad
import Text.Read
import Text.ParserCombinators.ReadPrec
import Config (runnableTypes)
import Commands

data Runnable = forall r . (Exec r, Read r) => Run r

instance Exec Runnable where
     run (Run a) = run a
     rate (Run a) = rate a
     alias (Run a) = alias a

instance Read Runnable where
    readPrec = readRunnable

class ReadAsAnyOf ts ex where
    -- | Reads an existential type as any of hidden types ts
    readAsAnyOf :: ts -> ReadPrec ex

instance ReadAsAnyOf () ex where 
    readAsAnyOf ~() = mzero

instance (Read t, Exec t, ReadAsAnyOf ts Runnable) => ReadAsAnyOf (t,ts) Runnable where 
    readAsAnyOf ~(t,ts) = r t `mplus` readAsAnyOf ts
              where r ty = do { m <- readPrec; return (Run (m `asTypeOf` ty)) }

-- | The 'Prelude.Read' parser for the 'Runnable' existential type. It
-- needs an 'Prelude.undefined' with a type signature containing the
-- list of all possible types hidden within 'Runnable'. See 'Config.runnableTypes'.
-- Each hidden type must have a 'Prelude.Read' instance.
readRunnable :: ReadPrec Runnable
readRunnable = prec 10 $ do
                 Ident "Run" <- lexP
                 parens $ readAsAnyOf runnableTypes