code
stringlengths 5
1.03M
| repo_name
stringlengths 5
90
| path
stringlengths 4
158
| license
stringclasses 15
values | size
int64 5
1.03M
| n_ast_errors
int64 0
53.9k
| ast_max_depth
int64 2
4.17k
| n_whitespaces
int64 0
365k
| n_ast_nodes
int64 3
317k
| n_ast_terminals
int64 1
171k
| n_ast_nonterminals
int64 1
146k
| loc
int64 -1
37.3k
| cycloplexity
int64 -1
1.31k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
module Language.Java.Jdi.EventRequest
( EventRequest
, enable
, disable
, addCountFilter
, createClassPrepareRequest
, createBreakpointRequest
, createStepRequest
) where
import Language.Java.Jdi.Impl
| VictorDenisov/jdi | src/Language/Java/Jdi/EventRequest.hs | gpl-2.0 | 202 | 0 | 4 | 21 | 38 | 26 | 12 | 9 | 0 |
((a, b), c) | hmemcpy/milewski-ctfp-pdf | src/content/1.6/code/haskell/snippet02.hs | gpl-3.0 | 11 | 0 | 6 | 2 | 16 | 9 | 7 | -1 | -1 |
{-# LANGUAGE TemplateHaskell #-}
module Data.PaperStatus where
import Database.Persist.TH
import Prelude
data PaperStatus = SReject | WReject | Neutral | WAccept | SAccept | NotReviewed
deriving (Show, Read, Eq)
derivePersistField "PaperStatus"
| ackao/APRICoT | web/conference-management-system/Data/PaperStatus.hs | gpl-3.0 | 251 | 0 | 6 | 37 | 59 | 35 | 24 | 7 | 0 |
{-# LANGUAGE DeriveDataTypeable #-}
module InnerEar.Exercises.OddEvenAll (oddEvenAllExercise) where
import Reflex
import Reflex.Dom
import Data.Map
import Text.JSON
import Text.JSON.Generic
import Sound.MusicW hiding (Frequency)
import InnerEar.Exercises.MultipleChoice
import InnerEar.Types.ExerciseId
import InnerEar.Types.Exercise
import InnerEar.Types.Score
import InnerEar.Types.MultipleChoiceStore
import InnerEar.Widgets.Config
import InnerEar.Widgets.SpecEval
import InnerEar.Types.Data hiding (Time)
import InnerEar.Types.Frequency
import InnerEar.Widgets.AnswerButton
type Config = Frequency -- represents fundamental frequency for sound generation
configs :: [Config]
configs = [F 100 "100 Hz",F 200 "200 Hz", F 400 "400 Hz", F 800 "800 Hz", F 1600 "1600Hz", F 3200 "3200Hz"]
data Answer = Odd | Even | All deriving (Eq,Ord,Data,Typeable,Show)
instance Buttonable Answer where
makeButton = showAnswerButton
answers = [Odd,Even,All]
renderAnswer :: Map String AudioBuffer -> Config -> (SourceNodeSpec,Maybe Time) -> Maybe Answer -> Synth ()
renderAnswer _ f0 _ (Just a) = buildSynth $ do
let env = asr (Sec 0.01) (Sec 2) (Sec 0.01) (Amp 1)
let masterGain = gain (Db $ -10)
mapM_ (\(f,g) -> oscillator Sine f >> gain g >> env >> masterGain >> destination) oscSpecs
setDeletionTime (Sec 2.5)
where
fs = fmap Hz $ Prelude.filter (< 20000) $ take 200 $ fmap (* (freqAsDouble f0)) $ case a of
Odd -> [1,3 .. ]
Even -> (1:[2,4..])
All -> [1,2 .. ]
gs = fmap Db [0,(-6) .. ]
oscSpecs = zip fs gs
renderAnswer _ f0 _ Nothing = return ()
displayEval :: MonadWidget t m => Dynamic t (Map Answer Score) -> Dynamic t (MultipleChoiceStore Config Answer) -> m ()
displayEval e _ = displayMultipleChoiceEvaluationGraph ("scoreBarWrapperThreeBars","svgBarContainerThreeBars","svgFaintedLineThreeBars","xLabelThreeBars") "Session Performance" "" answers e
generateQ :: Config -> [ExerciseDatum] -> IO ([Answer],Answer)
generateQ _ _ = randomMultipleChoiceQuestion answers
oddEvenAllConfigWidget :: MonadWidget t m => Map String AudioBuffer -> Config -> m (Dynamic t Config, Dynamic t (Maybe (SourceNodeSpec, Maybe Time)), Event t (), Event t ())
oddEvenAllConfigWidget _ c = do
text "Fundamental Frequency: "
dd <- dropdown (freqAsDouble $ head configs) (constDyn $ fromList $ fmap (\x-> (freqAsDouble x, freqAsString x)) configs) (DropdownConfig never (constDyn empty))
let ddVal = _dropdown_value dd -- Dynamic Double
conf <- mapDyn (\x -> F x (show x++" Hz")) ddVal
source <- mapDyn (\x -> Just (Oscillator Sine (Hz x), Just (Sec 2))) ddVal
return (conf, source, never, never)
instructions :: MonadWidget t m => m ()
instructions = el "div" $ do
elClass "div" "instructionsText" $ text "Instructions placeholder"
oddEvenAllExercise :: MonadWidget t m => Exercise t m Config [Answer] Answer (Map Answer Score) (MultipleChoiceStore Config Answer)
oddEvenAllExercise = multipleChoiceExercise
2
answers
instructions
oddEvenAllConfigWidget
renderAnswer
OddEvenAll
(-10)
displayEval
generateQ
(const (0,2))
| JamieBeverley/InnerEar | src/InnerEar/Exercises/OddEvenAll.hs | gpl-3.0 | 3,092 | 0 | 15 | 509 | 1,134 | 595 | 539 | 65 | 3 |
{-# LANGUAGE OverloadedStrings #-}
module Lamdu.Infer.Error
( Error(..)
) where
import Lamdu.Expr.Constraints (Constraints)
import qualified Lamdu.Expr.Type as T
import qualified Lamdu.Expr.Val as V
import Text.PrettyPrint ((<+>), Doc)
import Text.PrettyPrint.HughesPJClass (Pretty(..))
data Error
= DuplicateField T.Tag T.Product
| DuplicateAlt T.Tag T.Sum
| MissingGlobal V.GlobalId
| MissingNominal T.NominalId
| OccursCheckFail Doc Doc
| TypesDoNotUnity Doc Doc
| UnboundVariable V.Var
| SkolemsUnified Doc Doc
| SkolemNotPolymorphic Doc Doc
| UnexpectedSkolemConstraint Constraints
| SkolemEscapesScope
instance Pretty Error where
pPrint (DuplicateField t r) =
"Field" <+> pPrint t <+> "forbidden in record" <+> pPrint r
pPrint (DuplicateAlt t r) =
"Alternative" <+> pPrint t <+> "forbidden in sum" <+> pPrint r
pPrint (MissingGlobal g) =
"Missing global:" <+> pPrint g
pPrint (MissingNominal i) =
"Missing nominal:" <+> pPrint i
pPrint (OccursCheckFail v t) =
"Occurs check fails:" <+> v <+> "vs." <+> t
pPrint (UnboundVariable v) =
"Unbound variable:" <+> pPrint v
pPrint (TypesDoNotUnity x y) =
"Types do not unify" <+> x <+> "vs." <+> y
pPrint (SkolemsUnified x y) =
"Two skolems unified" <+> x <+> "vs." <+> y
pPrint (SkolemNotPolymorphic x y) =
"Skolem" <+> x <+> "unified with non-polymorphic type" <+> y
pPrint (UnexpectedSkolemConstraint constraints) =
"Unexpected constraint on skolem[s] " <+> pPrint constraints
pPrint SkolemEscapesScope = "Skolem escapes scope"
| da-x/Algorithm-W-Step-By-Step | Lamdu/Infer/Error.hs | gpl-3.0 | 1,689 | 0 | 9 | 419 | 439 | 236 | 203 | 42 | 0 |
-- |
module Async where
import Control.Concurrent
-- Represent an asynchronous action that has been started.
data Async a
async :: IO a -> IO (Async a)
async = undefined
wait :: Async a -> IO a
wait = undefined
| capitanbatata/marlows-parconc-exercises | parconc-ch08/src/Async.hs | gpl-3.0 | 226 | 0 | 8 | 55 | 61 | 34 | 27 | -1 | -1 |
module Main where
import Test.QuickCheck
import Mangling
import Data.Either (lefts, rights)
import Data.List (inits)
allNumerics :: [Numeric]
allNumerics = [Intval x | x <- [0..35]] ++
[ Variable x | x <- [0..7]] ++
[ MaxLength
, MaxLengthMinus1
, MaxLengthPlus1
, CurrentWordLength
, InitialLastCharPos
, PosFoundChar
, Infinite ]
allCharacterClassTypes :: [CharacterClassType]
allCharacterClassTypes = [ MatchVowel
, MatchConsonant
, MatchWhitespace
, MatchPunctuation
, MatchSymbol
, MatchLower
, MatchUpper
, MatchDigit
, MatchLetter
, MatchAlphaNum
, MatchAny ]
allMChar :: [CharacterClassType]
allMChar = [MatchChar x | x <- [' '..'Z']]
allCharacterClass :: [CharacterClass]
allCharacterClass = [CharacterClass ctype b | ctype <- allCharacterClassTypes, b <- [True, False]] ++ [CharacterClass ctype False | ctype <- allMChar]
allStrings :: [String]
allStrings = tail ((take 4 . inits . repeat) "abcABC \\\"'" >>= sequence)
allRules :: [Rule]
allRules = [ RejectUnlessCaseSensitive -- -c
, RejectUnless8Bits -- -8
, RejectUnlessSplit -- -s
, RejectUnlessWordPairs -- -p
, LowerCase
, UpperCase
, Capitalize
, ToggleAllCase
, Reverse
, Duplicate
, Reflect
, RotateLeft
, RotateRight
, Pluralize
, PastTense
, Genitive
, ShiftCase
, LowerVowels
, DeleteFirst
, ShiftRightKeyboard
, ShiftLeftKeyboard
, RejectUnlessChanged
, Memorize
, DeleteLast ]
++ concatMap wNum
[ ToggleCase
, Delete
, RejectUnlessLengthLess
, RejectUnlessLengthMore
, Truncate
]
++ concatMap wChar
[ Append
, Prepend
]
++ [Extract a b | a <- allNumerics, b <- allNumerics]
++ [Insert a b | a <- allNumerics, b <- [' '..'Z'] ]
++ [Overstrike a b | a <- allNumerics, b <- [' '..'Z'] ]
++ [ExtractInsert a b c | a <- allNumerics, b <- allNumerics, c <- allNumerics]
++ [Update a b c | a <- allNumerics, b <- allNumerics, c <- allNumerics]
++ concatMap wCClass
[ RejectUnlessFirstChar
, RejectUnlessLastChar
, PurgeAll
, RejectIfContains
, RejectUnlessContains
]
++ [InsertString n s | n <- allNumerics, s <- allStrings]
++ [RejectUnlessCharInPos n c | n <- allNumerics, c <- allCharacterClass]
++ [RejectUnlessNInstances n c | n <- allNumerics, c <- allCharacterClass]
++ [ReplaceAll cc c | cc <- allCharacterClass, c <- [' '..'Z']]
where
wNum f = [f n | n <- allNumerics]
wChar f = [f n | n <- [' '..'Z']]
wCClass f = [f n | n <- allCharacterClass]
instance Arbitrary Rule where
arbitrary = elements allRules
testJTR :: [Rule] -> Bool
testJTR r = let
rc = cleanup r
str = showRule JTR rc
rev = case str of
Right "" -> parseSingleRule JTR ":"
Right s -> parseSingleRule JTR s
Left e -> [Left e]
l' = lefts rev
r' = rights rev
in if (null l') && (length r' == 1)
then head r' == rc
else False
main :: IO ()
main = verboseCheck testJTR
| bartavelle/manglingrules | test/tests.hs | gpl-3.0 | 3,764 | 0 | 18 | 1,506 | 989 | 538 | 451 | 102 | 4 |
{-# LANGUAGE OverloadedStrings #-}
module Pirandello.Config ( ParseException, Config (..), Host, Port
, defaultPort, defaultConfig, decodeConfigFile, defaultConfigFile )
where
import Control.Applicative ((<$>), (<*>))
import Control.Monad (mzero)
import Control.Monad.Trans.Except (ExceptT (ExceptT))
import Data.Text (Text)
import Data.Word (Word16)
import Data.Yaml (FromJSON (parseJSON), ParseException, Value (Object), (.:?), (.!=), decodeFileEither)
import Pirandello.Events (RemoteId)
import System.Environment.XDG.BaseDir (getUserConfigFile)
import UnexceptionalIO (UIO, unsafeFromIO)
type Host = Text
type Port = Word16
data Config = Config { krugerServer ∷ Maybe Host
, krugerName ∷ Maybe RemoteId
, port ∷ Port }
deriving (Show, Eq)
instance FromJSON Config where
parseJSON (Object v) = Config <$> v .:? "kruger-server"
<*> v .:? "kruger-name"
<*> v .:? "port" .!= defaultPort
parseJSON _ = mzero
defaultPort ∷ Word16
defaultPort = 30716
defaultConfig ∷ Config
defaultConfig = Config Nothing Nothing defaultPort
decodeConfigFile ∷ FilePath → ExceptT ParseException UIO Config
decodeConfigFile = ExceptT . unsafeFromIO . decodeFileEither
defaultConfigFile ∷ UIO FilePath
defaultConfigFile = unsafeFromIO $ getUserConfigFile "pirandello" "config.yml"
| rimmington/pirandello | src/Pirandello/Config.hs | gpl-3.0 | 1,481 | 0 | 12 | 360 | 362 | 216 | 146 | -1 | -1 |
{-# LANGUAGE UnicodeSyntax, NoImplicitPrelude #-}
{-# LANGUAGE DeriveGeneric #-}
module Layout.Mod
( Mod(Mod)
, isEmptyMod
, applyMod
, applyInverseMod
) where
import BasePrelude
import Prelude.Unicode
import Data.Monoid.Unicode ((∅), (⊕))
import Data.Aeson
import Layout.Pos (Pos)
import Permutation (Permutation, isEmptyPermutation, permutate, inverse)
data Mod = Mod
{ name ∷ String
, permutation ∷ Permutation Pos
} deriving (Eq, Ord, Show, Read, Generic)
isEmptyMod ∷ Mod → Bool
isEmptyMod (Mod "" p) = isEmptyPermutation p
isEmptyMod _ = False
instance Semigroup Mod where
Mod a1 a2 <> Mod b1 b2 = Mod (a1 ⊕ b1) (a2 ⊕ b2)
instance Monoid Mod where
mempty = Mod (∅) (∅)
mappend = (<>)
instance ToJSON Mod
instance FromJSON Mod
applyMod ∷ Mod → Pos → Pos
applyMod = permutate ∘ permutation
applyInverseMod ∷ Mod → Pos → Pos
applyInverseMod = permutate ∘ inverse ∘ permutation
| 39aldo39/klfc | src/Layout/Mod.hs | gpl-3.0 | 971 | 0 | 9 | 192 | 306 | 173 | 133 | 34 | 1 |
{-# LANGUAGE TemplateHaskell, ScopedTypeVariables, TypeSynonymInstances, FlexibleInstances, GeneralizedNewtypeDeriving, MultiParamTypeClasses #-}
{-# OPTIONS -Wall #-}
-- | Canonical vertex ordering for faces of a triangulation
module Triangulation.CanonOrdered(
module Triangulation,
CanonOrdered(..),COIEdge,COITriangle,
CanonicallyOrderable(..),isCanonicallyOrdered,tCOIEdges,tCOITriangles,
polyprop_CanonicallyOrderable
) where
import Tetrahedron
import Control.Applicative
import Control.Monad.Reader
import Data.Function
import Equivalence
import Prelude hiding(catch,lookup)
import Test.QuickCheck
import PrettyUtil
import Triangulation.FacetGluing
import QuickCheckUtil
import Data.Proxy
import Triangulation
import ShortShow
newtype CanonOrdered a = UnsafeCanonOrdered { unCanonOrdered :: a }
deriving(Show,Eq,Ord,TriangulationDSnakeItem,Pretty,ShortShow)
type COITriangle = CanonOrdered OITriangle
type COIEdge = CanonOrdered OIEdge
class OrderableFace t ot => CanonicallyOrderable t ot where
orderCanonically :: Triangulation -> t -> CanonOrdered ot
allCanonicallyOrdered :: Triangulation -> [CanonOrdered ot]
isCanonicallyOrdered
:: (Eq ot, CanonicallyOrderable t ot) => Triangulation -> ot -> Bool
isCanonicallyOrdered tr x =
x == (unCanonOrdered . orderCanonically tr . forgetVertexOrder) x
tCOITriangles :: Triangulation -> [CanonOrdered OITriangle]
tCOITriangles tr = UnsafeCanonOrdered <$> do
tri <- tITriangles tr
case lookupGluingOfITriangle tr tri of
Nothing -> [ toOrderedFace tri ]
Just otri
| tri < forgetVertexOrder otri -> [ toOrderedFace tri, otri ]
| otherwise -> []
-- | = 'tCOITriangles'
instance CanonicallyOrderable ITriangle OITriangle where
allCanonicallyOrdered = tCOITriangles
orderCanonically tr tri = UnsafeCanonOrdered $
case lookupGluingOfITriangle tr tri of
Nothing -> toOrderedFace tri
Just otri
| tri < forgetVertexOrder otri -> toOrderedFace tri
| otherwise -> snd (flipGluing (tri,otri))
tCOIEdges
:: Triangulation -> [COIEdge]
tCOIEdges tr = UnsafeCanonOrdered <$> do
cl <- eqvClasses (oEdgeEqv tr)
guard (isCanonicallyOrderedClass cl)
ec_elementList cl
instance CanonicallyOrderable IEdge OIEdge where
allCanonicallyOrdered = tCOIEdges
orderCanonically tr e = UnsafeCanonOrdered $
let
oe = toOrderedFace e
in
oe *. (getVertexOrder (eqvRep (oEdgeEqv tr) oe))
--polyprop_CanonicallyOrderable :: CanonicallyOrderable t ot => Proxy ot -> Triangulation -> Property
polyprop_CanonicallyOrderable
:: (Eq ot, Show ot, CanonicallyOrderable t ot) =>
Proxy ot -> Triangulation -> Property
polyprop_CanonicallyOrderable (_ :: Proxy ot) tr =
forAllElements (allCanonicallyOrdered tr :: [CanonOrdered ot])
(isCanonicallyOrdered tr . unCanonOrdered)
-- .&.
--
-- forAllElements
instance IsSubface a b => IsSubface (CanonOrdered a) b where
isSubface = isSubface . unCanonOrdered
| DanielSchuessler/hstri | Triangulation/CanonOrdered.hs | gpl-3.0 | 3,138 | 0 | 15 | 658 | 731 | 382 | 349 | 67 | 2 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-matches #-}
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- |
-- Module : Network.AWS.IAM.UpdateUser
-- Copyright : (c) 2013-2015 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Updates the name and\/or the path of the specified user.
--
-- You should understand the implications of changing a user\'s path or
-- name. For more information, see
-- <http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_WorkingWithGroupsAndUsers.html Renaming Users and Groups>
-- in the /IAM User Guide/.
--
-- To change a user name the requester must have appropriate permissions on
-- both the source object and the target object. For example, to change Bob
-- to Robert, the entity making the request must have permission on Bob and
-- Robert, or must have permission on all (*). For more information about
-- permissions, see
-- <http://docs.aws.amazon.com/IAM/latest/UserGuide/PermissionsAndPolicies.html Permissions and Policies>.
--
-- /See:/ <http://docs.aws.amazon.com/IAM/latest/APIReference/API_UpdateUser.html AWS API Reference> for UpdateUser.
module Network.AWS.IAM.UpdateUser
(
-- * Creating a Request
updateUser
, UpdateUser
-- * Request Lenses
, uuNewUserName
, uuNewPath
, uuUserName
-- * Destructuring the Response
, updateUserResponse
, UpdateUserResponse
) where
import Network.AWS.IAM.Types
import Network.AWS.IAM.Types.Product
import Network.AWS.Prelude
import Network.AWS.Request
import Network.AWS.Response
-- | /See:/ 'updateUser' smart constructor.
data UpdateUser = UpdateUser'
{ _uuNewUserName :: !(Maybe Text)
, _uuNewPath :: !(Maybe Text)
, _uuUserName :: !Text
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'UpdateUser' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'uuNewUserName'
--
-- * 'uuNewPath'
--
-- * 'uuUserName'
updateUser
:: Text -- ^ 'uuUserName'
-> UpdateUser
updateUser pUserName_ =
UpdateUser'
{ _uuNewUserName = Nothing
, _uuNewPath = Nothing
, _uuUserName = pUserName_
}
-- | New name for the user. Include this parameter only if you\'re changing
-- the user\'s name.
uuNewUserName :: Lens' UpdateUser (Maybe Text)
uuNewUserName = lens _uuNewUserName (\ s a -> s{_uuNewUserName = a});
-- | New path for the user. Include this parameter only if you\'re changing
-- the user\'s path.
uuNewPath :: Lens' UpdateUser (Maybe Text)
uuNewPath = lens _uuNewPath (\ s a -> s{_uuNewPath = a});
-- | Name of the user to update. If you\'re changing the name of the user,
-- this is the original user name.
uuUserName :: Lens' UpdateUser Text
uuUserName = lens _uuUserName (\ s a -> s{_uuUserName = a});
instance AWSRequest UpdateUser where
type Rs UpdateUser = UpdateUserResponse
request = postQuery iAM
response = receiveNull UpdateUserResponse'
instance ToHeaders UpdateUser where
toHeaders = const mempty
instance ToPath UpdateUser where
toPath = const "/"
instance ToQuery UpdateUser where
toQuery UpdateUser'{..}
= mconcat
["Action" =: ("UpdateUser" :: ByteString),
"Version" =: ("2010-05-08" :: ByteString),
"NewUserName" =: _uuNewUserName,
"NewPath" =: _uuNewPath, "UserName" =: _uuUserName]
-- | /See:/ 'updateUserResponse' smart constructor.
data UpdateUserResponse =
UpdateUserResponse'
deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'UpdateUserResponse' with the minimum fields required to make a request.
--
updateUserResponse
:: UpdateUserResponse
updateUserResponse = UpdateUserResponse'
| olorin/amazonka | amazonka-iam/gen/Network/AWS/IAM/UpdateUser.hs | mpl-2.0 | 4,242 | 0 | 11 | 861 | 535 | 327 | 208 | 68 | 1 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-matches #-}
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- |
-- Module : Network.AWS.IAM.PutUserPolicy
-- Copyright : (c) 2013-2015 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Adds (or updates) an inline policy document that is embedded in the
-- specified user.
--
-- A user can also have a managed policy attached to it. To attach a
-- managed policy to a user, use AttachUserPolicy. To create a new managed
-- policy, use CreatePolicy. For information about policies, refer to
-- <http://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-vs-inline.html Managed Policies and Inline Policies>
-- in the /Using IAM/ guide.
--
-- For information about limits on the number of inline policies that you
-- can embed in a user, see
-- <http://docs.aws.amazon.com/IAM/latest/UserGuide/LimitationsOnEntities.html Limitations on IAM Entities>
-- in the /Using IAM/ guide.
--
-- Because policy documents can be large, you should use POST rather than
-- GET when calling 'PutUserPolicy'. For general information about using
-- the Query API with IAM, go to
-- <http://docs.aws.amazon.com/IAM/latest/UserGuide/IAM_UsingQueryAPI.html Making Query Requests>
-- in the /Using IAM/ guide.
--
-- /See:/ <http://docs.aws.amazon.com/IAM/latest/APIReference/API_PutUserPolicy.html AWS API Reference> for PutUserPolicy.
module Network.AWS.IAM.PutUserPolicy
(
-- * Creating a Request
putUserPolicy
, PutUserPolicy
-- * Request Lenses
, pupUserName
, pupPolicyName
, pupPolicyDocument
-- * Destructuring the Response
, putUserPolicyResponse
, PutUserPolicyResponse
) where
import Network.AWS.IAM.Types
import Network.AWS.IAM.Types.Product
import Network.AWS.Prelude
import Network.AWS.Request
import Network.AWS.Response
-- | /See:/ 'putUserPolicy' smart constructor.
data PutUserPolicy = PutUserPolicy'
{ _pupUserName :: !Text
, _pupPolicyName :: !Text
, _pupPolicyDocument :: !Text
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'PutUserPolicy' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'pupUserName'
--
-- * 'pupPolicyName'
--
-- * 'pupPolicyDocument'
putUserPolicy
:: Text -- ^ 'pupUserName'
-> Text -- ^ 'pupPolicyName'
-> Text -- ^ 'pupPolicyDocument'
-> PutUserPolicy
putUserPolicy pUserName_ pPolicyName_ pPolicyDocument_ =
PutUserPolicy'
{ _pupUserName = pUserName_
, _pupPolicyName = pPolicyName_
, _pupPolicyDocument = pPolicyDocument_
}
-- | The name of the user to associate the policy with.
pupUserName :: Lens' PutUserPolicy Text
pupUserName = lens _pupUserName (\ s a -> s{_pupUserName = a});
-- | The name of the policy document.
pupPolicyName :: Lens' PutUserPolicy Text
pupPolicyName = lens _pupPolicyName (\ s a -> s{_pupPolicyName = a});
-- | The policy document.
pupPolicyDocument :: Lens' PutUserPolicy Text
pupPolicyDocument = lens _pupPolicyDocument (\ s a -> s{_pupPolicyDocument = a});
instance AWSRequest PutUserPolicy where
type Rs PutUserPolicy = PutUserPolicyResponse
request = postQuery iAM
response = receiveNull PutUserPolicyResponse'
instance ToHeaders PutUserPolicy where
toHeaders = const mempty
instance ToPath PutUserPolicy where
toPath = const "/"
instance ToQuery PutUserPolicy where
toQuery PutUserPolicy'{..}
= mconcat
["Action" =: ("PutUserPolicy" :: ByteString),
"Version" =: ("2010-05-08" :: ByteString),
"UserName" =: _pupUserName,
"PolicyName" =: _pupPolicyName,
"PolicyDocument" =: _pupPolicyDocument]
-- | /See:/ 'putUserPolicyResponse' smart constructor.
data PutUserPolicyResponse =
PutUserPolicyResponse'
deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'PutUserPolicyResponse' with the minimum fields required to make a request.
--
putUserPolicyResponse
:: PutUserPolicyResponse
putUserPolicyResponse = PutUserPolicyResponse'
| fmapfmapfmap/amazonka | amazonka-iam/gen/Network/AWS/IAM/PutUserPolicy.hs | mpl-2.0 | 4,618 | 0 | 9 | 900 | 528 | 326 | 202 | 71 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- Module : Network.AWS.CloudWatchLogs.TestMetricFilter
-- Copyright : (c) 2013-2014 Brendan Hay <brendan.g.hay@gmail.com>
-- License : This Source Code Form is subject to the terms of
-- the Mozilla Public License, v. 2.0.
-- A copy of the MPL can be found in the LICENSE file or
-- you can obtain it at http://mozilla.org/MPL/2.0/.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : experimental
-- Portability : non-portable (GHC extensions)
--
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- | Tests the filter pattern of a metric filter against a sample of log event
-- messages. You can use this operation to validate the correctness of a metric
-- filter pattern.
--
-- <http://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_TestMetricFilter.html>
module Network.AWS.CloudWatchLogs.TestMetricFilter
(
-- * Request
TestMetricFilter
-- ** Request constructor
, testMetricFilter
-- ** Request lenses
, tmfFilterPattern
, tmfLogEventMessages
-- * Response
, TestMetricFilterResponse
-- ** Response constructor
, testMetricFilterResponse
-- ** Response lenses
, tmfrMatches
) where
import Network.AWS.Prelude
import Network.AWS.Request.JSON
import Network.AWS.CloudWatchLogs.Types
import qualified GHC.Exts
data TestMetricFilter = TestMetricFilter
{ _tmfFilterPattern :: Text
, _tmfLogEventMessages :: List1 "logEventMessages" Text
} deriving (Eq, Ord, Read, Show)
-- | 'TestMetricFilter' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'tmfFilterPattern' @::@ 'Text'
--
-- * 'tmfLogEventMessages' @::@ 'NonEmpty' 'Text'
--
testMetricFilter :: Text -- ^ 'tmfFilterPattern'
-> NonEmpty Text -- ^ 'tmfLogEventMessages'
-> TestMetricFilter
testMetricFilter p1 p2 = TestMetricFilter
{ _tmfFilterPattern = p1
, _tmfLogEventMessages = withIso _List1 (const id) p2
}
tmfFilterPattern :: Lens' TestMetricFilter Text
tmfFilterPattern = lens _tmfFilterPattern (\s a -> s { _tmfFilterPattern = a })
tmfLogEventMessages :: Lens' TestMetricFilter (NonEmpty Text)
tmfLogEventMessages =
lens _tmfLogEventMessages (\s a -> s { _tmfLogEventMessages = a })
. _List1
newtype TestMetricFilterResponse = TestMetricFilterResponse
{ _tmfrMatches :: List "matches" MetricFilterMatchRecord
} deriving (Eq, Read, Show, Monoid, Semigroup)
instance GHC.Exts.IsList TestMetricFilterResponse where
type Item TestMetricFilterResponse = MetricFilterMatchRecord
fromList = TestMetricFilterResponse . GHC.Exts.fromList
toList = GHC.Exts.toList . _tmfrMatches
-- | 'TestMetricFilterResponse' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'tmfrMatches' @::@ ['MetricFilterMatchRecord']
--
testMetricFilterResponse :: TestMetricFilterResponse
testMetricFilterResponse = TestMetricFilterResponse
{ _tmfrMatches = mempty
}
tmfrMatches :: Lens' TestMetricFilterResponse [MetricFilterMatchRecord]
tmfrMatches = lens _tmfrMatches (\s a -> s { _tmfrMatches = a }) . _List
instance ToPath TestMetricFilter where
toPath = const "/"
instance ToQuery TestMetricFilter where
toQuery = const mempty
instance ToHeaders TestMetricFilter
instance ToJSON TestMetricFilter where
toJSON TestMetricFilter{..} = object
[ "filterPattern" .= _tmfFilterPattern
, "logEventMessages" .= _tmfLogEventMessages
]
instance AWSRequest TestMetricFilter where
type Sv TestMetricFilter = CloudWatchLogs
type Rs TestMetricFilter = TestMetricFilterResponse
request = post "TestMetricFilter"
response = jsonResponse
instance FromJSON TestMetricFilterResponse where
parseJSON = withObject "TestMetricFilterResponse" $ \o -> TestMetricFilterResponse
<$> o .:? "matches" .!= mempty
| dysinger/amazonka | amazonka-cloudwatch-logs/gen/Network/AWS/CloudWatchLogs/TestMetricFilter.hs | mpl-2.0 | 4,403 | 0 | 10 | 905 | 591 | 350 | 241 | 68 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.YouTube.Sponsors.List
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Lists sponsors for a channel.
--
-- /See:/ <https://developers.google.com/youtube/v3 YouTube Data API Reference> for @youtube.sponsors.list@.
module Network.Google.Resource.YouTube.Sponsors.List
(
-- * REST Resource
SponsorsListResource
-- * Creating a Request
, sponsorsList
, SponsorsList
-- * Request Lenses
, sPart
, sFilter
, sPageToken
, sMaxResults
) where
import Network.Google.Prelude
import Network.Google.YouTube.Types
-- | A resource alias for @youtube.sponsors.list@ method which the
-- 'SponsorsList' request conforms to.
type SponsorsListResource =
"youtube" :>
"v3" :>
"sponsors" :>
QueryParam "part" Text :>
QueryParam "filter" SponsorsListFilter :>
QueryParam "pageToken" Text :>
QueryParam "maxResults" (Textual Word32) :>
QueryParam "alt" AltJSON :>
Get '[JSON] SponsorListResponse
-- | Lists sponsors for a channel.
--
-- /See:/ 'sponsorsList' smart constructor.
data SponsorsList =
SponsorsList'
{ _sPart :: !Text
, _sFilter :: !SponsorsListFilter
, _sPageToken :: !(Maybe Text)
, _sMaxResults :: !(Textual Word32)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'SponsorsList' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'sPart'
--
-- * 'sFilter'
--
-- * 'sPageToken'
--
-- * 'sMaxResults'
sponsorsList
:: Text -- ^ 'sPart'
-> SponsorsList
sponsorsList pSPart_ =
SponsorsList'
{ _sPart = pSPart_
, _sFilter = SLFNewest
, _sPageToken = Nothing
, _sMaxResults = 5
}
-- | The part parameter specifies the sponsor resource parts that the API
-- response will include. Supported values are id and snippet.
sPart :: Lens' SponsorsList Text
sPart = lens _sPart (\ s a -> s{_sPart = a})
-- | The filter parameter specifies which channel sponsors to return.
sFilter :: Lens' SponsorsList SponsorsListFilter
sFilter = lens _sFilter (\ s a -> s{_sFilter = a})
-- | The pageToken parameter identifies a specific page in the result set
-- that should be returned. In an API response, the nextPageToken and
-- prevPageToken properties identify other pages that could be retrieved.
sPageToken :: Lens' SponsorsList (Maybe Text)
sPageToken
= lens _sPageToken (\ s a -> s{_sPageToken = a})
-- | The maxResults parameter specifies the maximum number of items that
-- should be returned in the result set.
sMaxResults :: Lens' SponsorsList Word32
sMaxResults
= lens _sMaxResults (\ s a -> s{_sMaxResults = a}) .
_Coerce
instance GoogleRequest SponsorsList where
type Rs SponsorsList = SponsorListResponse
type Scopes SponsorsList =
'["https://www.googleapis.com/auth/youtube",
"https://www.googleapis.com/auth/youtube.force-ssl",
"https://www.googleapis.com/auth/youtube.readonly"]
requestClient SponsorsList'{..}
= go (Just _sPart) (Just _sFilter) _sPageToken
(Just _sMaxResults)
(Just AltJSON)
youTubeService
where go
= buildClient (Proxy :: Proxy SponsorsListResource)
mempty
| brendanhay/gogol | gogol-youtube/gen/Network/Google/Resource/YouTube/Sponsors/List.hs | mpl-2.0 | 4,109 | 0 | 15 | 996 | 562 | 332 | 230 | 82 | 1 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-matches #-}
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- |
-- Module : Network.AWS.IAM.ListPolicies
-- Copyright : (c) 2013-2015 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Lists all the managed policies that are available to your account,
-- including your own customer managed policies and all AWS managed
-- policies.
--
-- You can filter the list of policies that is returned using the optional
-- 'OnlyAttached', 'Scope', and 'PathPrefix' parameters. For example, to
-- list only the customer managed policies in your AWS account, set 'Scope'
-- to 'Local'. To list only AWS managed policies, set 'Scope' to 'AWS'.
--
-- You can paginate the results using the 'MaxItems' and 'Marker'
-- parameters.
--
-- For more information about managed policies, refer to
-- <http://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-vs-inline.html Managed Policies and Inline Policies>
-- in the /Using IAM/ guide.
--
-- /See:/ <http://docs.aws.amazon.com/IAM/latest/APIReference/API_ListPolicies.html AWS API Reference> for ListPolicies.
--
-- This operation returns paginated results.
module Network.AWS.IAM.ListPolicies
(
-- * Creating a Request
listPolicies
, ListPolicies
-- * Request Lenses
, lpPathPrefix
, lpOnlyAttached
, lpMarker
, lpScope
, lpMaxItems
-- * Destructuring the Response
, listPoliciesResponse
, ListPoliciesResponse
-- * Response Lenses
, lprsMarker
, lprsIsTruncated
, lprsPolicies
, lprsResponseStatus
) where
import Network.AWS.IAM.Types
import Network.AWS.IAM.Types.Product
import Network.AWS.Pager
import Network.AWS.Prelude
import Network.AWS.Request
import Network.AWS.Response
-- | /See:/ 'listPolicies' smart constructor.
data ListPolicies = ListPolicies'
{ _lpPathPrefix :: !(Maybe Text)
, _lpOnlyAttached :: !(Maybe Bool)
, _lpMarker :: !(Maybe Text)
, _lpScope :: !(Maybe PolicyScopeType)
, _lpMaxItems :: !(Maybe Nat)
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'ListPolicies' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'lpPathPrefix'
--
-- * 'lpOnlyAttached'
--
-- * 'lpMarker'
--
-- * 'lpScope'
--
-- * 'lpMaxItems'
listPolicies
:: ListPolicies
listPolicies =
ListPolicies'
{ _lpPathPrefix = Nothing
, _lpOnlyAttached = Nothing
, _lpMarker = Nothing
, _lpScope = Nothing
, _lpMaxItems = Nothing
}
-- | The path prefix for filtering the results. This parameter is optional.
-- If it is not included, it defaults to a slash (\/), listing all
-- policies.
lpPathPrefix :: Lens' ListPolicies (Maybe Text)
lpPathPrefix = lens _lpPathPrefix (\ s a -> s{_lpPathPrefix = a});
-- | A flag to filter the results to only the attached policies.
--
-- When 'OnlyAttached' is 'true', the returned list contains only the
-- policies that are attached to a user, group, or role. When
-- 'OnlyAttached' is 'false', or when the parameter is not included, all
-- policies are returned.
lpOnlyAttached :: Lens' ListPolicies (Maybe Bool)
lpOnlyAttached = lens _lpOnlyAttached (\ s a -> s{_lpOnlyAttached = a});
-- | Use this parameter only when paginating results and only after you have
-- received a response where the results are truncated. Set it to the value
-- of the 'Marker' element in the response you just received.
lpMarker :: Lens' ListPolicies (Maybe Text)
lpMarker = lens _lpMarker (\ s a -> s{_lpMarker = a});
-- | The scope to use for filtering the results.
--
-- To list only AWS managed policies, set 'Scope' to 'AWS'. To list only
-- the customer managed policies in your AWS account, set 'Scope' to
-- 'Local'.
--
-- This parameter is optional. If it is not included, or if it is set to
-- 'All', all policies are returned.
lpScope :: Lens' ListPolicies (Maybe PolicyScopeType)
lpScope = lens _lpScope (\ s a -> s{_lpScope = a});
-- | Use this only when paginating results to indicate the maximum number of
-- items you want in the response. If there are additional items beyond the
-- maximum you specify, the 'IsTruncated' response element is 'true'.
--
-- This parameter is optional. If you do not include it, it defaults to
-- 100.
lpMaxItems :: Lens' ListPolicies (Maybe Natural)
lpMaxItems = lens _lpMaxItems (\ s a -> s{_lpMaxItems = a}) . mapping _Nat;
instance AWSPager ListPolicies where
page rq rs
| stop (rs ^. lprsMarker) = Nothing
| stop (rs ^. lprsPolicies) = Nothing
| otherwise =
Just $ rq & lpMarker .~ rs ^. lprsMarker
instance AWSRequest ListPolicies where
type Rs ListPolicies = ListPoliciesResponse
request = postQuery iAM
response
= receiveXMLWrapper "ListPoliciesResult"
(\ s h x ->
ListPoliciesResponse' <$>
(x .@? "Marker") <*> (x .@? "IsTruncated") <*>
(x .@? "Policies" .!@ mempty >>=
may (parseXMLList "member"))
<*> (pure (fromEnum s)))
instance ToHeaders ListPolicies where
toHeaders = const mempty
instance ToPath ListPolicies where
toPath = const "/"
instance ToQuery ListPolicies where
toQuery ListPolicies'{..}
= mconcat
["Action" =: ("ListPolicies" :: ByteString),
"Version" =: ("2010-05-08" :: ByteString),
"PathPrefix" =: _lpPathPrefix,
"OnlyAttached" =: _lpOnlyAttached,
"Marker" =: _lpMarker, "Scope" =: _lpScope,
"MaxItems" =: _lpMaxItems]
-- | Contains the response to a successful ListPolicies request.
--
-- /See:/ 'listPoliciesResponse' smart constructor.
data ListPoliciesResponse = ListPoliciesResponse'
{ _lprsMarker :: !(Maybe Text)
, _lprsIsTruncated :: !(Maybe Bool)
, _lprsPolicies :: !(Maybe [Policy])
, _lprsResponseStatus :: !Int
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'ListPoliciesResponse' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'lprsMarker'
--
-- * 'lprsIsTruncated'
--
-- * 'lprsPolicies'
--
-- * 'lprsResponseStatus'
listPoliciesResponse
:: Int -- ^ 'lprsResponseStatus'
-> ListPoliciesResponse
listPoliciesResponse pResponseStatus_ =
ListPoliciesResponse'
{ _lprsMarker = Nothing
, _lprsIsTruncated = Nothing
, _lprsPolicies = Nothing
, _lprsResponseStatus = pResponseStatus_
}
-- | When 'IsTruncated' is 'true', this element is present and contains the
-- value to use for the 'Marker' parameter in a subsequent pagination
-- request.
lprsMarker :: Lens' ListPoliciesResponse (Maybe Text)
lprsMarker = lens _lprsMarker (\ s a -> s{_lprsMarker = a});
-- | A flag that indicates whether there are more items to return. If your
-- results were truncated, you can make a subsequent pagination request
-- using the 'Marker' request parameter to retrieve more items.
lprsIsTruncated :: Lens' ListPoliciesResponse (Maybe Bool)
lprsIsTruncated = lens _lprsIsTruncated (\ s a -> s{_lprsIsTruncated = a});
-- | A list of policies.
lprsPolicies :: Lens' ListPoliciesResponse [Policy]
lprsPolicies = lens _lprsPolicies (\ s a -> s{_lprsPolicies = a}) . _Default . _Coerce;
-- | The response status code.
lprsResponseStatus :: Lens' ListPoliciesResponse Int
lprsResponseStatus = lens _lprsResponseStatus (\ s a -> s{_lprsResponseStatus = a});
| fmapfmapfmap/amazonka | amazonka-iam/gen/Network/AWS/IAM/ListPolicies.hs | mpl-2.0 | 8,098 | 0 | 15 | 1,757 | 1,182 | 704 | 478 | 126 | 1 |
-- Copyright 2017 Lukas Epple
--
-- This file is part of likely music.
--
-- likely music is free software: you can redistribute it and/or modify
-- it under the terms of the GNU Affero General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- likely music is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU Affero General Public License for more details.
--
-- You should have received a copy of the GNU Affero General Public License
-- along with likely music. If not, see <http://www.gnu.org/licenses/>.
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE FlexibleInstances #-}
module Sound.Likely
( Probability
, ID
, Node (..)
, Edge (..)
, Graph (..)
, insertNode
, insertEdge
, interpretation
, takeNotes
, emptyMusic
, exampleGraph
) where
import Control.Monad
import Data.Aeson
import Data.Aeson.Types (Parser ())
import Data.Maybe
import Data.Text (Text ())
import Euterpea
import System.Random
import qualified Data.Map as M
import qualified Data.Set as S
type Probability = Double
type ID = Text
data Node
= Node
{ nId :: ID
, nMusic :: Music Pitch
} deriving (Show, Eq, Ord)
data Edge
= Edge
{ eTo :: Node
, eProb :: Probability
} deriving (Show, Eq, Ord)
newtype Graph = Graph { unGraph :: M.Map Node (S.Set Edge) }
deriving (Show, Eq, Ord)
insertNode :: Node -> Graph -> Graph
insertNode t = Graph . M.insertWith S.union t S.empty . unGraph
insertEdge :: Node -> Edge -> Graph -> Graph
insertEdge n e =
insertNode n . Graph . M.insertWith S.union n (S.singleton e) . unGraph
interpretation :: RandomGen g => g -> Graph -> Node -> Music Pitch
interpretation gen graph n = (nMusic n) :+:
recurse (fromMaybe S.empty (M.lookup n (unGraph graph)))
where (prob, gen') = randomR (0.0, 1.0) gen
recurse edges =
case edgeForRoll prob edges of
Nothing -> emptyMusic
Just nextEdge ->
interpretation gen' graph . eTo $ nextEdge
edgeForRoll :: Probability -> S.Set Edge -> Maybe Edge
edgeForRoll prob set =
if S.null set
then Nothing
else let curr = S.elemAt 0 set
in if prob <= eProb curr
then Just curr
else edgeForRoll (prob - eProb curr) (S.delete curr set)
emptyMusic :: Music a
emptyMusic = Prim (Rest 0)
exampleGraph :: Graph
exampleGraph = Graph $ M.fromList
[ (Node "bla" (c 4 qn), S.fromList [ Edge (Node "blub" (d 4 qn)) 1 ] )
, (Node "blub" (d 4 qn), S.fromList [ ])
]
-- | Take the first @n@ notes of a 'Music'
takeNotes :: Integer -> Music a -> Music a
takeNotes _ m@(Prim _) = m
takeNotes n (Modify c m) = Modify c $ takeNotes n m
takeNotes _ m@(_ :=: _) = m
takeNotes n (m1 :+: m2)
| n < 1 = emptyMusic
| n == 1 = m1
| otherwise = m1 :+: takeNotes (n - 1) m2
instance FromJSON Node where
parseJSON = withObject "Node" $ \v ->
Node <$> v .: "id" <*> (Prim <$> v .: "music")
lookupNode :: Text -> [Object] -> Parser Node
lookupNode id nodes = do
matches <- filterM (fmap (== id) . (.: "id")) nodes
case matches of
[node] -> parseJSON (Object node)
_ -> fail "Couldn't match node by id"
buildMap :: [Object] -> [Object] -> Graph -> Parser Graph
buildMap _ [] m = pure m
buildMap nodes (e:es) m = do
toId <- e .: "to"
fromId <- e .: "from"
edge <- Edge <$> lookupNode toId nodes <*> e .: "prob"
from <- lookupNode fromId nodes
buildMap nodes es $ insertEdge from edge m
instance FromJSON Graph where
parseJSON = withObject "Graph" $ \v -> do
edges <- v .: "edges"
nodes <- v .: "nodes"
buildMap nodes edges $ Graph mempty
instance FromJSON (Primitive Pitch) where
parseJSON = withObject "Primitive" $ \v -> do
-- TODO Ratio _Integer_ is easy DOSable
-- RAM consumption
duration <- v .: "dur"
octave <- v .: "octave"
pitchClass <- v .: "pitch"
case pitchClass of
"Rest" -> pure $ Rest duration
p -> pure $ Note duration (read pitchClass, octave)
| sternenseemann/likely-music | lib/Sound/Likely.hs | agpl-3.0 | 4,176 | 0 | 16 | 1,002 | 1,350 | 706 | 644 | 103 | 3 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE ExistentialQuantification #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE KindSignatures #-}
module GoNoGo where
------------------------------------------------------------------------------
import MissionControl
import ScratchPad.Astro
import ScratchPad.Weather
------------------------------------------------------------------------------
import Data.Kind
------------------------------------------------------------------------------
data GoNoGo :: RocketState -> WeatherState -> AstronautState -> Type where
GO :: GoNoGo 'NoProblems 'CorrectWeather 'OnBoard
| haroldcarr/learn-haskell-coq-ml-etc | haskell/playpen/2020-07-07-harold-carr-phantom-existential-scratchpad/src/GoNoGo.hs | unlicense | 691 | 0 | 7 | 142 | 66 | 41 | 25 | 11 | 0 |
{-# LANGUAGE TemplateHaskell #-}
module IFind.Config (
IFindConfig(..),
FindFilters(..),
UIColors(..),
readConfFile
) where
import Data.Aeson
import Data.Aeson.Encode.Pretty
import Data.Aeson.TH
import Graphics.Vty.Attributes
import System.Directory
import System.Exit (exitFailure)
import qualified Data.ByteString.Lazy as L
import IFind.Opts
instance FromJSON Color where
parseJSON = fmap ISOColor . parseJSON
instance ToJSON Color where
toJSON (ISOColor c) = toJSON c
toJSON (Color240 _) = error "Expected ISOColor, got Color240"
data UIColors =
UIColors { helpColorDescription :: [String]
, focusedItemForegroundColor:: Color
, focusedItemBackgroundColor:: Color
, searchCountForegroundColor:: Color
, searchCountBackgroundColor:: Color
} deriving (Show)
$(deriveJSON defaultOptions ''UIColors)
-- | regex filters we apply to recursive find
data FindFilters = FindFilters { excludeDirectories:: [String]
, excludePaths:: [String]
} deriving (Show)
$(deriveJSON defaultOptions ''FindFilters)
-- | Common config parameters
-- initially read from $HOME/.iconfig
data IFindConfig =
IFindConfig { uiColors:: UIColors
, findFilters:: FindFilters
} deriving (Show)
$(deriveJSON defaultOptions ''IFindConfig)
emptyFilters:: FindFilters
emptyFilters =
FindFilters { excludeDirectories = []
, excludePaths = []
}
defaultFilters:: FindFilters
defaultFilters =
FindFilters { excludeDirectories = ["\\.git$"
, "\\.svn$"
]
, excludePaths = [ "\\.class$"
, "\\.swp$"
, "\\.hi$"
, "\\.o$"
, "\\.jar$"
]
}
defaultUIColors:: UIColors
defaultUIColors =
UIColors { helpColorDescription = [
"Color mappings:",
"black = 0",
"red = 1",
"green = 2",
"yellow = 3",
"blue = 4",
"magenta = 5",
"cyan = 6",
"white = 7",
"bright_black = 8",
"bright_red = 9",
"bright_green = 10",
"bright_yellow = 11",
"bright_blue = 12",
"bright_magenta= 13",
"bright_cyan = 14",
"bright_white = 15"
]
, focusedItemForegroundColor = black
, focusedItemBackgroundColor = white
, searchCountForegroundColor = black
, searchCountBackgroundColor = yellow
}
defaultConfig:: IFindConfig
defaultConfig =
IFindConfig { uiColors = defaultUIColors
, findFilters = defaultFilters
}
confFileName:: IO FilePath
confFileName = do
homeDir <- getHomeDirectory
return $ homeDir ++ "/.ifind"
createDefaultConfFile:: IO ()
createDefaultConfFile = do
fName <- confFileName
let jsonTxt = encodePretty $ defaultConfig
L.writeFile fName jsonTxt
readConfFile:: IFindOpts -> IO IFindConfig
readConfFile opts = do
fName <- confFileName
foundConfFile <- doesFileExist fName
_ <- if not foundConfFile then createDefaultConfFile else return ()
r <- if noDefaultFilters opts
then return $ Right defaultConfig { findFilters = emptyFilters }
else eitherDecode' <$> L.readFile fName
case r of
Left e -> putStrLn e >> exitFailure
Right ff -> return ff
| andreyk0/ifind | IFind/Config.hs | apache-2.0 | 3,744 | 0 | 12 | 1,330 | 707 | 400 | 307 | 97 | 4 |
-- Copyright (c) 2010 - Seweryn Dynerowicz
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- imitations under the License.
module Algebra.Constructs.Lexicographic
( Lexicographic(..)
, lexicographic
) where
import LaTeX
import Algebra.Matrix
import Algebra.Semiring
data Lexicographic s t = Lex (s,t)
deriving (Eq)
instance (Show s, Show t) => Show (Lexicographic s t) where
show (Lex l) = show l
instance (LaTeX s, LaTeX t) => LaTeX (Lexicographic s t) where
toLaTeX (Lex p) = toLaTeX p
instance (Semiring s, Semiring t) => Semiring (Lexicographic s t) where
zero = Lex (zero, zero)
unit = Lex (unit, unit)
add (Lex (s1,t1)) (Lex (s2,t2))
| (addS == s1 && addS == s2) = Lex (addS,add t1 t2)
| (addS == s1) = Lex (s1,t1)
| (addS == s2) = Lex (s2,t2)
| otherwise = Lex (addS, zero)
where addS = add s1 s2
mul (Lex (s1, t1)) (Lex (s2, t2)) = Lex (mul s1 s2, mul t1 t2)
lub (Lex (s1, t1)) (Lex (s2, t2))
| (lubS == s1 && lubS == s2) = Lex (lubS,add t1 t2)
| (lubS == s1) = Lex (s1,t1)
| (lubS == s2) = Lex (s2,t2)
| otherwise = Lex (lubS, zero)
where lubS = add s1 s2
lexicographic :: (Semiring s, Semiring t) => Matrix s -> Matrix t -> Matrix (Lexicographic s t)
lexicographic as bs | (order as) == (order bs) = pointwise as bs zipL
| otherwise = error "Incompatibles matrice sizes"
zipL :: s -> t -> Lexicographic s t
zipL s t = Lex (s, t)
| sdynerow/Semirings-Library | haskell/Algebra/Constructs/Lexicographic.hs | apache-2.0 | 1,925 | 0 | 12 | 449 | 707 | 374 | 333 | 33 | 1 |
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE OverloadedStrings #-}
{-
Copyright 2018 The CodeWorld Authors. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-}
module Compile
( compileSource
, Stage(..)
) where
import Control.Concurrent
import Control.Monad
import Data.ByteString (ByteString)
import qualified Data.ByteString as B
import Data.ByteString.Char8 (pack)
import Data.Monoid
import ErrorSanitizer
import System.Directory
import System.FilePath
import System.IO
import System.IO.Temp (withSystemTempDirectory)
import System.Process
import Text.Regex.TDFA
import ParseCode
data Stage
= FullBuild
| GenBase String
FilePath
FilePath
| UseBase FilePath
compileSource :: Stage -> FilePath -> FilePath -> FilePath -> String -> IO Bool
compileSource stage src out err mode =
checkDangerousSource src >>= \case
True -> do
B.writeFile
err
"Sorry, but your program refers to forbidden language features."
return False
False ->
withSystemTempDirectory "build" $ \tmpdir -> do
parenProblem <-
case mode of
"codeworld" -> not <$> checkParsedCode src err
_ -> return False
copyFile src (tmpdir </> "program.hs")
baseArgs <-
case mode of
"haskell" -> return haskellCompatibleBuildArgs
"codeworld" -> standardBuildArgs <$> hasOldStyleMain src
linkArgs <-
case stage of
FullBuild -> return []
GenBase mod base _ -> do
copyFile base (tmpdir </> mod <.> "hs")
return ["-generate-base", mod]
UseBase syms -> do
copyFile syms (tmpdir </> "out.base.symbs")
return ["-use-base", "out.base.symbs"]
let ghcjsArgs = ["program.hs"] ++ baseArgs ++ linkArgs
runCompiler tmpdir userCompileMicros ghcjsArgs >>= \case
Nothing -> return False
Just output -> do
let filteredOutput =
case mode of
"codeworld" -> filterOutput output
_ -> output
when (not parenProblem) $ B.writeFile err ""
B.appendFile err filteredOutput
let target = tmpdir </> "program.jsexe"
case stage of
GenBase _ _ syms -> do
hasTarget <-
and <$>
mapM
doesFileExist
[ target </> "rts.js"
, target </> "lib.base.js"
, target </> "out.base.js"
, target </> "out.base.symbs"
]
when hasTarget $ do
rtsCode <- B.readFile $ target </> "rts.js"
libCode <-
B.readFile $ target </> "lib.base.js"
outCode <-
B.readFile $ target </> "out.base.js"
B.writeFile
out
(rtsCode <> libCode <> outCode)
copyFile (target </> "out.base.symbs") syms
return hasTarget
UseBase _ -> do
hasTarget <-
and <$>
mapM
doesFileExist
[ target </> "lib.js"
, target </> "out.js"
]
when hasTarget $ do
libCode <- B.readFile $ target </> "lib.js"
outCode <- B.readFile $ target </> "out.js"
B.writeFile out (libCode <> outCode)
return hasTarget
FullBuild -> do
hasTarget <-
and <$>
mapM
doesFileExist
[ target </> "rts.js"
, target </> "lib.js"
, target </> "out.js"
]
when hasTarget $ do
rtsCode <- B.readFile $ target </> "rts.js"
libCode <- B.readFile $ target </> "lib.js"
outCode <- B.readFile $ target </> "out.js"
B.writeFile
out
(rtsCode <> libCode <> outCode)
return hasTarget
userCompileMicros :: Int
userCompileMicros = 45 * 1000000
checkDangerousSource :: FilePath -> IO Bool
checkDangerousSource dir = do
contents <- B.readFile dir
return $
matches contents ".*TemplateHaskell.*" ||
matches contents ".*QuasiQuotes.*" ||
matches contents ".*glasgow-exts.*"
hasOldStyleMain :: FilePath -> IO Bool
hasOldStyleMain fname = do
contents <- B.readFile fname
return (matches contents "(^|\\n)main[ \\t]*=")
matches :: ByteString -> ByteString -> Bool
matches txt pat = txt =~ pat
runCompiler :: FilePath -> Int -> [String] -> IO (Maybe ByteString)
runCompiler dir micros args = do
(Just inh, Just outh, Just errh, pid) <-
createProcess
(proc "ghcjs" args)
{ cwd = Just dir
, std_in = CreatePipe
, std_out = CreatePipe
, std_err = CreatePipe
, close_fds = True
}
hClose inh
result <- withTimeout micros $ B.hGetContents errh
hClose outh
terminateProcess pid
_ <- waitForProcess pid
return result
standardBuildArgs :: Bool -> [String]
standardBuildArgs True =
[ "-DGHCJS_BROWSER"
, "-dedupe"
, "-Wall"
, "-O2"
, "-fno-warn-deprecated-flags"
, "-fno-warn-amp"
, "-fno-warn-missing-signatures"
, "-fno-warn-incomplete-patterns"
, "-fno-warn-unused-matches"
, "-hide-package"
, "base"
, "-package"
, "codeworld-base"
, "-XBangPatterns"
, "-XDisambiguateRecordFields"
, "-XEmptyDataDecls"
, "-XExistentialQuantification"
, "-XForeignFunctionInterface"
, "-XGADTs"
, "-XJavaScriptFFI"
, "-XKindSignatures"
, "-XLiberalTypeSynonyms"
, "-XNamedFieldPuns"
, "-XNoMonomorphismRestriction"
, "-XNoQuasiQuotes"
, "-XNoTemplateHaskell"
, "-XNoUndecidableInstances"
, "-XOverloadedStrings"
, "-XPackageImports"
, "-XParallelListComp"
, "-XPatternGuards"
, "-XRankNTypes"
, "-XRebindableSyntax"
, "-XRecordWildCards"
, "-XScopedTypeVariables"
, "-XTypeOperators"
, "-XViewPatterns"
, "-XImplicitPrelude" -- MUST come after RebindableSyntax.
]
standardBuildArgs False = standardBuildArgs True ++ ["-main-is", "Main.program"]
haskellCompatibleBuildArgs :: [String]
haskellCompatibleBuildArgs =
[ "-DGHCJS_BROWSER"
, "-dedupe"
, "-Wall"
, "-O2"
, "-package"
, "codeworld-api"
, "-package"
, "QuickCheck"
]
withTimeout :: Int -> IO a -> IO (Maybe a)
withTimeout micros action = do
result <- newEmptyMVar
killer <- forkIO $ threadDelay micros >> putMVar result Nothing
runner <- forkIO $ action >>= putMVar result . Just
r <- takeMVar result
killThread killer
killThread runner
return r
| tgdavies/codeworld | codeworld-compiler/src/Compile.hs | apache-2.0 | 8,890 | 0 | 30 | 3,920 | 1,562 | 785 | 777 | 204 | 10 |
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE BangPatterns #-}
module Data.CRF.Chain1.Constrained.Intersect
( intersect
) where
import qualified Data.Vector.Unboxed as U
import Data.CRF.Chain1.Constrained.Dataset.Internal (Lb, AVec, unAVec)
import Data.CRF.Chain1.Constrained.Model (FeatIx)
-- | Assumption: both input list are given in an ascending order.
intersect
:: AVec (Lb, FeatIx) -- ^ Vector of (label, features index) pairs
-> AVec Lb -- ^ Vector of labels
-- | Intersection of arguments: vector indices from the second list
-- and feature indices from the first list.
-> [(Int, FeatIx)]
intersect xs' ys'
| n == 0 || m == 0 = []
| otherwise = merge xs ys
where
xs = unAVec xs'
ys = unAVec ys'
n = U.length ys
m = U.length xs
merge :: U.Vector (Lb, FeatIx) -> U.Vector Lb -> [(Int, FeatIx)]
merge xs ys = doIt 0 0
where
m = U.length xs
n = U.length ys
doIt i j
| i >= m || j >= n = []
| otherwise = case compare x y of
EQ -> (j, ix) : doIt (i+1) (j+1)
LT -> doIt (i+1) j
GT -> doIt i (j+1)
where
(x, ix) = xs `U.unsafeIndex` i
y = ys `U.unsafeIndex` j
---------------------------------------------
-- Alternative version
---------------------------------------------
-- -- | Assumption: both input list are given in an ascending order.
-- intersect'
-- :: AVec (Lb, FeatIx) -- ^ Vector of (label, features index) pairs
-- -> AVec (Lb, Prob) -- ^ Vector of labels
-- -- | Intersection of arguments: vector indices from the second list
-- -- and feature indices from the first list.
-- -> [(Int, FeatIx)]
-- intersect' xs' ys'
-- | n == 0 || m == 0 = []
-- | otherwise = merge xs ys
-- where
-- xs = unAVec xs'
-- ys = unAVec ys'
-- n = U.length ys
-- m = U.length xs
--
--
-- merge :: U.Vector (Lb, FeatIx) -> U.Vector Lb -> [(Int, FeatIx)]
-- merge xs ys = doIt 0 0
-- where
-- m = U.length xs
-- n = U.length ys
-- doIt i j
-- | i >= m || j >= n = []
-- | otherwise = case compare x y of
-- EQ -> (j, ix) : doIt (i+1) (j+1)
-- LT -> doIt (i+1) j
-- GT -> doIt i (j+1)
-- where
-- (x, ix) = xs `U.unsafeIndex` i
-- y = ys `U.unsafeIndex` j
| kawu/crf-chain1-constrained | src/Data/CRF/Chain1/Constrained/Intersect.hs | bsd-2-clause | 2,352 | 0 | 14 | 707 | 442 | 258 | 184 | 30 | 3 |
{-# LANGUAGE OverloadedStrings #-}
module RefTrack.OAI.Arxiv ( getRecord
) where
import Control.Applicative
import Control.Error
import Data.Char (isSpace)
import Data.Maybe
import Data.Monoid
import qualified Data.Text as T
import qualified Data.Set as S
import Network.URI
import Text.XML
import Text.XML.Cursor
import RefTrack.OAI hiding (getRecord)
import RefTrack.Types
getRecord :: URI -> Identifier -> EitherT String IO Ref
getRecord baseUri id =
oaiRequest baseUri [ ("verb", "GetRecord")
, ("identifier", id)
, ("metadataPrefix", "arXiv")
]
>>= parseRecord . fromDocument
parseAuthor :: Cursor -> Maybe Person
parseAuthor cur =
Person <$> listToMaybe (cur $/ laxElement "forenames" &/ content)
<*> listToMaybe (cur $/ laxElement "keyname" &/ content)
parseRecord :: Monad m => Cursor -> EitherT String m Ref
parseRecord cur = do
metad <- tryHead "Couldn't find arXiv metadata"
$ cur $/ laxElement "GetRecord"
&/ laxElement "record"
&/ laxElement "metadata"
&/ laxElement "arXiv"
arxivId <- tryHead "Couldn't find arXiv ID"
$ metad $/ laxElement "id" &/ content
let authors = mapMaybe parseAuthor $ metad $/ laxElement "authors"
&/ laxElement "author"
title <- tryHead "Couldn't find title"
$ metad $/ laxElement "title" &/ content
let categories = concatMap (T.split isSpace)
$ metad $/ laxElement "categories" &/ content
abstract = T.intercalate " " $ T.lines $ T.intercalate " " $ map T.strip
$ metad $/ laxElement "abstract" &/ content
created = metad $/ laxElement "created" &/ content
return $ Ref { _refId = RefId arxivId
, _refTitle = title
, _refAuthors = authors
, _refPubDate = Nothing
, _refYear = Year 0
, _refExternalRefs = [ ArxivRef $ ArxivId arxivId ]
, _refPublication = OtherPub
, _refAbstract = if T.null abstract then Nothing
else Just abstract
, _refTags = S.fromList $ map Tag $ map ("arxiv:"<>) categories
}
| bgamari/reftrack | RefTrack/OAI/Arxiv.hs | bsd-3-clause | 2,516 | 0 | 17 | 954 | 593 | 309 | 284 | 52 | 2 |
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE OverloadedStrings #-}
-------------------------------------------------------------------------------
-- |
-- Module : Yesod.Comments.Storage
-- Copyright : (c) Patrick Brisbin 2010
-- License : as-is
--
-- Maintainer : pbrisbin@gmail.com
-- Stability : unstable
-- Portability : unportable
--
-------------------------------------------------------------------------------
module Yesod.Comments.Storage
( persistStorage
, migrateComments
, SqlComment
, SqlCommentGeneric (..)
, EntityField (..)
) where
import Yesod
import Yesod.Comments.Core
import Yesod.Markdown (Markdown(..))
import Data.Text (Text)
import Data.Time (UTCTime)
import Database.Persist.Sql (SqlPersist)
share [mkPersist sqlSettings, mkMigrate "migrateComments"] [persistUpperCase|
SqlComment
threadId Text Eq noreference
commentId Int Eq Asc noreference
timeStamp UTCTime
ipAddress Text
userName Text
userEmail Text
content Markdown Update
isAuth Bool
UniqueSqlComment threadId commentId
|]
toSqlComment :: Comment -> SqlComment
toSqlComment comment = SqlComment
{ sqlCommentCommentId = commentId comment
, sqlCommentThreadId = cThreadId comment
, sqlCommentTimeStamp = cTimeStamp comment
, sqlCommentIpAddress = cIpAddress comment
, sqlCommentUserName = cUserName comment
, sqlCommentUserEmail = cUserEmail comment
, sqlCommentContent = cContent comment
, sqlCommentIsAuth = cIsAuth comment
}
fromSqlComment :: SqlComment -> Comment
fromSqlComment sqlComment = Comment
{ commentId = sqlCommentCommentId sqlComment
, cThreadId = sqlCommentThreadId sqlComment
, cTimeStamp = sqlCommentTimeStamp sqlComment
, cIpAddress = sqlCommentIpAddress sqlComment
, cUserName = sqlCommentUserName sqlComment
, cUserEmail = sqlCommentUserEmail sqlComment
, cContent = sqlCommentContent sqlComment
, cIsAuth = sqlCommentIsAuth sqlComment
}
-- | Store comments in an instance of YesodPersit with a SQL backend
persistStorage :: ( YesodPersist m
, YesodPersistBackend m ~ SqlPersist
) => CommentStorage s m
persistStorage = CommentStorage
{ csGet = \tid cid -> do
mentity <- runDB (getBy $ UniqueSqlComment tid cid)
return $ fmap (fromSqlComment . entityVal) mentity
, csStore = \c -> do
_ <- runDB (insert $ toSqlComment c)
return ()
, csUpdate = \(Comment cid tid _ _ _ _ _ _) (Comment _ _ _ _ _ _ newContent _) -> do
mres <- runDB (getBy $ UniqueSqlComment tid cid)
case mres of
Just (Entity k _) -> runDB $ update k [SqlCommentContent =. newContent]
_ -> return ()
, csDelete = \c -> do
_ <- runDB (deleteBy $ UniqueSqlComment (cThreadId c) (commentId c))
return ()
, csLoad = \mthread -> do
entities <- case mthread of
(Just tid) -> runDB (selectList [SqlCommentThreadId ==. tid] [Asc SqlCommentCommentId])
Nothing -> runDB (selectList [] [Asc SqlCommentCommentId])
return $ map (fromSqlComment . entityVal) entities
}
| pbrisbin/yesod-comments | Yesod/Comments/Storage.hs | bsd-3-clause | 3,542 | 0 | 18 | 918 | 723 | 393 | 330 | 64 | 3 |
module Anatomy.Debug where
import Debug.Trace
import Text.Show.Pretty
debugging :: Bool
debugging = False
debug :: (Show a, Show b) => b -> a -> a
debug s v
| debugging = trace (prettyShow s ++ ": " ++ prettyShow v) v
| otherwise = v
dump :: (Monad m, Show a) => a -> m ()
dump x
| debugging = trace (prettyShow x) (return ())
| otherwise = return ()
prettyShow :: Show a => a -> String
prettyShow = ppShow
| vito/atomo-anatomy | src/Anatomy/Debug.hs | bsd-3-clause | 429 | 0 | 10 | 104 | 199 | 100 | 99 | 15 | 1 |
{-# LANGUAGE PatternSynonyms #-}
--------------------------------------------------------------------------------
-- |
-- Module : Graphics.GL.SGIS.TextureBorderClamp
-- Copyright : (c) Sven Panne 2019
-- License : BSD3
--
-- Maintainer : Sven Panne <svenpanne@gmail.com>
-- Stability : stable
-- Portability : portable
--
--------------------------------------------------------------------------------
module Graphics.GL.SGIS.TextureBorderClamp (
-- * Extension Support
glGetSGISTextureBorderClamp,
gl_SGIS_texture_border_clamp,
-- * Enums
pattern GL_CLAMP_TO_BORDER_SGIS
) where
import Graphics.GL.ExtensionPredicates
import Graphics.GL.Tokens
| haskell-opengl/OpenGLRaw | src/Graphics/GL/SGIS/TextureBorderClamp.hs | bsd-3-clause | 679 | 0 | 5 | 91 | 47 | 36 | 11 | 7 | 0 |
-----------------------------------------------------------------------------
-- |
-- Module : TestSuite.Uninterpreted.Function
-- Copyright : (c) Levent Erkok
-- License : BSD3
-- Maintainer : erkokl@gmail.com
-- Stability : experimental
--
-- Testsuite for Data.SBV.Examples.Uninterpreted.Function
-----------------------------------------------------------------------------
module TestSuite.Uninterpreted.Function(tests) where
import Data.SBV.Examples.Uninterpreted.Function
import Utils.SBVTestFramework
tests :: TestTree
tests =
testGroup "Uninterpreted.Function"
[ testCase "aufunc-0" (assertIsThm thmGood)
]
| josefs/sbv | SBVTestSuite/TestSuite/Uninterpreted/Function.hs | bsd-3-clause | 645 | 0 | 9 | 80 | 64 | 42 | 22 | 7 | 1 |
-- |
-- Module: Graphics.LWGL.Vertex_P
-- Copyright: (c) 2017 Patrik Sandahl
-- Licence: BSD3
-- Maintainer: Patrik Sandahl <patrik.sandahl@gmail.com>
-- Stability: experimental
-- Portability: portable
-- Language: Haskell2010
module Graphics.LWGL.Vertex_P
( Vertex (..)
, makeVertexArrayObject
) where
import Control.Monad (void)
import Foreign (Storable (..), castPtr)
import Linear (V3)
import Graphics.LWGL.Api
import Graphics.LWGL.Mesh
import Graphics.LWGL.Types
-- | A vertex record with just one field: position.
data Vertex = Vertex
{ position :: !(V3 GLfloat)
} deriving Show
instance Storable Vertex where
sizeOf v = sizeOf $ position v
alignment v = alignment $ position v
peek ptr = Vertex <$> peek (castPtr ptr)
poke ptr v = poke (castPtr ptr) $ position v
instance Meshable Vertex where
fromList bufferUsage =
makeVertexArrayObject . setBufferFromList bufferUsage
fromVector bufferUsage =
makeVertexArrayObject . setBufferFromVector bufferUsage
-- | Create a Vertex Array Object, with the specified BufferUsage and the
-- given vertices. The vertex attributes are populated (location = 0). At the
-- return the Vertex Array Object is still bound.
makeVertexArrayObject :: IO Vertex -> IO VertexArrayObject
makeVertexArrayObject setBuffer = do
[vaoId] <- glGenVertexArray 1
glBindVertexArray vaoId
[vboId] <- glGenBuffers 1
glBindBuffer ArrayBuffer vboId
void setBuffer
-- Setting position - three components of type GLfloat
glEnableVertexAttribArray (AttributeIndex 0)
glVertexAttribPointer (AttributeIndex 0) Three GLFloat False 0 0
return vaoId
| psandahl/light-weight-opengl | src/Graphics/LWGL/Vertex_P.hs | bsd-3-clause | 1,759 | 0 | 11 | 410 | 340 | 178 | 162 | 34 | 1 |
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
module HaskellCI.Config.CopyFields where
import HaskellCI.Prelude
import qualified Distribution.Compat.CharParsing as C
import qualified Distribution.Parsec as C
import qualified Distribution.Pretty as C
import qualified Text.PrettyPrint as PP
data CopyFields
= CopyFieldsNone
| CopyFieldsSome
| CopyFieldsAll
deriving (Eq, Ord, Show, Enum, Bounded)
-------------------------------------------------------------------------------
-- Functions
-------------------------------------------------------------------------------
showCopyFields :: CopyFields -> String
showCopyFields CopyFieldsNone = "none"
showCopyFields CopyFieldsSome = "some"
showCopyFields CopyFieldsAll = "all"
instance C.Pretty CopyFields where
pretty = PP.text . showCopyFields
instance C.Parsec CopyFields where
parsec = C.choice
[ f <$ C.string (showCopyFields f)
| f <- [ minBound .. maxBound ]
]
| hvr/multi-ghc-travis | src/HaskellCI/Config/CopyFields.hs | bsd-3-clause | 1,039 | 0 | 11 | 196 | 192 | 113 | 79 | 23 | 1 |
module Distribution.ArchLinux.Libalpm.Wrapper.Options where
import Control.Monad.Reader
import Distribution.ArchLinux.Libalpm.Wrapper.Types
import Distribution.ArchLinux.Libalpm.Wrapper.Callbacks
import Distribution.ArchLinux.Libalpm.Wrapper.Alpm
type AlpmOptions = [AlpmOption]
data AlpmOption = AlpmOption
withAlpmOptions :: AlpmOptions -> Alpm a -> Alpm a
withAlpmOptions options a = loadOptions options >> a
loadOptions = undefined
-- | Execute 'Alpm' monadic action with specified event handlers.
withEventHandlers :: EventHandlers -> Alpm a -> Alpm a
withEventHandlers eh a = do
cb <- liftIO $ makeEventCallback eh
local (updater cb) a
where
updater cb env =
env {
envCallbacks = Just $
(maybe defaultCallbacks id (envCallbacks env)) {
callbackEvents = Just cb
}
}
| netvl/alpmhs | lib/Distribution/ArchLinux/Libalpm/Wrapper/Options.hs | bsd-3-clause | 841 | 0 | 14 | 166 | 205 | 113 | 92 | 19 | 1 |
import Data.List
import Data.List.Split
import Data.Ord
flipLog (b:e) = (head e) * (log b)
largestExponential xs = snd . maximum $ zip (map flipLog xs) [1..]
main = readFile "099.txt" >>= print . largestExponential . map (map (read::String->Float) . (splitOn ",")) . lines
| JacksonGariety/euler.hs | 099.hs | bsd-3-clause | 274 | 0 | 12 | 44 | 133 | 69 | 64 | 6 | 1 |
module Main where
import GraphDraw.TestFgl
import Data.Graph.Inductive.Graph
import Data.Graph.Inductive
import Diagrams.Prelude
import Diagrams.Backend.SVG.CmdLine
import Data.List
myGraph :: Gr [Char] ()
myGraph = mkGraph
[(1, "A"), (2, "B"), (3, "C"), (4, "D"), (5, "E"), (6, "E"), (7, "E")]
[(1,2, ()),(2,3, ()),(3,4, ()),(4,5, ()),(5,6, ()),(6,7, ())]
--________________________________________________________________________________________________________________________________
{-
myGraph = mkGraph
[(1, "A"), (2, "B"), (3, "C"), (4, "D"), (5, "E")]
[(1,2, ()),(2,3, ()),(3,4, ()),(4,2, ()),(1,3, ()),(1,4, ()),(1,5, ()),(2,5, ()),(3,5, ())]
-}
{-
myGraph = mkGraph
[(1, "A"), (2, "B"), (3, "C"), (4, "D"), (5, "E"), (6, "F"), (7, "G")]
[(2,1, ()),(2,3, ()),(2,4, ()),(2,5, ()),(2,6, ()),(2,7, ())]
-}
{-
myGraph = mkGraph
[(1, "A"), (2, "B"), (3, "C"), (4, "D"), (5, "E")]
[(1,2, ()),(2,3, ()),(3,4, ()),(4,5, ()),(5,1,()),(1,3,())]
-}
--_________________________________________________________________________________________________________________________________
node :: Int -> Diagram B R2
node n = text (show n) # scale 2.3 # fc white
<> circle 2.3 # fc green # named n
arrowOpts = with Diagrams.Prelude.& arrowHead .~ dart Diagrams.Prelude.& headSize .~ 1.2
Diagrams.Prelude.& shaftStyle %~ lw 0.2
example :: Diagram B R2
example = position . flip zip (map node (nodes myGraph)) . map p2 $ (giveList myGraph 50)
main = mainWith (example # applyAll (map (\(x,y) -> connectOutside' arrowOpts x y ) (edges myGraph)) ::Diagram B R2)
| prash471/GraphDraw | Main.hs | bsd-3-clause | 1,661 | 0 | 13 | 315 | 441 | 252 | 189 | 19 | 1 |
module Text.XML.YJSVG (
SVG(..), Position(..), Color(..), Transform(..),
Font(..), FontWeight(..),
showSVG, topleft, center,
) where
import Text.XML.HaXml(
AttValue(..), QName(..), Prolog(..),
EncodingDecl(..), XMLDecl(..), SystemLiteral(..), PubidLiteral(..),
ExternalID(..), DocTypeDecl(..), Misc(..), Element(..), Content(..),
Document(..) )
import Text.XML.HaXml.Pretty (document)
import Data.Word(Word8)
data FontWeight = Normal | Bold deriving (Show, Read)
weightValue :: FontWeight -> String
weightValue Normal = "normal"
weightValue Bold = "bold"
data Font = Font{ fontName :: String, fontWeight :: FontWeight }
deriving (Show, Read)
data Position
= TopLeft { posX :: Double, posY :: Double }
| Center { posX :: Double, posY :: Double }
deriving (Show, Read)
topleft, center :: Double -> Double -> Position -> Position
topleft w h Center { posX = x, posY = y } =
TopLeft { posX = x + w / 2, posY = - y + h / 2 }
topleft _ _ pos = pos
center w h TopLeft { posX = x, posY = y } =
Center { posX = x - w / 2, posY = - y + h / 2 }
center _ _ pos = pos
getPos :: Double -> Double -> Position -> (Double, Double)
getPos _ _ TopLeft { posX = x, posY = y } = (x, y)
getPos w h Center { posX = x, posY = y } = (x + w / 2, - y + h / 2)
type Id = String
data SVG = Line Position Position Color Double |
Polyline [Position] Color Color Double |
Rect Position Double Double Double Color Color |
Fill Color |
Circle Position Double Color |
Text Position Double Color Font String |
Image Position Double Double FilePath |
Use Position Double Double String |
Group [ Transform ] [ (Id,SVG) ] |
Defs [ (Id,SVG) ]
--Symbol [ (Id,SVG) ]
deriving (Show, Read)
data Color
= ColorName{ colorName :: String }
| RGB { colorRed :: Word8,
colorGreen :: Word8,
colorBlue :: Word8 }
deriving (Eq, Show, Read)
mkColorStr :: Color -> String
mkColorStr ColorName { colorName = n } = n
mkColorStr RGB { colorRed = r, colorGreen = g, colorBlue = b } =
"rgb(" ++ show r ++ "," ++ show g ++ "," ++ show b ++ ")"
data Transform
= Matrix Double Double Double Double Double Double
| Translate Double Double
| Scale Double Double
| Rotate Double (Maybe (Double, Double))
| SkewX Double
| SkewY Double
deriving (Show, Read)
showTrans :: Transform -> String
showTrans (Translate tx ty) = "translate(" ++ show tx ++ "," ++ show ty ++ ") "
showTrans (Scale sx sy) = "scale(" ++ show sx ++ "," ++ show sy ++ ") "
showTrans (SkewX s) = "skewX(" ++ show s ++ ") "
showTrans (SkewY s) = "skewY(" ++ show s ++ ") "
showTrans (Rotate s _) = "rotate(" ++ show s ++ ") "
showTrans (Matrix a b c d e f) = "matrix(" ++
show a ++ "," ++ show b ++ "," ++ show c ++ "," ++
show d ++ "," ++ show e ++ "," ++ show f ++ ") "
-- showTrans _ = error "not implemented yet"
showSVG :: Double -> Double -> [ (Id, SVG) ] -> String
showSVG w h = show . document . svgToXml w h
svgToElem :: Double -> Double -> (Id, SVG) -> Element ()
svgToElem pw ph (idn, (Line p1 p2 color lineWidth)) = Elem (N "line") [
(N "id", AttValue [Left idn]),
(N "x1", AttValue [Left $ show x1]),
(N "y1", AttValue [Left $ show y1]),
(N "x2", AttValue [Left $ show x2]),
(N "y2", AttValue [Left $ show y2]),
(N "stroke", AttValue [Left $ mkColorStr color]),
(N "stroke-width", AttValue [Left $ show lineWidth]),
(N "stroke-linecap", AttValue [Left "round"]) ] []
where
(x1, y1) = getPos pw ph p1
(x2, y2) = getPos pw ph p2
svgToElem pw ph (idn, (Polyline points fillColor lineColor lineWidth)) =
Elem (N "polyline") [
(N "id", AttValue [ Left $ idn ]),
(N "points", AttValue [ Left $ pointsToAttVal points ]),
(N "fill" , AttValue [ Left $ mkColorStr fillColor ]),
(N "stroke", AttValue [ Left $ mkColorStr lineColor ]),
(N "stroke-width", AttValue [ Left $ show lineWidth ]) ] []
where
pointsToAttVal :: [Position] -> String
pointsToAttVal [] = ""
pointsToAttVal (p : ps) = let (x, y) = getPos pw ph p in
show x ++ "," ++ show y ++ " " ++ pointsToAttVal ps
svgToElem pw ph (idn, (Rect p w h sw cf cs)) = Elem (N "rect") [
(N "id", AttValue [Left $ idn]),
(N "x", AttValue [Left $ show x]),
(N "y", AttValue [Left $ show y]),
(N "width", AttValue [Left $ show w]),
(N "height", AttValue [Left $ show h]),
(N "stroke-width", AttValue [Left $ show sw]),
(N "fill", AttValue [Left $ mkColorStr cf]),
(N "stroke", AttValue [Left $ mkColorStr cs]) ] []
where (x, y) = getPos pw ph p
svgToElem pw ph (idn, (Fill c)) =
svgToElem pw ph $ (idn, Rect (TopLeft 0 0) pw ph 0 c c)
svgToElem pw ph (idn, (Text p s c f t)) = Elem (N "text") [
(N "id", AttValue [Left $ idn]),
(N "x", AttValue [Left $ show x]),
(N "y", AttValue [Left $ show y]),
(N "font-family", AttValue [Left $ fontName f]),
(N "font-weight", AttValue [Left $ weightValue $ fontWeight f]),
(N "font-size", AttValue [Left $ show s]),
(N "fill", AttValue [Left $ mkColorStr c]) ]
[CString False (escape t) ()]
where (x, y) = getPos pw ph p
svgToElem pw ph (idn, (Circle p r c)) = Elem (N "circle") [
(N "id", AttValue [Left $ idn]),
(N "cx", AttValue [Left $ show x]),
(N "cy", AttValue [Left $ show y]),
(N "r", AttValue [Left $ show r]),
(N "fill", AttValue [Left $ mkColorStr c]) ] []
where (x, y) = getPos pw ph p
svgToElem pw ph (idn, (Image p w h path)) = Elem (N "image") [
(N "id", AttValue [Left $ idn]),
(N "x", AttValue [Left $ show x]),
(N "y", AttValue [Left $ show y]),
(N "width", AttValue [Left $ show w]),
(N "height", AttValue [Left $ show h]),
(N "xlink:href", AttValue [Left path]) ] []
where (x, y) = getPos pw ph p
svgToElem pw ph (_idn, (Use p w h path)) = Elem (N "use") [
(N "x", AttValue [Left $ show x]),
(N "y", AttValue [Left $ show y]),
(N "width", AttValue [Left $ show w]),
(N "height", AttValue [Left $ show h]),
(N "xlink:href", AttValue [Left ("url(#"++path++")")]) ] []
where (x, y) = getPos pw ph p
svgToElem pw ph (_idn, (Group trs svgs)) = Elem (N "g")
[(N "transform", AttValue (map Left (map showTrans trs)))]
$ map (flip CElem () . svgToElem pw ph) svgs
svgToElem pw ph (_idn, (Defs svgs)) = Elem (N "defs") []
$ map (flip CElem () . svgToElem pw ph) svgs
-- svgToElem pw ph (id, (Symbol svgs)) = Elem (N "symbol") []
-- $ map (flip CElem () . svgToElem pw ph) svgs
svgToXml :: Double -> Double -> [ (Id,SVG) ] -> Document ()
svgToXml w h svgs = Document prlg [] (Elem (N "svg") (emAtt w h)
$ map (flip CElem () . svgToElem w h) svgs) []
pmsc :: [Misc]
pmsc = [ Comment " MADE BY SVG.HS " ]
pblit, sslit :: String
pblit = "-//W3C//DTD SVG 1.1//EN"
sslit = "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"
doctype :: DocTypeDecl
doctype = DTD (N "svg")
(Just (PUBLIC (PubidLiteral pblit) (SystemLiteral sslit))) []
xmldcl :: XMLDecl
xmldcl = XMLDecl "1.0" (Just (EncodingDecl "UTF-8")) Nothing
prlg :: Prolog
prlg = Prolog (Just xmldcl) pmsc (Just doctype) []
xmlns, ver, xlink :: String
xmlns = "http://www.w3.org/2000/svg"
ver = "1.1"
xlink = "http://www.w3.org/1999/xlink"
emAtt :: (Show a, Show b) => a -> b -> [(QName, AttValue)]
emAtt w h = [
(N "xmlns", AttValue [Left xmlns]),
(N "version", AttValue [Left ver]),
(N "xmlns:xlink", AttValue [Left xlink]),
(N "width", AttValue [Left $ show w]),
(N "height", AttValue [Left $ show h]) ]
escape :: String -> String
escape "" = ""
escape ('&' : cs) = "&" ++ escape cs
escape ('<' : cs) = "<" ++ escape cs
escape ('>' : cs) = ">" ++ escape cs
escape (c : cs) = c : escape cs
| YoshikuniJujo/yjsvg_haskell | src/Text/XML/YJSVG.hs | bsd-3-clause | 7,487 | 166 | 17 | 1,614 | 3,851 | 2,055 | 1,796 | 176 | 2 |
{-# LANGUAGE OverloadedStrings #-}
module Redeux.DOM (module Redeux.DOM, DOM) where
import Redeux.Core
import Redeux.DOM.Core
import Data.Text (Text)
import qualified Data.Text as Text
div_, span_, p_, a_, h1_, h2_, h3_
, section_, footer_, header_, strong_
, label_, ul_, li_
, button_ :: [AttrOrHandler g] -> DOM g a -> DOM g a
div_ = el_ "div"
section_ = el_ "section"
footer_ = el_ "footer"
header_ = el_ "header"
label_ = el_ "label"
span_ = el_ "span"
strong_ = el_ "strong"
button_ = el_ "button"
ul_ = el_ "ul"
li_ = el_ "li"
p_ = el_ "p"
a_ = el_ "a"
h1_ = el_ "h1"
h2_ = el_ "h2"
h3_ = el_ "h3"
input_ :: [AttrOrHandler g] -> DOM g ()
input_ a = el_ "input" a (pure ())
attr_ :: Text -> Text -> AttrOrHandler g
attr_ name value = OrAttr (name, value)
text_ :: Text -> DOM g ()
text_ = text
class_, placeholder_, type_, value_
, href_ :: Text -> AttrOrHandler g
class_ = attr_ "class"
placeholder_ = attr_ "placeholder"
type_ = attr_ "type"
value_ = attr_ "value"
href_ = attr_ "href"
classes_ :: [Text] -> AttrOrHandler g
classes_ xs =
let classes = Text.intercalate " " $ xs
in if Text.null classes then OrEmpty
else class_ classes
checked_ :: Bool -> AttrOrHandler g
checked_ b =
if b then attr_ "checked" "checked"
else OrEmpty
onClick, onDoubleClick :: MouseHandler grammer -> AttrOrHandler grammer
onClick f = OrHandler $ Click f
onDoubleClick f = OrHandler $ DoubleClick f
onBlur :: FocusHandler grammer -> AttrOrHandler grammer
onBlur f = OrHandler $ Blur f
onKeyUp, onKeyDown :: KeyboardHandler grammer -> AttrOrHandler grammer
onKeyUp f = OrHandler $ KeyUp f
onKeyDown f = OrHandler $ KeyDown f
onClick_, onDoubleClick_, onBlur_, onKeyUp_, onKeyDown_ :: Command grammer () -> AttrOrHandler grammer
onClick_ = onClick . const
onDoubleClick_ = onDoubleClick . const
onBlur_ = onBlur . const
onKeyUp_ = onKeyUp . const
onKeyDown_ = onKeyDown . const
| eborden/redeux | src/Redeux/DOM.hs | bsd-3-clause | 1,992 | 0 | 11 | 447 | 673 | 366 | 307 | 61 | 2 |
{-# LANGUAGE DeriveDataTypeable #-}
module Missile where
import Data.Data
import Data.Typeable
import Coordinate
type Missile = String
type Missiles = [String]
data Speed = Speed { x :: Float, y :: Float } deriving (Data, Typeable, Show)
data MissileLaunched = MissileLaunched { code :: String, speed :: Speed, pos :: Coordinates, launchTime :: Int } deriving (Data, Typeable, Show)
removeMissedMissiles :: Int -> Float -> [MissileLaunched] -> [MissileLaunched]
removeMissedMissiles currentTime maxWidth missiles = filter (inBoard currentTime maxWidth) missiles
inBoard :: Int -> Float -> MissileLaunched -> Bool
inBoard currentTime maxWidth missile = do
let currentX = missileCurrentX currentTime missile
(currentX > -2000) && (currentX < (maxWidth + 2000))
missileStartX :: MissileLaunched -> Float
missileStartX = Coordinate.x . Missile.pos
missileCurrentX :: Int -> MissileLaunched -> Float
missileCurrentX currentTime missile = startX + (runtime * missileSpeed)
where startX = missileStartX missile
runtime = fromIntegral $ currentTime - (launchTime $ missile)
missileSpeed = Missile.x $ speed $ missile | timorantalaiho/pong11 | src/Missile.hs | bsd-3-clause | 1,142 | 0 | 11 | 188 | 339 | 188 | 151 | 22 | 1 |
{-# LANGUAGE MultiParamTypeClasses, TypeFamilies, FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances,Rank2Types, ScopedTypeVariables #-}
{-# LANGUAGE TemplateHaskell #-}
{-# OPTIONS -Wall #-}
module PushdownAutomaton.State (
PDAState(PDAState),
PDAStaten, initialStackn, initialPDAStaten,
PDATransn, gcompile, translate
) where
import Basic.Types (GetValue, Forward, Trans(Trans), readMem, next)
import Basic.Memory --(Stack(..), empty, MapLike(..))
import Basic.Features (HasQ(..), HasMemory(..), HasIP(..))
import Control.Lens (makeLenses, (%~), (^.), (.~))
import PushdownAutomaton.Operations
---------------------------------------------------------------------
---- PDAState
---------------------------------------------------------------------
data PDAState qs stk ptr = PDAState {_cs :: qs, _mem :: stk, _inptp :: ptr}
makeLenses ''PDAState
instance HasQ (PDAState qs stk ptr) where
type Q (PDAState qs stk ptr) = qs
q = cs
instance HasMemory (PDAState qs stk ptr) where
type Memory (PDAState qs stk ptr) = stk
memory = mem
instance HasIP (PDAState qs stk ptr) where
type IP (PDAState qs stk ptr) = ptr
ip = inptp
---------------------------------------------------------------------
---- PDAState with n stack
---------------------------------------------------------------------
type PDAStaten qs map n stack s ptr = PDAState qs (map n (stack s)) ptr
initialStackn :: (Stack s, MapLike m) => v -> m a (s v) -> m a (s v)
initialStackn v mapn = mapWithKeyM mapn (\_ _ -> push v empty)
initialPDAStaten :: (Stack stack, MapLike map, Ord n, Bounded n, Enum n) =>
qs -> v -> ptr -> PDAStaten qs map n stack v ptr
initialPDAStaten qs v ptr = PDAState qs (initialStackn v emptyM') ptr
type PDATransn m n ch s qs = ch -> m n s -> qs -> (qs, m n (StackCommd s))
gcompile :: (Ord a, HasQ st, HasIP st, HasMemory st, Stack s, MapLike m,
Memory st ~ m a (s v), Forward (IP st), GetValue (IP st) mem b ) =>
(b -> m a v -> Q st -> (Q st, m a (StackCommd v))) -> Trans (x, mem b) st
gcompile f = Trans g
where g (_, inpt) st = ip %~ next $ q .~ qs' $ memory %~ (stackoperate comds') $ st
where stkm = mapWithKeyM (st^.memory) (\_ -> top)
ch = readMem (st^.ip) inpt
(qs', comds') = f ch stkm (st^.q)
stackoperate comds stkmap = mapWithKeyM stkmap sop
where sop k sta = stackoperation (lookupM comds k) sta
translate :: forall a b qs m n. (Ord n, Bounded n, Enum n, AscListLike m) =>
(a -> [b] -> qs -> (qs, [StackCommd b])) -> PDATransn m n a b qs
translate f inp stak qs = (qs', mapFromL (minBound::n) stakctrl)
where
(qs', stakctrl) = f inp stak' qs
stak' = map snd $ mapToL stak | davidzhulijun/TAM | PushdownAutomaton/State.hs | bsd-3-clause | 2,717 | 0 | 14 | 556 | 1,022 | 560 | 462 | 49 | 1 |
-----------------------------------------------------------------------------
--
-- (c) The University of Glasgow 2006
--
-- The purpose of this module is to transform an HsExpr into a CoreExpr which
-- when evaluated, returns a (Meta.Q Meta.Exp) computation analogous to the
-- input HsExpr. We do this in the DsM monad, which supplies access to
-- CoreExpr's of the "smart constructors" of the Meta.Exp datatype.
--
-- It also defines a bunch of knownKeyNames, in the same way as is done
-- in prelude/PrelNames. It's much more convenient to do it here, becuase
-- otherwise we have to recompile PrelNames whenever we add a Name, which is
-- a Royal Pain (triggers other recompilation).
-----------------------------------------------------------------------------
{-# OPTIONS -fno-warn-tabs #-}
-- The above warning supression flag is a temporary kludge.
-- While working on this module you are encouraged to remove it and
-- detab the module (please do the detabbing in a separate patch). See
-- http://hackage.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#TabsvsSpaces
-- for details
module DsMeta( dsBracket,
templateHaskellNames, qTyConName, nameTyConName,
liftName, liftStringName, expQTyConName, patQTyConName,
decQTyConName, decsQTyConName, typeQTyConName,
decTyConName, typeTyConName, mkNameG_dName, mkNameG_vName, mkNameG_tcName,
quoteExpName, quotePatName, quoteDecName, quoteTypeName
) where
#include "HsVersions.h"
import {-# SOURCE #-} DsExpr ( dsExpr )
import MatchLit
import DsMonad
import qualified Language.Haskell.TH as TH
import HsSyn
import Class
import PrelNames
-- To avoid clashes with DsMeta.varName we must make a local alias for
-- OccName.varName we do this by removing varName from the import of
-- OccName above, making a qualified instance of OccName and using
-- OccNameAlias.varName where varName ws previously used in this file.
import qualified OccName( isDataOcc, isVarOcc, isTcOcc, varName, tcName, dataName )
import Module
import Id
import Name hiding( isVarOcc, isTcOcc, varName, tcName )
import NameEnv
import TcType
import TyCon
import TysWiredIn
import TysPrim ( liftedTypeKindTyConName, constraintKindTyConName )
import CoreSyn
import MkCore
import CoreUtils
import SrcLoc
import Unique
import BasicTypes
import Outputable
import Bag
import FastString
import ForeignCall
import MonadUtils
import Util
import Data.Maybe
import Control.Monad
import Data.List
-----------------------------------------------------------------------------
dsBracket :: HsBracket Name -> [PendingSplice] -> DsM CoreExpr
-- Returns a CoreExpr of type TH.ExpQ
-- The quoted thing is parameterised over Name, even though it has
-- been type checked. We don't want all those type decorations!
dsBracket brack splices
= dsExtendMetaEnv new_bit (do_brack brack)
where
new_bit = mkNameEnv [(n, Splice (unLoc e)) | (n,e) <- splices]
do_brack (VarBr _ n) = do { MkC e1 <- lookupOcc n ; return e1 }
do_brack (ExpBr e) = do { MkC e1 <- repLE e ; return e1 }
do_brack (PatBr p) = do { MkC p1 <- repTopP p ; return p1 }
do_brack (TypBr t) = do { MkC t1 <- repLTy t ; return t1 }
do_brack (DecBrG gp) = do { MkC ds1 <- repTopDs gp ; return ds1 }
do_brack (DecBrL _) = panic "dsBracket: unexpected DecBrL"
{- -------------- Examples --------------------
[| \x -> x |]
====>
gensym (unpackString "x"#) `bindQ` \ x1::String ->
lam (pvar x1) (var x1)
[| \x -> $(f [| x |]) |]
====>
gensym (unpackString "x"#) `bindQ` \ x1::String ->
lam (pvar x1) (f (var x1))
-}
-------------------------------------------------------
-- Declarations
-------------------------------------------------------
repTopP :: LPat Name -> DsM (Core TH.PatQ)
repTopP pat = do { ss <- mkGenSyms (collectPatBinders pat)
; pat' <- addBinds ss (repLP pat)
; wrapGenSyms ss pat' }
repTopDs :: HsGroup Name -> DsM (Core (TH.Q [TH.Dec]))
repTopDs group
= do { let { tv_bndrs = hsSigTvBinders (hs_valds group)
; bndrs = tv_bndrs ++ hsGroupBinders group } ;
ss <- mkGenSyms bndrs ;
-- Bind all the names mainly to avoid repeated use of explicit strings.
-- Thus we get
-- do { t :: String <- genSym "T" ;
-- return (Data t [] ...more t's... }
-- The other important reason is that the output must mention
-- only "T", not "Foo:T" where Foo is the current module
decls <- addBinds ss (do {
fix_ds <- mapM repFixD (hs_fixds group) ;
val_ds <- rep_val_binds (hs_valds group) ;
tycl_ds <- mapM repTyClD (concat (hs_tyclds group)) ;
inst_ds <- mapM repInstD (hs_instds group) ;
rule_ds <- mapM repRuleD (hs_ruleds group) ;
for_ds <- mapM repForD (hs_fords group) ;
-- more needed
return (de_loc $ sort_by_loc $
val_ds ++ catMaybes tycl_ds ++ fix_ds
++ inst_ds ++ rule_ds ++ for_ds) }) ;
decl_ty <- lookupType decQTyConName ;
let { core_list = coreList' decl_ty decls } ;
dec_ty <- lookupType decTyConName ;
q_decs <- repSequenceQ dec_ty core_list ;
wrapGenSyms ss q_decs
}
hsSigTvBinders :: HsValBinds Name -> [Name]
-- See Note [Scoped type variables in bindings]
hsSigTvBinders binds
= [hsLTyVarName tv | L _ (TypeSig _ (L _ (HsForAllTy Explicit qtvs _ _))) <- sigs
, tv <- hsQTvBndrs qtvs]
where
sigs = case binds of
ValBindsIn _ sigs -> sigs
ValBindsOut _ sigs -> sigs
{- Notes
Note [Scoped type variables in bindings]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider
f :: forall a. a -> a
f x = x::a
Here the 'forall a' brings 'a' into scope over the binding group.
To achieve this we
a) Gensym a binding for 'a' at the same time as we do one for 'f'
collecting the relevant binders with hsSigTvBinders
b) When processing the 'forall', don't gensym
The relevant places are signposted with references to this Note
Note [Binders and occurrences]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
When we desugar [d| data T = MkT |]
we want to get
Data "T" [] [Con "MkT" []] []
and *not*
Data "Foo:T" [] [Con "Foo:MkT" []] []
That is, the new data decl should fit into whatever new module it is
asked to fit in. We do *not* clone, though; no need for this:
Data "T79" ....
But if we see this:
data T = MkT
foo = reifyDecl T
then we must desugar to
foo = Data "Foo:T" [] [Con "Foo:MkT" []] []
So in repTopDs we bring the binders into scope with mkGenSyms and addBinds.
And we use lookupOcc, rather than lookupBinder
in repTyClD and repC.
-}
-- represent associated family instances
--
repTyClDs :: [LTyClDecl Name] -> DsM [Core TH.DecQ]
repTyClDs ds = liftM de_loc (mapMaybeM repTyClD ds)
repTyClD :: LTyClDecl Name -> DsM (Maybe (SrcSpan, Core TH.DecQ))
repTyClD (L loc (TyFamily { tcdFlavour = flavour,
tcdLName = tc, tcdTyVars = tvs,
tcdKindSig = opt_kind }))
= do { tc1 <- lookupLOcc tc -- See note [Binders and occurrences]
; dec <- addTyClTyVarBinds tvs $ \bndrs ->
do { flav <- repFamilyFlavour flavour
; case opt_kind of
Nothing -> repFamilyNoKind flav tc1 bndrs
Just ki -> do { ki1 <- repLKind ki
; repFamilyKind flav tc1 bndrs ki1 }
}
; return $ Just (loc, dec)
}
repTyClD (L loc (TyDecl { tcdLName = tc, tcdTyVars = tvs, tcdTyDefn = defn }))
= do { tc1 <- lookupLOcc tc -- See note [Binders and occurrences]
; tc_tvs <- mk_extra_tvs tc tvs defn
; dec <- addTyClTyVarBinds tc_tvs $ \bndrs ->
repTyDefn tc1 bndrs Nothing (hsLTyVarNames tc_tvs) defn
; return (Just (loc, dec)) }
repTyClD (L loc (ClassDecl { tcdCtxt = cxt, tcdLName = cls,
tcdTyVars = tvs, tcdFDs = fds,
tcdSigs = sigs, tcdMeths = meth_binds,
tcdATs = ats, tcdATDefs = [] }))
= do { cls1 <- lookupLOcc cls -- See note [Binders and occurrences]
; dec <- addTyVarBinds tvs $ \bndrs ->
do { cxt1 <- repLContext cxt
; sigs1 <- rep_sigs sigs
; binds1 <- rep_binds meth_binds
; fds1 <- repLFunDeps fds
; ats1 <- repTyClDs ats
; decls1 <- coreList decQTyConName (ats1 ++ sigs1 ++ binds1)
; repClass cxt1 cls1 bndrs fds1 decls1
}
; return $ Just (loc, dec)
}
-- Un-handled cases
repTyClD (L loc d) = putSrcSpanDs loc $
do { warnDs (hang ds_msg 4 (ppr d))
; return Nothing }
-------------------------
repTyDefn :: Core TH.Name -> Core [TH.TyVarBndr]
-> Maybe (Core [TH.TypeQ])
-> [Name] -> HsTyDefn Name
-> DsM (Core TH.DecQ)
repTyDefn tc bndrs opt_tys tv_names
(TyData { td_ND = new_or_data, td_ctxt = cxt
, td_cons = cons, td_derivs = mb_derivs })
= do { cxt1 <- repLContext cxt
; derivs1 <- repDerivs mb_derivs
; case new_or_data of
NewType -> do { con1 <- repC tv_names (head cons)
; repNewtype cxt1 tc bndrs opt_tys con1 derivs1 }
DataType -> do { cons1 <- mapM (repC tv_names) cons
; cons2 <- coreList conQTyConName cons1
; repData cxt1 tc bndrs opt_tys cons2 derivs1 } }
repTyDefn tc bndrs opt_tys _ (TySynonym { td_synRhs = ty })
= do { ty1 <- repLTy ty
; repTySyn tc bndrs opt_tys ty1 }
-------------------------
mk_extra_tvs :: Located Name -> LHsTyVarBndrs Name
-> HsTyDefn Name -> DsM (LHsTyVarBndrs Name)
-- If there is a kind signature it must be of form
-- k1 -> .. -> kn -> *
-- Return type variables [tv1:k1, tv2:k2, .., tvn:kn]
mk_extra_tvs tc tvs defn
| TyData { td_kindSig = Just hs_kind } <- defn
= do { extra_tvs <- go hs_kind
; return (tvs { hsq_tvs = hsq_tvs tvs ++ extra_tvs }) }
| otherwise
= return tvs
where
go :: LHsKind Name -> DsM [LHsTyVarBndr Name]
go (L loc (HsFunTy kind rest))
= do { uniq <- newUnique
; let { occ = mkTyVarOccFS (fsLit "t")
; nm = mkInternalName uniq occ loc
; hs_tv = L loc (KindedTyVar nm kind) }
; hs_tvs <- go rest
; return (hs_tv : hs_tvs) }
go (L _ (HsTyVar n))
| n == liftedTypeKindTyConName
= return []
go _ = failWithDs (ptext (sLit "Malformed kind signature for") <+> ppr tc)
-------------------------
-- represent fundeps
--
repLFunDeps :: [Located (FunDep Name)] -> DsM (Core [TH.FunDep])
repLFunDeps fds = do fds' <- mapM repLFunDep fds
fdList <- coreList funDepTyConName fds'
return fdList
repLFunDep :: Located (FunDep Name) -> DsM (Core TH.FunDep)
repLFunDep (L _ (xs, ys)) = do xs' <- mapM lookupBinder xs
ys' <- mapM lookupBinder ys
xs_list <- coreList nameTyConName xs'
ys_list <- coreList nameTyConName ys'
repFunDep xs_list ys_list
-- represent family declaration flavours
--
repFamilyFlavour :: FamilyFlavour -> DsM (Core TH.FamFlavour)
repFamilyFlavour TypeFamily = rep2 typeFamName []
repFamilyFlavour DataFamily = rep2 dataFamName []
-- Represent instance declarations
--
repInstD :: LInstDecl Name -> DsM (SrcSpan, Core TH.DecQ)
repInstD (L loc (FamInstD { lid_inst = fi_decl }))
= do { dec <- repFamInstD fi_decl
; return (loc, dec) }
repInstD (L loc (ClsInstD { cid_poly_ty = ty, cid_binds = binds
, cid_sigs = prags, cid_fam_insts = ats }))
= do { dec <- addTyVarBinds tvs $ \_ ->
-- We must bring the type variables into scope, so their
-- occurrences don't fail, even though the binders don't
-- appear in the resulting data structure
--
-- But we do NOT bring the binders of 'binds' into scope
-- becuase they are properly regarded as occurrences
-- For example, the method names should be bound to
-- the selector Ids, not to fresh names (Trac #5410)
--
do { cxt1 <- repContext cxt
; cls_tcon <- repTy (HsTyVar (unLoc cls))
; cls_tys <- repLTys tys
; inst_ty1 <- repTapps cls_tcon cls_tys
; binds1 <- rep_binds binds
; prags1 <- rep_sigs prags
; ats1 <- mapM (repFamInstD . unLoc) ats
; decls <- coreList decQTyConName (ats1 ++ binds1 ++ prags1)
; repInst cxt1 inst_ty1 decls }
; return (loc, dec) }
where
Just (tvs, cxt, cls, tys) = splitLHsInstDeclTy_maybe ty
repFamInstD :: FamInstDecl Name -> DsM (Core TH.DecQ)
repFamInstD (FamInstDecl { fid_tycon = tc_name
, fid_pats = HsWB { hswb_cts = tys, hswb_kvs = kv_names, hswb_tvs = tv_names }
, fid_defn = defn })
= WARN( not (null kv_names), ppr kv_names ) -- We have not yet dealt with kind
-- polymorphism in Template Haskell (sigh)
do { tc <- lookupLOcc tc_name -- See note [Binders and occurrences]
; let loc = getLoc tc_name
hs_tvs = HsQTvs { hsq_kvs = kv_names, hsq_tvs = userHsTyVarBndrs loc tv_names } -- Yuk
; addTyClTyVarBinds hs_tvs $ \ bndrs ->
do { tys1 <- repLTys tys
; tys2 <- coreList typeQTyConName tys1
; repTyDefn tc bndrs (Just tys2) tv_names defn } }
repForD :: Located (ForeignDecl Name) -> DsM (SrcSpan, Core TH.DecQ)
repForD (L loc (ForeignImport name typ _ (CImport cc s mch cis)))
= do MkC name' <- lookupLOcc name
MkC typ' <- repLTy typ
MkC cc' <- repCCallConv cc
MkC s' <- repSafety s
cis' <- conv_cimportspec cis
MkC str <- coreStringLit (static ++ chStr ++ cis')
dec <- rep2 forImpDName [cc', s', str, name', typ']
return (loc, dec)
where
conv_cimportspec (CLabel cls) = notHandled "Foreign label" (doubleQuotes (ppr cls))
conv_cimportspec (CFunction DynamicTarget) = return "dynamic"
conv_cimportspec (CFunction (StaticTarget fs _ True)) = return (unpackFS fs)
conv_cimportspec (CFunction (StaticTarget _ _ False)) = panic "conv_cimportspec: values not supported yet"
conv_cimportspec CWrapper = return "wrapper"
static = case cis of
CFunction (StaticTarget _ _ _) -> "static "
_ -> ""
chStr = case mch of
Nothing -> ""
Just (Header h) -> unpackFS h ++ " "
repForD decl = notHandled "Foreign declaration" (ppr decl)
repCCallConv :: CCallConv -> DsM (Core TH.Callconv)
repCCallConv CCallConv = rep2 cCallName []
repCCallConv StdCallConv = rep2 stdCallName []
repCCallConv callConv = notHandled "repCCallConv" (ppr callConv)
repSafety :: Safety -> DsM (Core TH.Safety)
repSafety PlayRisky = rep2 unsafeName []
repSafety PlayInterruptible = rep2 interruptibleName []
repSafety PlaySafe = rep2 safeName []
repFixD :: LFixitySig Name -> DsM (SrcSpan, Core TH.DecQ)
repFixD (L loc (FixitySig name (Fixity prec dir)))
= do { MkC name' <- lookupLOcc name
; MkC prec' <- coreIntLit prec
; let rep_fn = case dir of
InfixL -> infixLDName
InfixR -> infixRDName
InfixN -> infixNDName
; dec <- rep2 rep_fn [prec', name']
; return (loc, dec) }
repRuleD :: LRuleDecl Name -> DsM (SrcSpan, Core TH.DecQ)
repRuleD (L loc (HsRule n act bndrs lhs _ rhs _))
= do { n' <- coreStringLit $ unpackFS n
; phases <- repPhases act
; bndrs' <- mapM repRuleBndr bndrs >>= coreList ruleBndrQTyConName
; lhs' <- repLE lhs
; rhs' <- repLE rhs
; pragma <- repPragRule n' bndrs' lhs' rhs' phases
; return (loc, pragma) }
repRuleBndr :: RuleBndr Name -> DsM (Core TH.RuleBndrQ)
repRuleBndr (RuleBndr n)
= do { MkC n' <- lookupLOcc n
; rep2 ruleVarName [n'] }
repRuleBndr (RuleBndrSig n (HsWB { hswb_cts = ty }))
= do { MkC n' <- lookupLOcc n
; MkC ty' <- repLTy ty
; rep2 typedRuleVarName [n', ty'] }
ds_msg :: SDoc
ds_msg = ptext (sLit "Cannot desugar this Template Haskell declaration:")
-------------------------------------------------------
-- Constructors
-------------------------------------------------------
repC :: [Name] -> LConDecl Name -> DsM (Core TH.ConQ)
repC _ (L _ (ConDecl { con_name = con, con_qvars = con_tvs, con_cxt = L _ []
, con_details = details, con_res = ResTyH98 }))
| null (hsQTvBndrs con_tvs)
= do { con1 <- lookupLOcc con -- See Note [Binders and occurrences]
; repConstr con1 details }
repC tvs (L _ (ConDecl { con_name = con
, con_qvars = con_tvs, con_cxt = L _ ctxt
, con_details = details
, con_res = res_ty }))
= do { (eq_ctxt, con_tv_subst) <- mkGadtCtxt tvs res_ty
; let ex_tvs = HsQTvs { hsq_kvs = filterOut (in_subst con_tv_subst) (hsq_kvs con_tvs)
, hsq_tvs = filterOut (in_subst con_tv_subst . hsLTyVarName) (hsq_tvs con_tvs) }
; binds <- mapM dupBinder con_tv_subst
; dsExtendMetaEnv (mkNameEnv binds) $ -- Binds some of the con_tvs
addTyVarBinds ex_tvs $ \ ex_bndrs -> -- Binds the remaining con_tvs
do { con1 <- lookupLOcc con -- See Note [Binders and occurrences]
; c' <- repConstr con1 details
; ctxt' <- repContext (eq_ctxt ++ ctxt)
; rep2 forallCName [unC ex_bndrs, unC ctxt', unC c'] } }
in_subst :: [(Name,Name)] -> Name -> Bool
in_subst [] _ = False
in_subst ((n',_):ns) n = n==n' || in_subst ns n
mkGadtCtxt :: [Name] -- Tyvars of the data type
-> ResType (LHsType Name)
-> DsM (HsContext Name, [(Name,Name)])
-- Given a data type in GADT syntax, figure out the equality
-- context, so that we can represent it with an explicit
-- equality context, because that is the only way to express
-- the GADT in TH syntax
--
-- Example:
-- data T a b c where { MkT :: forall d e. d -> e -> T d [e] e
-- mkGadtCtxt [a,b,c] [d,e] (T d [e] e)
-- returns
-- (b~[e], c~e), [d->a]
--
-- This function is fiddly, but not really hard
mkGadtCtxt _ ResTyH98
= return ([], [])
mkGadtCtxt data_tvs (ResTyGADT res_ty)
| let (head_ty, tys) = splitHsAppTys res_ty []
, Just _ <- is_hs_tyvar head_ty
, data_tvs `equalLength` tys
= return (go [] [] (data_tvs `zip` tys))
| otherwise
= failWithDs (ptext (sLit "Malformed constructor result type:") <+> ppr res_ty)
where
go cxt subst [] = (cxt, subst)
go cxt subst ((data_tv, ty) : rest)
| Just con_tv <- is_hs_tyvar ty
, isTyVarName con_tv
, not (in_subst subst con_tv)
= go cxt ((con_tv, data_tv) : subst) rest
| otherwise
= go (eq_pred : cxt) subst rest
where
loc = getLoc ty
eq_pred = L loc (HsEqTy (L loc (HsTyVar data_tv)) ty)
is_hs_tyvar (L _ (HsTyVar n)) = Just n -- Type variables *and* tycons
is_hs_tyvar (L _ (HsParTy ty)) = is_hs_tyvar ty
is_hs_tyvar _ = Nothing
repBangTy :: LBangType Name -> DsM (Core (TH.StrictTypeQ))
repBangTy ty= do
MkC s <- rep2 str []
MkC t <- repLTy ty'
rep2 strictTypeName [s, t]
where
(str, ty') = case ty of
L _ (HsBangTy HsUnpack ty) -> (unpackedName, ty)
L _ (HsBangTy _ ty) -> (isStrictName, ty)
_ -> (notStrictName, ty)
-------------------------------------------------------
-- Deriving clause
-------------------------------------------------------
repDerivs :: Maybe [LHsType Name] -> DsM (Core [TH.Name])
repDerivs Nothing = coreList nameTyConName []
repDerivs (Just ctxt)
= do { strs <- mapM rep_deriv ctxt ;
coreList nameTyConName strs }
where
rep_deriv :: LHsType Name -> DsM (Core TH.Name)
-- Deriving clauses must have the simple H98 form
rep_deriv ty
| Just (cls, []) <- splitHsClassTy_maybe (unLoc ty)
= lookupOcc cls
| otherwise
= notHandled "Non-H98 deriving clause" (ppr ty)
-------------------------------------------------------
-- Signatures in a class decl, or a group of bindings
-------------------------------------------------------
rep_sigs :: [LSig Name] -> DsM [Core TH.DecQ]
rep_sigs sigs = do locs_cores <- rep_sigs' sigs
return $ de_loc $ sort_by_loc locs_cores
rep_sigs' :: [LSig Name] -> DsM [(SrcSpan, Core TH.DecQ)]
-- We silently ignore ones we don't recognise
rep_sigs' sigs = do { sigs1 <- mapM rep_sig sigs ;
return (concat sigs1) }
rep_sig :: LSig Name -> DsM [(SrcSpan, Core TH.DecQ)]
-- Singleton => Ok
-- Empty => Too hard, signature ignored
rep_sig (L loc (TypeSig nms ty)) = mapM (rep_ty_sig loc ty) nms
rep_sig (L _ (GenericSig nm _)) = failWithDs msg
where msg = vcat [ ptext (sLit "Illegal default signature for") <+> quotes (ppr nm)
, ptext (sLit "Default signatures are not supported by Template Haskell") ]
rep_sig (L loc (InlineSig nm ispec)) = rep_inline nm ispec loc
rep_sig (L loc (SpecSig nm ty ispec)) = rep_specialise nm ty ispec loc
rep_sig (L loc (SpecInstSig ty)) = rep_specialiseInst ty loc
rep_sig _ = return []
rep_ty_sig :: SrcSpan -> LHsType Name -> Located Name
-> DsM (SrcSpan, Core TH.DecQ)
rep_ty_sig loc (L _ ty) nm
= do { nm1 <- lookupLOcc nm
; ty1 <- rep_ty ty
; sig <- repProto nm1 ty1
; return (loc, sig) }
where
-- We must special-case the top-level explicit for-all of a TypeSig
-- See Note [Scoped type variables in bindings]
rep_ty (HsForAllTy Explicit tvs ctxt ty)
= do { let rep_in_scope_tv tv = do { name <- lookupBinder (hsLTyVarName tv)
; repTyVarBndrWithKind tv name }
; bndrs1 <- mapM rep_in_scope_tv (hsQTvBndrs tvs)
; bndrs2 <- coreList tyVarBndrTyConName bndrs1
; ctxt1 <- repLContext ctxt
; ty1 <- repLTy ty
; repTForall bndrs2 ctxt1 ty1 }
rep_ty ty = repTy ty
rep_inline :: Located Name
-> InlinePragma -- Never defaultInlinePragma
-> SrcSpan
-> DsM [(SrcSpan, Core TH.DecQ)]
rep_inline nm ispec loc
= do { nm1 <- lookupLOcc nm
; inline <- repInline $ inl_inline ispec
; rm <- repRuleMatch $ inl_rule ispec
; phases <- repPhases $ inl_act ispec
; pragma <- repPragInl nm1 inline rm phases
; return [(loc, pragma)]
}
rep_specialise :: Located Name -> LHsType Name -> InlinePragma -> SrcSpan
-> DsM [(SrcSpan, Core TH.DecQ)]
rep_specialise nm ty ispec loc
= do { nm1 <- lookupLOcc nm
; ty1 <- repLTy ty
; phases <- repPhases $ inl_act ispec
; let inline = inl_inline ispec
; pragma <- if isEmptyInlineSpec inline
then -- SPECIALISE
repPragSpec nm1 ty1 phases
else -- SPECIALISE INLINE
do { inline1 <- repInline inline
; repPragSpecInl nm1 ty1 inline1 phases }
; return [(loc, pragma)]
}
rep_specialiseInst :: LHsType Name -> SrcSpan -> DsM [(SrcSpan, Core TH.DecQ)]
rep_specialiseInst ty loc
= do { ty1 <- repLTy ty
; pragma <- repPragSpecInst ty1
; return [(loc, pragma)] }
repInline :: InlineSpec -> DsM (Core TH.Inline)
repInline NoInline = dataCon noInlineDataConName
repInline Inline = dataCon inlineDataConName
repInline Inlinable = dataCon inlinableDataConName
repInline spec = notHandled "repInline" (ppr spec)
repRuleMatch :: RuleMatchInfo -> DsM (Core TH.RuleMatch)
repRuleMatch ConLike = dataCon conLikeDataConName
repRuleMatch FunLike = dataCon funLikeDataConName
repPhases :: Activation -> DsM (Core TH.Phases)
repPhases (ActiveBefore i) = do { MkC arg <- coreIntLit i
; dataCon' beforePhaseDataConName [arg] }
repPhases (ActiveAfter i) = do { MkC arg <- coreIntLit i
; dataCon' fromPhaseDataConName [arg] }
repPhases _ = dataCon allPhasesDataConName
-------------------------------------------------------
-- Types
-------------------------------------------------------
addTyVarBinds :: LHsTyVarBndrs Name -- the binders to be added
-> (Core [TH.TyVarBndr] -> DsM (Core (TH.Q a))) -- action in the ext env
-> DsM (Core (TH.Q a))
-- gensym a list of type variables and enter them into the meta environment;
-- the computations passed as the second argument is executed in that extended
-- meta environment and gets the *new* names on Core-level as an argument
addTyVarBinds tvs m
= do { freshNames <- mkGenSyms (hsLKiTyVarNames tvs)
; term <- addBinds freshNames $
do { kbs1 <- mapM mk_tv_bndr (hsQTvBndrs tvs `zip` freshNames)
; kbs2 <- coreList tyVarBndrTyConName kbs1
; m kbs2 }
; wrapGenSyms freshNames term }
where
mk_tv_bndr (tv, (_,v)) = repTyVarBndrWithKind tv (coreVar v)
addTyClTyVarBinds :: LHsTyVarBndrs Name
-> (Core [TH.TyVarBndr] -> DsM (Core (TH.Q a)))
-> DsM (Core (TH.Q a))
-- Used for data/newtype declarations, and family instances,
-- so that the nested type variables work right
-- instance C (T a) where
-- type W (T a) = blah
-- The 'a' in the type instance is the one bound by the instance decl
addTyClTyVarBinds tvs m
= do { let tv_names = hsLKiTyVarNames tvs
; env <- dsGetMetaEnv
; freshNames <- mkGenSyms (filterOut (`elemNameEnv` env) tv_names)
-- Make fresh names for the ones that are not already in scope
-- This makes things work for family declarations
; term <- addBinds freshNames $
do { kbs1 <- mapM mk_tv_bndr (hsQTvBndrs tvs)
; kbs2 <- coreList tyVarBndrTyConName kbs1
; m kbs2 }
; wrapGenSyms freshNames term }
where
mk_tv_bndr tv = do { v <- lookupOcc (hsLTyVarName tv)
; repTyVarBndrWithKind tv v }
-- Produce kinded binder constructors from the Haskell tyvar binders
--
repTyVarBndrWithKind :: LHsTyVarBndr Name
-> Core TH.Name -> DsM (Core TH.TyVarBndr)
repTyVarBndrWithKind (L _ (UserTyVar {})) nm
= repPlainTV nm
repTyVarBndrWithKind (L _ (KindedTyVar _ ki)) nm
= repLKind ki >>= repKindedTV nm
-- represent a type context
--
repLContext :: LHsContext Name -> DsM (Core TH.CxtQ)
repLContext (L _ ctxt) = repContext ctxt
repContext :: HsContext Name -> DsM (Core TH.CxtQ)
repContext ctxt = do
preds <- mapM repLPred ctxt
predList <- coreList predQTyConName preds
repCtxt predList
-- represent a type predicate
--
repLPred :: LHsType Name -> DsM (Core TH.PredQ)
repLPred (L _ p) = repPred p
repPred :: HsType Name -> DsM (Core TH.PredQ)
repPred ty
| Just (cls, tys) <- splitHsClassTy_maybe ty
= do
cls1 <- lookupOcc cls
tys1 <- repLTys tys
tys2 <- coreList typeQTyConName tys1
repClassP cls1 tys2
repPred (HsEqTy tyleft tyright)
= do
tyleft1 <- repLTy tyleft
tyright1 <- repLTy tyright
repEqualP tyleft1 tyright1
repPred ty
= notHandled "Exotic predicate type" (ppr ty)
-- yield the representation of a list of types
--
repLTys :: [LHsType Name] -> DsM [Core TH.TypeQ]
repLTys tys = mapM repLTy tys
-- represent a type
--
repLTy :: LHsType Name -> DsM (Core TH.TypeQ)
repLTy (L _ ty) = repTy ty
repTy :: HsType Name -> DsM (Core TH.TypeQ)
repTy (HsForAllTy _ tvs ctxt ty) =
addTyVarBinds tvs $ \bndrs -> do
ctxt1 <- repLContext ctxt
ty1 <- repLTy ty
repTForall bndrs ctxt1 ty1
repTy (HsTyVar n)
| isTvOcc occ = do tv1 <- lookupOcc n
repTvar tv1
| isDataOcc occ = do tc1 <- lookupOcc n
repPromotedTyCon tc1
| otherwise = do tc1 <- lookupOcc n
repNamedTyCon tc1
where
occ = nameOccName n
repTy (HsAppTy f a) = do
f1 <- repLTy f
a1 <- repLTy a
repTapp f1 a1
repTy (HsFunTy f a) = do
f1 <- repLTy f
a1 <- repLTy a
tcon <- repArrowTyCon
repTapps tcon [f1, a1]
repTy (HsListTy t) = do
t1 <- repLTy t
tcon <- repListTyCon
repTapp tcon t1
repTy (HsPArrTy t) = do
t1 <- repLTy t
tcon <- repTy (HsTyVar (tyConName parrTyCon))
repTapp tcon t1
repTy (HsTupleTy HsUnboxedTuple tys) = do
tys1 <- repLTys tys
tcon <- repUnboxedTupleTyCon (length tys)
repTapps tcon tys1
repTy (HsTupleTy _ tys) = do tys1 <- repLTys tys
tcon <- repTupleTyCon (length tys)
repTapps tcon tys1
repTy (HsOpTy ty1 (_, n) ty2) = repLTy ((nlHsTyVar (unLoc n) `nlHsAppTy` ty1)
`nlHsAppTy` ty2)
repTy (HsParTy t) = repLTy t
repTy (HsKindSig t k) = do
t1 <- repLTy t
k1 <- repLKind k
repTSig t1 k1
repTy (HsSpliceTy splice _ _) = repSplice splice
repTy (HsExplicitListTy _ tys) = do
tys1 <- repLTys tys
repTPromotedList tys1
repTy (HsExplicitTupleTy _ tys) = do
tys1 <- repLTys tys
tcon <- repPromotedTupleTyCon (length tys)
repTapps tcon tys1
repTy (HsTyLit lit) = do
lit' <- repTyLit lit
repTLit lit'
repTy ty = notHandled "Exotic form of type" (ppr ty)
repTyLit :: HsTyLit -> DsM (Core TH.TyLitQ)
repTyLit (HsNumTy i) = rep2 numTyLitName [mkIntExpr i]
repTyLit (HsStrTy s) = do { s' <- mkStringExprFS s
; rep2 strTyLitName [s']
}
-- represent a kind
--
repLKind :: LHsKind Name -> DsM (Core TH.Kind)
repLKind ki
= do { let (kis, ki') = splitHsFunType ki
; kis_rep <- mapM repLKind kis
; ki'_rep <- repNonArrowLKind ki'
; kcon <- repKArrow
; let f k1 k2 = repKApp kcon k1 >>= flip repKApp k2
; foldrM f ki'_rep kis_rep
}
repNonArrowLKind :: LHsKind Name -> DsM (Core TH.Kind)
repNonArrowLKind (L _ ki) = repNonArrowKind ki
repNonArrowKind :: HsKind Name -> DsM (Core TH.Kind)
repNonArrowKind (HsTyVar name)
| name == liftedTypeKindTyConName = repKStar
| name == constraintKindTyConName = repKConstraint
| isTvOcc (nameOccName name) = lookupOcc name >>= repKVar
| otherwise = lookupOcc name >>= repKCon
repNonArrowKind (HsAppTy f a) = do { f' <- repLKind f
; a' <- repLKind a
; repKApp f' a'
}
repNonArrowKind (HsListTy k) = do { k' <- repLKind k
; kcon <- repKList
; repKApp kcon k'
}
repNonArrowKind (HsTupleTy _ ks) = do { ks' <- mapM repLKind ks
; kcon <- repKTuple (length ks)
; repKApps kcon ks'
}
repNonArrowKind k = notHandled "Exotic form of kind" (ppr k)
-----------------------------------------------------------------------------
-- Splices
-----------------------------------------------------------------------------
repSplice :: HsSplice Name -> DsM (Core a)
-- See Note [How brackets and nested splices are handled] in TcSplice
-- We return a CoreExpr of any old type; the context should know
repSplice (HsSplice n _)
= do { mb_val <- dsLookupMetaEnv n
; case mb_val of
Just (Splice e) -> do { e' <- dsExpr e
; return (MkC e') }
_ -> pprPanic "HsSplice" (ppr n) }
-- Should not happen; statically checked
-----------------------------------------------------------------------------
-- Expressions
-----------------------------------------------------------------------------
repLEs :: [LHsExpr Name] -> DsM (Core [TH.ExpQ])
repLEs es = do { es' <- mapM repLE es ;
coreList expQTyConName es' }
-- FIXME: some of these panics should be converted into proper error messages
-- unless we can make sure that constructs, which are plainly not
-- supported in TH already lead to error messages at an earlier stage
repLE :: LHsExpr Name -> DsM (Core TH.ExpQ)
repLE (L loc e) = putSrcSpanDs loc (repE e)
repE :: HsExpr Name -> DsM (Core TH.ExpQ)
repE (HsVar x) =
do { mb_val <- dsLookupMetaEnv x
; case mb_val of
Nothing -> do { str <- globalVar x
; repVarOrCon x str }
Just (Bound y) -> repVarOrCon x (coreVar y)
Just (Splice e) -> do { e' <- dsExpr e
; return (MkC e') } }
repE e@(HsIPVar _) = notHandled "Implicit parameters" (ppr e)
-- Remember, we're desugaring renamer output here, so
-- HsOverlit can definitely occur
repE (HsOverLit l) = do { a <- repOverloadedLiteral l; repLit a }
repE (HsLit l) = do { a <- repLiteral l; repLit a }
repE (HsLam (MatchGroup [m] _)) = repLambda m
repE (HsLamCase _ (MatchGroup ms _))
= do { ms' <- mapM repMatchTup ms
; repLamCase (nonEmptyCoreList ms') }
repE (HsApp x y) = do {a <- repLE x; b <- repLE y; repApp a b}
repE (OpApp e1 op _ e2) =
do { arg1 <- repLE e1;
arg2 <- repLE e2;
the_op <- repLE op ;
repInfixApp arg1 the_op arg2 }
repE (NegApp x _) = do
a <- repLE x
negateVar <- lookupOcc negateName >>= repVar
negateVar `repApp` a
repE (HsPar x) = repLE x
repE (SectionL x y) = do { a <- repLE x; b <- repLE y; repSectionL a b }
repE (SectionR x y) = do { a <- repLE x; b <- repLE y; repSectionR a b }
repE (HsCase e (MatchGroup ms _))
= do { arg <- repLE e
; ms2 <- mapM repMatchTup ms
; repCaseE arg (nonEmptyCoreList ms2) }
repE (HsIf _ x y z) = do
a <- repLE x
b <- repLE y
c <- repLE z
repCond a b c
repE (HsMultiIf _ alts)
= do { (binds, alts') <- liftM unzip $ mapM repLGRHS alts
; expr' <- repMultiIf (nonEmptyCoreList alts')
; wrapGenSyms (concat binds) expr' }
repE (HsLet bs e) = do { (ss,ds) <- repBinds bs
; e2 <- addBinds ss (repLE e)
; z <- repLetE ds e2
; wrapGenSyms ss z }
-- FIXME: I haven't got the types here right yet
repE e@(HsDo ctxt sts _)
| case ctxt of { DoExpr -> True; GhciStmt -> True; _ -> False }
= do { (ss,zs) <- repLSts sts;
e' <- repDoE (nonEmptyCoreList zs);
wrapGenSyms ss e' }
| ListComp <- ctxt
= do { (ss,zs) <- repLSts sts;
e' <- repComp (nonEmptyCoreList zs);
wrapGenSyms ss e' }
| otherwise
= notHandled "mdo, monad comprehension and [: :]" (ppr e)
repE (ExplicitList _ es) = do { xs <- repLEs es; repListExp xs }
repE e@(ExplicitPArr _ _) = notHandled "Parallel arrays" (ppr e)
repE e@(ExplicitTuple es boxed)
| not (all tupArgPresent es) = notHandled "Tuple sections" (ppr e)
| isBoxed boxed = do { xs <- repLEs [e | Present e <- es]; repTup xs }
| otherwise = do { xs <- repLEs [e | Present e <- es]; repUnboxedTup xs }
repE (RecordCon c _ flds)
= do { x <- lookupLOcc c;
fs <- repFields flds;
repRecCon x fs }
repE (RecordUpd e flds _ _ _)
= do { x <- repLE e;
fs <- repFields flds;
repRecUpd x fs }
repE (ExprWithTySig e ty) = do { e1 <- repLE e; t1 <- repLTy ty; repSigExp e1 t1 }
repE (ArithSeq _ aseq) =
case aseq of
From e -> do { ds1 <- repLE e; repFrom ds1 }
FromThen e1 e2 -> do
ds1 <- repLE e1
ds2 <- repLE e2
repFromThen ds1 ds2
FromTo e1 e2 -> do
ds1 <- repLE e1
ds2 <- repLE e2
repFromTo ds1 ds2
FromThenTo e1 e2 e3 -> do
ds1 <- repLE e1
ds2 <- repLE e2
ds3 <- repLE e3
repFromThenTo ds1 ds2 ds3
repE (HsSpliceE splice) = repSplice splice
repE e@(PArrSeq {}) = notHandled "Parallel arrays" (ppr e)
repE e@(HsCoreAnn {}) = notHandled "Core annotations" (ppr e)
repE e@(HsSCC {}) = notHandled "Cost centres" (ppr e)
repE e@(HsTickPragma {}) = notHandled "Tick Pragma" (ppr e)
repE e@(HsBracketOut {}) = notHandled "TH brackets" (ppr e)
repE e = notHandled "Expression form" (ppr e)
-----------------------------------------------------------------------------
-- Building representations of auxillary structures like Match, Clause, Stmt,
repMatchTup :: LMatch Name -> DsM (Core TH.MatchQ)
repMatchTup (L _ (Match [p] _ (GRHSs guards wheres))) =
do { ss1 <- mkGenSyms (collectPatBinders p)
; addBinds ss1 $ do {
; p1 <- repLP p
; (ss2,ds) <- repBinds wheres
; addBinds ss2 $ do {
; gs <- repGuards guards
; match <- repMatch p1 gs ds
; wrapGenSyms (ss1++ss2) match }}}
repMatchTup _ = panic "repMatchTup: case alt with more than one arg"
repClauseTup :: LMatch Name -> DsM (Core TH.ClauseQ)
repClauseTup (L _ (Match ps _ (GRHSs guards wheres))) =
do { ss1 <- mkGenSyms (collectPatsBinders ps)
; addBinds ss1 $ do {
ps1 <- repLPs ps
; (ss2,ds) <- repBinds wheres
; addBinds ss2 $ do {
gs <- repGuards guards
; clause <- repClause ps1 gs ds
; wrapGenSyms (ss1++ss2) clause }}}
repGuards :: [LGRHS Name] -> DsM (Core TH.BodyQ)
repGuards [L _ (GRHS [] e)]
= do { a <- repLE e
; repNormal a }
repGuards alts
= do { (binds, alts') <- liftM unzip $ mapM repLGRHS alts
; body <- repGuarded (nonEmptyCoreList alts')
; wrapGenSyms (concat binds) body }
repLGRHS :: LGRHS Name -> DsM ([GenSymBind], (Core (TH.Q (TH.Guard, TH.Exp))))
repLGRHS (L _ (GRHS [L _ (ExprStmt guard _ _ _)] rhs))
= do { guarded <- repLNormalGE guard rhs
; return ([], guarded) }
repLGRHS (L _ (GRHS stmts rhs))
= do { (gs, stmts') <- repLSts stmts
; rhs' <- addBinds gs $ repLE rhs
; guarded <- repPatGE (nonEmptyCoreList stmts') rhs'
; return (gs, guarded) }
repFields :: HsRecordBinds Name -> DsM (Core [TH.Q TH.FieldExp])
repFields (HsRecFields { rec_flds = flds })
= do { fnames <- mapM lookupLOcc (map hsRecFieldId flds)
; es <- mapM repLE (map hsRecFieldArg flds)
; fs <- zipWithM repFieldExp fnames es
; coreList fieldExpQTyConName fs }
-----------------------------------------------------------------------------
-- Representing Stmt's is tricky, especially if bound variables
-- shadow each other. Consider: [| do { x <- f 1; x <- f x; g x } |]
-- First gensym new names for every variable in any of the patterns.
-- both static (x'1 and x'2), and dynamic ((gensym "x") and (gensym "y"))
-- if variables didn't shaddow, the static gensym wouldn't be necessary
-- and we could reuse the original names (x and x).
--
-- do { x'1 <- gensym "x"
-- ; x'2 <- gensym "x"
-- ; doE [ BindSt (pvar x'1) [| f 1 |]
-- , BindSt (pvar x'2) [| f x |]
-- , NoBindSt [| g x |]
-- ]
-- }
-- The strategy is to translate a whole list of do-bindings by building a
-- bigger environment, and a bigger set of meta bindings
-- (like: x'1 <- gensym "x" ) and then combining these with the translations
-- of the expressions within the Do
-----------------------------------------------------------------------------
-- The helper function repSts computes the translation of each sub expression
-- and a bunch of prefix bindings denoting the dynamic renaming.
repLSts :: [LStmt Name] -> DsM ([GenSymBind], [Core TH.StmtQ])
repLSts stmts = repSts (map unLoc stmts)
repSts :: [Stmt Name] -> DsM ([GenSymBind], [Core TH.StmtQ])
repSts (BindStmt p e _ _ : ss) =
do { e2 <- repLE e
; ss1 <- mkGenSyms (collectPatBinders p)
; addBinds ss1 $ do {
; p1 <- repLP p;
; (ss2,zs) <- repSts ss
; z <- repBindSt p1 e2
; return (ss1++ss2, z : zs) }}
repSts (LetStmt bs : ss) =
do { (ss1,ds) <- repBinds bs
; z <- repLetSt ds
; (ss2,zs) <- addBinds ss1 (repSts ss)
; return (ss1++ss2, z : zs) }
repSts (ExprStmt e _ _ _ : ss) =
do { e2 <- repLE e
; z <- repNoBindSt e2
; (ss2,zs) <- repSts ss
; return (ss2, z : zs) }
repSts [LastStmt e _]
= do { e2 <- repLE e
; z <- repNoBindSt e2
; return ([], [z]) }
repSts [] = return ([],[])
repSts other = notHandled "Exotic statement" (ppr other)
-----------------------------------------------------------
-- Bindings
-----------------------------------------------------------
repBinds :: HsLocalBinds Name -> DsM ([GenSymBind], Core [TH.DecQ])
repBinds EmptyLocalBinds
= do { core_list <- coreList decQTyConName []
; return ([], core_list) }
repBinds b@(HsIPBinds _) = notHandled "Implicit parameters" (ppr b)
repBinds (HsValBinds decs)
= do { let { bndrs = hsSigTvBinders decs ++ collectHsValBinders decs }
-- No need to worrry about detailed scopes within
-- the binding group, because we are talking Names
-- here, so we can safely treat it as a mutually
-- recursive group
-- For hsSigTvBinders see Note [Scoped type variables in bindings]
; ss <- mkGenSyms bndrs
; prs <- addBinds ss (rep_val_binds decs)
; core_list <- coreList decQTyConName
(de_loc (sort_by_loc prs))
; return (ss, core_list) }
rep_val_binds :: HsValBinds Name -> DsM [(SrcSpan, Core TH.DecQ)]
-- Assumes: all the binders of the binding are alrady in the meta-env
rep_val_binds (ValBindsOut binds sigs)
= do { core1 <- rep_binds' (unionManyBags (map snd binds))
; core2 <- rep_sigs' sigs
; return (core1 ++ core2) }
rep_val_binds (ValBindsIn _ _)
= panic "rep_val_binds: ValBindsIn"
rep_binds :: LHsBinds Name -> DsM [Core TH.DecQ]
rep_binds binds = do { binds_w_locs <- rep_binds' binds
; return (de_loc (sort_by_loc binds_w_locs)) }
rep_binds' :: LHsBinds Name -> DsM [(SrcSpan, Core TH.DecQ)]
rep_binds' binds = mapM rep_bind (bagToList binds)
rep_bind :: LHsBind Name -> DsM (SrcSpan, Core TH.DecQ)
-- Assumes: all the binders of the binding are alrady in the meta-env
-- Note GHC treats declarations of a variable (not a pattern)
-- e.g. x = g 5 as a Fun MonoBinds. This is indicated by a single match
-- with an empty list of patterns
rep_bind (L loc (FunBind { fun_id = fn,
fun_matches = MatchGroup [L _ (Match [] _ (GRHSs guards wheres))] _ }))
= do { (ss,wherecore) <- repBinds wheres
; guardcore <- addBinds ss (repGuards guards)
; fn' <- lookupLBinder fn
; p <- repPvar fn'
; ans <- repVal p guardcore wherecore
; ans' <- wrapGenSyms ss ans
; return (loc, ans') }
rep_bind (L loc (FunBind { fun_id = fn, fun_matches = MatchGroup ms _ }))
= do { ms1 <- mapM repClauseTup ms
; fn' <- lookupLBinder fn
; ans <- repFun fn' (nonEmptyCoreList ms1)
; return (loc, ans) }
rep_bind (L loc (PatBind { pat_lhs = pat, pat_rhs = GRHSs guards wheres }))
= do { patcore <- repLP pat
; (ss,wherecore) <- repBinds wheres
; guardcore <- addBinds ss (repGuards guards)
; ans <- repVal patcore guardcore wherecore
; ans' <- wrapGenSyms ss ans
; return (loc, ans') }
rep_bind (L _ (VarBind { var_id = v, var_rhs = e}))
= do { v' <- lookupBinder v
; e2 <- repLE e
; x <- repNormal e2
; patcore <- repPvar v'
; empty_decls <- coreList decQTyConName []
; ans <- repVal patcore x empty_decls
; return (srcLocSpan (getSrcLoc v), ans) }
rep_bind (L _ (AbsBinds {})) = panic "rep_bind: AbsBinds"
-----------------------------------------------------------------------------
-- Since everything in a Bind is mutually recursive we need rename all
-- all the variables simultaneously. For example:
-- [| AndMonoBinds (f x = x + g 2) (g x = f 1 + 2) |] would translate to
-- do { f'1 <- gensym "f"
-- ; g'2 <- gensym "g"
-- ; [ do { x'3 <- gensym "x"; fun f'1 [pvar x'3] [| x + g2 |]},
-- do { x'4 <- gensym "x"; fun g'2 [pvar x'4] [| f 1 + 2 |]}
-- ]}
-- This requires collecting the bindings (f'1 <- gensym "f"), and the
-- environment ( f |-> f'1 ) from each binding, and then unioning them
-- together. As we do this we collect GenSymBinds's which represent the renamed
-- variables bound by the Bindings. In order not to lose track of these
-- representations we build a shadow datatype MB with the same structure as
-- MonoBinds, but which has slots for the representations
-----------------------------------------------------------------------------
-- GHC allows a more general form of lambda abstraction than specified
-- by Haskell 98. In particular it allows guarded lambda's like :
-- (\ x | even x -> 0 | odd x -> 1) at the moment we can't represent this in
-- Haskell Template's Meta.Exp type so we punt if it isn't a simple thing like
-- (\ p1 .. pn -> exp) by causing an error.
repLambda :: LMatch Name -> DsM (Core TH.ExpQ)
repLambda (L _ (Match ps _ (GRHSs [L _ (GRHS [] e)] EmptyLocalBinds)))
= do { let bndrs = collectPatsBinders ps ;
; ss <- mkGenSyms bndrs
; lam <- addBinds ss (
do { xs <- repLPs ps; body <- repLE e; repLam xs body })
; wrapGenSyms ss lam }
repLambda (L _ m) = notHandled "Guarded labmdas" (pprMatch (LambdaExpr :: HsMatchContext Name) m)
-----------------------------------------------------------------------------
-- Patterns
-- repP deals with patterns. It assumes that we have already
-- walked over the pattern(s) once to collect the binders, and
-- have extended the environment. So every pattern-bound
-- variable should already appear in the environment.
-- Process a list of patterns
repLPs :: [LPat Name] -> DsM (Core [TH.PatQ])
repLPs ps = do { ps' <- mapM repLP ps ;
coreList patQTyConName ps' }
repLP :: LPat Name -> DsM (Core TH.PatQ)
repLP (L _ p) = repP p
repP :: Pat Name -> DsM (Core TH.PatQ)
repP (WildPat _) = repPwild
repP (LitPat l) = do { l2 <- repLiteral l; repPlit l2 }
repP (VarPat x) = do { x' <- lookupBinder x; repPvar x' }
repP (LazyPat p) = do { p1 <- repLP p; repPtilde p1 }
repP (BangPat p) = do { p1 <- repLP p; repPbang p1 }
repP (AsPat x p) = do { x' <- lookupLBinder x; p1 <- repLP p; repPaspat x' p1 }
repP (ParPat p) = repLP p
repP (ListPat ps _) = do { qs <- repLPs ps; repPlist qs }
repP (TuplePat ps boxed _)
| isBoxed boxed = do { qs <- repLPs ps; repPtup qs }
| otherwise = do { qs <- repLPs ps; repPunboxedTup qs }
repP (ConPatIn dc details)
= do { con_str <- lookupLOcc dc
; case details of
PrefixCon ps -> do { qs <- repLPs ps; repPcon con_str qs }
RecCon rec -> do { let flds = rec_flds rec
; vs <- sequence $ map lookupLOcc (map hsRecFieldId flds)
; ps <- sequence $ map repLP (map hsRecFieldArg flds)
; fps <- zipWithM (\x y -> rep2 fieldPatName [unC x,unC y]) vs ps
; fps' <- coreList fieldPatQTyConName fps
; repPrec con_str fps' }
InfixCon p1 p2 -> do { p1' <- repLP p1;
p2' <- repLP p2;
repPinfix p1' con_str p2' }
}
repP (NPat l Nothing _) = do { a <- repOverloadedLiteral l; repPlit a }
repP (ViewPat e p _) = do { e' <- repLE e; p' <- repLP p; repPview e' p' }
repP p@(NPat _ (Just _) _) = notHandled "Negative overloaded patterns" (ppr p)
repP p@(SigPatIn {}) = notHandled "Type signatures in patterns" (ppr p)
-- The problem is to do with scoped type variables.
-- To implement them, we have to implement the scoping rules
-- here in DsMeta, and I don't want to do that today!
-- do { p' <- repLP p; t' <- repLTy t; repPsig p' t' }
-- repPsig :: Core TH.PatQ -> Core TH.TypeQ -> DsM (Core TH.PatQ)
-- repPsig (MkC p) (MkC t) = rep2 sigPName [p, t]
repP other = notHandled "Exotic pattern" (ppr other)
----------------------------------------------------------
-- Declaration ordering helpers
sort_by_loc :: [(SrcSpan, a)] -> [(SrcSpan, a)]
sort_by_loc xs = sortBy comp xs
where comp x y = compare (fst x) (fst y)
de_loc :: [(a, b)] -> [b]
de_loc = map snd
----------------------------------------------------------
-- The meta-environment
-- A name/identifier association for fresh names of locally bound entities
type GenSymBind = (Name, Id) -- Gensym the string and bind it to the Id
-- I.e. (x, x_id) means
-- let x_id = gensym "x" in ...
-- Generate a fresh name for a locally bound entity
mkGenSyms :: [Name] -> DsM [GenSymBind]
-- We can use the existing name. For example:
-- [| \x_77 -> x_77 + x_77 |]
-- desugars to
-- do { x_77 <- genSym "x"; .... }
-- We use the same x_77 in the desugared program, but with the type Bndr
-- instead of Int
--
-- We do make it an Internal name, though (hence localiseName)
--
-- Nevertheless, it's monadic because we have to generate nameTy
mkGenSyms ns = do { var_ty <- lookupType nameTyConName
; return [(nm, mkLocalId (localiseName nm) var_ty) | nm <- ns] }
addBinds :: [GenSymBind] -> DsM a -> DsM a
-- Add a list of fresh names for locally bound entities to the
-- meta environment (which is part of the state carried around
-- by the desugarer monad)
addBinds bs m = dsExtendMetaEnv (mkNameEnv [(n,Bound id) | (n,id) <- bs]) m
dupBinder :: (Name, Name) -> DsM (Name, DsMetaVal)
dupBinder (new, old)
= do { mb_val <- dsLookupMetaEnv old
; case mb_val of
Just val -> return (new, val)
Nothing -> pprPanic "dupBinder" (ppr old) }
-- Look up a locally bound name
--
lookupLBinder :: Located Name -> DsM (Core TH.Name)
lookupLBinder (L _ n) = lookupBinder n
lookupBinder :: Name -> DsM (Core TH.Name)
lookupBinder = lookupOcc
-- Binders are brought into scope before the pattern or what-not is
-- desugared. Moreover, in instance declaration the binder of a method
-- will be the selector Id and hence a global; so we need the
-- globalVar case of lookupOcc
-- Look up a name that is either locally bound or a global name
--
-- * If it is a global name, generate the "original name" representation (ie,
-- the <module>:<name> form) for the associated entity
--
lookupLOcc :: Located Name -> DsM (Core TH.Name)
-- Lookup an occurrence; it can't be a splice.
-- Use the in-scope bindings if they exist
lookupLOcc (L _ n) = lookupOcc n
lookupOcc :: Name -> DsM (Core TH.Name)
lookupOcc n
= do { mb_val <- dsLookupMetaEnv n ;
case mb_val of
Nothing -> globalVar n
Just (Bound x) -> return (coreVar x)
Just (Splice _) -> pprPanic "repE:lookupOcc" (ppr n)
}
globalVar :: Name -> DsM (Core TH.Name)
-- Not bound by the meta-env
-- Could be top-level; or could be local
-- f x = $(g [| x |])
-- Here the x will be local
globalVar name
| isExternalName name
= do { MkC mod <- coreStringLit name_mod
; MkC pkg <- coreStringLit name_pkg
; MkC occ <- occNameLit name
; rep2 mk_varg [pkg,mod,occ] }
| otherwise
= do { MkC occ <- occNameLit name
; MkC uni <- coreIntLit (getKey (getUnique name))
; rep2 mkNameLName [occ,uni] }
where
mod = ASSERT( isExternalName name) nameModule name
name_mod = moduleNameString (moduleName mod)
name_pkg = packageIdString (modulePackageId mod)
name_occ = nameOccName name
mk_varg | OccName.isDataOcc name_occ = mkNameG_dName
| OccName.isVarOcc name_occ = mkNameG_vName
| OccName.isTcOcc name_occ = mkNameG_tcName
| otherwise = pprPanic "DsMeta.globalVar" (ppr name)
lookupType :: Name -- Name of type constructor (e.g. TH.ExpQ)
-> DsM Type -- The type
lookupType tc_name = do { tc <- dsLookupTyCon tc_name ;
return (mkTyConApp tc []) }
wrapGenSyms :: [GenSymBind]
-> Core (TH.Q a) -> DsM (Core (TH.Q a))
-- wrapGenSyms [(nm1,id1), (nm2,id2)] y
-- --> bindQ (gensym nm1) (\ id1 ->
-- bindQ (gensym nm2 (\ id2 ->
-- y))
wrapGenSyms binds body@(MkC b)
= do { var_ty <- lookupType nameTyConName
; go var_ty binds }
where
[elt_ty] = tcTyConAppArgs (exprType b)
-- b :: Q a, so we can get the type 'a' by looking at the
-- argument type. NB: this relies on Q being a data/newtype,
-- not a type synonym
go _ [] = return body
go var_ty ((name,id) : binds)
= do { MkC body' <- go var_ty binds
; lit_str <- occNameLit name
; gensym_app <- repGensym lit_str
; repBindQ var_ty elt_ty
gensym_app (MkC (Lam id body')) }
occNameLit :: Name -> DsM (Core String)
occNameLit n = coreStringLit (occNameString (nameOccName n))
-- %*********************************************************************
-- %* *
-- Constructing code
-- %* *
-- %*********************************************************************
-----------------------------------------------------------------------------
-- PHANTOM TYPES for consistency. In order to make sure we do this correct
-- we invent a new datatype which uses phantom types.
newtype Core a = MkC CoreExpr
unC :: Core a -> CoreExpr
unC (MkC x) = x
rep2 :: Name -> [ CoreExpr ] -> DsM (Core a)
rep2 n xs = do { id <- dsLookupGlobalId n
; return (MkC (foldl App (Var id) xs)) }
dataCon' :: Name -> [CoreExpr] -> DsM (Core a)
dataCon' n args = do { id <- dsLookupDataCon n
; return $ MkC $ mkConApp id args }
dataCon :: Name -> DsM (Core a)
dataCon n = dataCon' n []
-- Then we make "repConstructors" which use the phantom types for each of the
-- smart constructors of the Meta.Meta datatypes.
-- %*********************************************************************
-- %* *
-- The 'smart constructors'
-- %* *
-- %*********************************************************************
--------------- Patterns -----------------
repPlit :: Core TH.Lit -> DsM (Core TH.PatQ)
repPlit (MkC l) = rep2 litPName [l]
repPvar :: Core TH.Name -> DsM (Core TH.PatQ)
repPvar (MkC s) = rep2 varPName [s]
repPtup :: Core [TH.PatQ] -> DsM (Core TH.PatQ)
repPtup (MkC ps) = rep2 tupPName [ps]
repPunboxedTup :: Core [TH.PatQ] -> DsM (Core TH.PatQ)
repPunboxedTup (MkC ps) = rep2 unboxedTupPName [ps]
repPcon :: Core TH.Name -> Core [TH.PatQ] -> DsM (Core TH.PatQ)
repPcon (MkC s) (MkC ps) = rep2 conPName [s, ps]
repPrec :: Core TH.Name -> Core [(TH.Name,TH.PatQ)] -> DsM (Core TH.PatQ)
repPrec (MkC c) (MkC rps) = rep2 recPName [c,rps]
repPinfix :: Core TH.PatQ -> Core TH.Name -> Core TH.PatQ -> DsM (Core TH.PatQ)
repPinfix (MkC p1) (MkC n) (MkC p2) = rep2 infixPName [p1, n, p2]
repPtilde :: Core TH.PatQ -> DsM (Core TH.PatQ)
repPtilde (MkC p) = rep2 tildePName [p]
repPbang :: Core TH.PatQ -> DsM (Core TH.PatQ)
repPbang (MkC p) = rep2 bangPName [p]
repPaspat :: Core TH.Name -> Core TH.PatQ -> DsM (Core TH.PatQ)
repPaspat (MkC s) (MkC p) = rep2 asPName [s, p]
repPwild :: DsM (Core TH.PatQ)
repPwild = rep2 wildPName []
repPlist :: Core [TH.PatQ] -> DsM (Core TH.PatQ)
repPlist (MkC ps) = rep2 listPName [ps]
repPview :: Core TH.ExpQ -> Core TH.PatQ -> DsM (Core TH.PatQ)
repPview (MkC e) (MkC p) = rep2 viewPName [e,p]
--------------- Expressions -----------------
repVarOrCon :: Name -> Core TH.Name -> DsM (Core TH.ExpQ)
repVarOrCon vc str | isDataOcc (nameOccName vc) = repCon str
| otherwise = repVar str
repVar :: Core TH.Name -> DsM (Core TH.ExpQ)
repVar (MkC s) = rep2 varEName [s]
repCon :: Core TH.Name -> DsM (Core TH.ExpQ)
repCon (MkC s) = rep2 conEName [s]
repLit :: Core TH.Lit -> DsM (Core TH.ExpQ)
repLit (MkC c) = rep2 litEName [c]
repApp :: Core TH.ExpQ -> Core TH.ExpQ -> DsM (Core TH.ExpQ)
repApp (MkC x) (MkC y) = rep2 appEName [x,y]
repLam :: Core [TH.PatQ] -> Core TH.ExpQ -> DsM (Core TH.ExpQ)
repLam (MkC ps) (MkC e) = rep2 lamEName [ps, e]
repLamCase :: Core [TH.MatchQ] -> DsM (Core TH.ExpQ)
repLamCase (MkC ms) = rep2 lamCaseEName [ms]
repTup :: Core [TH.ExpQ] -> DsM (Core TH.ExpQ)
repTup (MkC es) = rep2 tupEName [es]
repUnboxedTup :: Core [TH.ExpQ] -> DsM (Core TH.ExpQ)
repUnboxedTup (MkC es) = rep2 unboxedTupEName [es]
repCond :: Core TH.ExpQ -> Core TH.ExpQ -> Core TH.ExpQ -> DsM (Core TH.ExpQ)
repCond (MkC x) (MkC y) (MkC z) = rep2 condEName [x,y,z]
repMultiIf :: Core [TH.Q (TH.Guard, TH.Exp)] -> DsM (Core TH.ExpQ)
repMultiIf (MkC alts) = rep2 multiIfEName [alts]
repLetE :: Core [TH.DecQ] -> Core TH.ExpQ -> DsM (Core TH.ExpQ)
repLetE (MkC ds) (MkC e) = rep2 letEName [ds, e]
repCaseE :: Core TH.ExpQ -> Core [TH.MatchQ] -> DsM( Core TH.ExpQ)
repCaseE (MkC e) (MkC ms) = rep2 caseEName [e, ms]
repDoE :: Core [TH.StmtQ] -> DsM (Core TH.ExpQ)
repDoE (MkC ss) = rep2 doEName [ss]
repComp :: Core [TH.StmtQ] -> DsM (Core TH.ExpQ)
repComp (MkC ss) = rep2 compEName [ss]
repListExp :: Core [TH.ExpQ] -> DsM (Core TH.ExpQ)
repListExp (MkC es) = rep2 listEName [es]
repSigExp :: Core TH.ExpQ -> Core TH.TypeQ -> DsM (Core TH.ExpQ)
repSigExp (MkC e) (MkC t) = rep2 sigEName [e,t]
repRecCon :: Core TH.Name -> Core [TH.Q TH.FieldExp]-> DsM (Core TH.ExpQ)
repRecCon (MkC c) (MkC fs) = rep2 recConEName [c,fs]
repRecUpd :: Core TH.ExpQ -> Core [TH.Q TH.FieldExp] -> DsM (Core TH.ExpQ)
repRecUpd (MkC e) (MkC fs) = rep2 recUpdEName [e,fs]
repFieldExp :: Core TH.Name -> Core TH.ExpQ -> DsM (Core (TH.Q TH.FieldExp))
repFieldExp (MkC n) (MkC x) = rep2 fieldExpName [n,x]
repInfixApp :: Core TH.ExpQ -> Core TH.ExpQ -> Core TH.ExpQ -> DsM (Core TH.ExpQ)
repInfixApp (MkC x) (MkC y) (MkC z) = rep2 infixAppName [x,y,z]
repSectionL :: Core TH.ExpQ -> Core TH.ExpQ -> DsM (Core TH.ExpQ)
repSectionL (MkC x) (MkC y) = rep2 sectionLName [x,y]
repSectionR :: Core TH.ExpQ -> Core TH.ExpQ -> DsM (Core TH.ExpQ)
repSectionR (MkC x) (MkC y) = rep2 sectionRName [x,y]
------------ Right hand sides (guarded expressions) ----
repGuarded :: Core [TH.Q (TH.Guard, TH.Exp)] -> DsM (Core TH.BodyQ)
repGuarded (MkC pairs) = rep2 guardedBName [pairs]
repNormal :: Core TH.ExpQ -> DsM (Core TH.BodyQ)
repNormal (MkC e) = rep2 normalBName [e]
------------ Guards ----
repLNormalGE :: LHsExpr Name -> LHsExpr Name -> DsM (Core (TH.Q (TH.Guard, TH.Exp)))
repLNormalGE g e = do g' <- repLE g
e' <- repLE e
repNormalGE g' e'
repNormalGE :: Core TH.ExpQ -> Core TH.ExpQ -> DsM (Core (TH.Q (TH.Guard, TH.Exp)))
repNormalGE (MkC g) (MkC e) = rep2 normalGEName [g, e]
repPatGE :: Core [TH.StmtQ] -> Core TH.ExpQ -> DsM (Core (TH.Q (TH.Guard, TH.Exp)))
repPatGE (MkC ss) (MkC e) = rep2 patGEName [ss, e]
------------- Stmts -------------------
repBindSt :: Core TH.PatQ -> Core TH.ExpQ -> DsM (Core TH.StmtQ)
repBindSt (MkC p) (MkC e) = rep2 bindSName [p,e]
repLetSt :: Core [TH.DecQ] -> DsM (Core TH.StmtQ)
repLetSt (MkC ds) = rep2 letSName [ds]
repNoBindSt :: Core TH.ExpQ -> DsM (Core TH.StmtQ)
repNoBindSt (MkC e) = rep2 noBindSName [e]
-------------- Range (Arithmetic sequences) -----------
repFrom :: Core TH.ExpQ -> DsM (Core TH.ExpQ)
repFrom (MkC x) = rep2 fromEName [x]
repFromThen :: Core TH.ExpQ -> Core TH.ExpQ -> DsM (Core TH.ExpQ)
repFromThen (MkC x) (MkC y) = rep2 fromThenEName [x,y]
repFromTo :: Core TH.ExpQ -> Core TH.ExpQ -> DsM (Core TH.ExpQ)
repFromTo (MkC x) (MkC y) = rep2 fromToEName [x,y]
repFromThenTo :: Core TH.ExpQ -> Core TH.ExpQ -> Core TH.ExpQ -> DsM (Core TH.ExpQ)
repFromThenTo (MkC x) (MkC y) (MkC z) = rep2 fromThenToEName [x,y,z]
------------ Match and Clause Tuples -----------
repMatch :: Core TH.PatQ -> Core TH.BodyQ -> Core [TH.DecQ] -> DsM (Core TH.MatchQ)
repMatch (MkC p) (MkC bod) (MkC ds) = rep2 matchName [p, bod, ds]
repClause :: Core [TH.PatQ] -> Core TH.BodyQ -> Core [TH.DecQ] -> DsM (Core TH.ClauseQ)
repClause (MkC ps) (MkC bod) (MkC ds) = rep2 clauseName [ps, bod, ds]
-------------- Dec -----------------------------
repVal :: Core TH.PatQ -> Core TH.BodyQ -> Core [TH.DecQ] -> DsM (Core TH.DecQ)
repVal (MkC p) (MkC b) (MkC ds) = rep2 valDName [p, b, ds]
repFun :: Core TH.Name -> Core [TH.ClauseQ] -> DsM (Core TH.DecQ)
repFun (MkC nm) (MkC b) = rep2 funDName [nm, b]
repData :: Core TH.CxtQ -> Core TH.Name -> Core [TH.TyVarBndr]
-> Maybe (Core [TH.TypeQ])
-> Core [TH.ConQ] -> Core [TH.Name] -> DsM (Core TH.DecQ)
repData (MkC cxt) (MkC nm) (MkC tvs) Nothing (MkC cons) (MkC derivs)
= rep2 dataDName [cxt, nm, tvs, cons, derivs]
repData (MkC cxt) (MkC nm) (MkC _) (Just (MkC tys)) (MkC cons) (MkC derivs)
= rep2 dataInstDName [cxt, nm, tys, cons, derivs]
repNewtype :: Core TH.CxtQ -> Core TH.Name -> Core [TH.TyVarBndr]
-> Maybe (Core [TH.TypeQ])
-> Core TH.ConQ -> Core [TH.Name] -> DsM (Core TH.DecQ)
repNewtype (MkC cxt) (MkC nm) (MkC tvs) Nothing (MkC con) (MkC derivs)
= rep2 newtypeDName [cxt, nm, tvs, con, derivs]
repNewtype (MkC cxt) (MkC nm) (MkC _) (Just (MkC tys)) (MkC con) (MkC derivs)
= rep2 newtypeInstDName [cxt, nm, tys, con, derivs]
repTySyn :: Core TH.Name -> Core [TH.TyVarBndr]
-> Maybe (Core [TH.TypeQ])
-> Core TH.TypeQ -> DsM (Core TH.DecQ)
repTySyn (MkC nm) (MkC tvs) Nothing (MkC rhs)
= rep2 tySynDName [nm, tvs, rhs]
repTySyn (MkC nm) (MkC _) (Just (MkC tys)) (MkC rhs)
= rep2 tySynInstDName [nm, tys, rhs]
repInst :: Core TH.CxtQ -> Core TH.TypeQ -> Core [TH.DecQ] -> DsM (Core TH.DecQ)
repInst (MkC cxt) (MkC ty) (MkC ds) = rep2 instanceDName [cxt, ty, ds]
repClass :: Core TH.CxtQ -> Core TH.Name -> Core [TH.TyVarBndr]
-> Core [TH.FunDep] -> Core [TH.DecQ]
-> DsM (Core TH.DecQ)
repClass (MkC cxt) (MkC cls) (MkC tvs) (MkC fds) (MkC ds)
= rep2 classDName [cxt, cls, tvs, fds, ds]
repPragInl :: Core TH.Name -> Core TH.Inline -> Core TH.RuleMatch
-> Core TH.Phases -> DsM (Core TH.DecQ)
repPragInl (MkC nm) (MkC inline) (MkC rm) (MkC phases)
= rep2 pragInlDName [nm, inline, rm, phases]
repPragSpec :: Core TH.Name -> Core TH.TypeQ -> Core TH.Phases
-> DsM (Core TH.DecQ)
repPragSpec (MkC nm) (MkC ty) (MkC phases)
= rep2 pragSpecDName [nm, ty, phases]
repPragSpecInl :: Core TH.Name -> Core TH.TypeQ -> Core TH.Inline
-> Core TH.Phases -> DsM (Core TH.DecQ)
repPragSpecInl (MkC nm) (MkC ty) (MkC inline) (MkC phases)
= rep2 pragSpecInlDName [nm, ty, inline, phases]
repPragSpecInst :: Core TH.TypeQ -> DsM (Core TH.DecQ)
repPragSpecInst (MkC ty) = rep2 pragSpecInstDName [ty]
repPragRule :: Core String -> Core [TH.RuleBndrQ] -> Core TH.ExpQ
-> Core TH.ExpQ -> Core TH.Phases -> DsM (Core TH.DecQ)
repPragRule (MkC nm) (MkC bndrs) (MkC lhs) (MkC rhs) (MkC phases)
= rep2 pragRuleDName [nm, bndrs, lhs, rhs, phases]
repFamilyNoKind :: Core TH.FamFlavour -> Core TH.Name -> Core [TH.TyVarBndr]
-> DsM (Core TH.DecQ)
repFamilyNoKind (MkC flav) (MkC nm) (MkC tvs)
= rep2 familyNoKindDName [flav, nm, tvs]
repFamilyKind :: Core TH.FamFlavour -> Core TH.Name -> Core [TH.TyVarBndr]
-> Core TH.Kind
-> DsM (Core TH.DecQ)
repFamilyKind (MkC flav) (MkC nm) (MkC tvs) (MkC ki)
= rep2 familyKindDName [flav, nm, tvs, ki]
repFunDep :: Core [TH.Name] -> Core [TH.Name] -> DsM (Core TH.FunDep)
repFunDep (MkC xs) (MkC ys) = rep2 funDepName [xs, ys]
repProto :: Core TH.Name -> Core TH.TypeQ -> DsM (Core TH.DecQ)
repProto (MkC s) (MkC ty) = rep2 sigDName [s, ty]
repCtxt :: Core [TH.PredQ] -> DsM (Core TH.CxtQ)
repCtxt (MkC tys) = rep2 cxtName [tys]
repClassP :: Core TH.Name -> Core [TH.TypeQ] -> DsM (Core TH.PredQ)
repClassP (MkC cla) (MkC tys) = rep2 classPName [cla, tys]
repEqualP :: Core TH.TypeQ -> Core TH.TypeQ -> DsM (Core TH.PredQ)
repEqualP (MkC ty1) (MkC ty2) = rep2 equalPName [ty1, ty2]
repConstr :: Core TH.Name -> HsConDeclDetails Name
-> DsM (Core TH.ConQ)
repConstr con (PrefixCon ps)
= do arg_tys <- mapM repBangTy ps
arg_tys1 <- coreList strictTypeQTyConName arg_tys
rep2 normalCName [unC con, unC arg_tys1]
repConstr con (RecCon ips)
= do arg_vs <- mapM lookupLOcc (map cd_fld_name ips)
arg_tys <- mapM repBangTy (map cd_fld_type ips)
arg_vtys <- zipWithM (\x y -> rep2 varStrictTypeName [unC x, unC y])
arg_vs arg_tys
arg_vtys' <- coreList varStrictTypeQTyConName arg_vtys
rep2 recCName [unC con, unC arg_vtys']
repConstr con (InfixCon st1 st2)
= do arg1 <- repBangTy st1
arg2 <- repBangTy st2
rep2 infixCName [unC arg1, unC con, unC arg2]
------------ Types -------------------
repTForall :: Core [TH.TyVarBndr] -> Core TH.CxtQ -> Core TH.TypeQ
-> DsM (Core TH.TypeQ)
repTForall (MkC tvars) (MkC ctxt) (MkC ty)
= rep2 forallTName [tvars, ctxt, ty]
repTvar :: Core TH.Name -> DsM (Core TH.TypeQ)
repTvar (MkC s) = rep2 varTName [s]
repTapp :: Core TH.TypeQ -> Core TH.TypeQ -> DsM (Core TH.TypeQ)
repTapp (MkC t1) (MkC t2) = rep2 appTName [t1, t2]
repTapps :: Core TH.TypeQ -> [Core TH.TypeQ] -> DsM (Core TH.TypeQ)
repTapps f [] = return f
repTapps f (t:ts) = do { f1 <- repTapp f t; repTapps f1 ts }
repTSig :: Core TH.TypeQ -> Core TH.Kind -> DsM (Core TH.TypeQ)
repTSig (MkC ty) (MkC ki) = rep2 sigTName [ty, ki]
repTPromotedList :: [Core TH.TypeQ] -> DsM (Core TH.TypeQ)
repTPromotedList [] = repPromotedNilTyCon
repTPromotedList (t:ts) = do { tcon <- repPromotedConsTyCon
; f <- repTapp tcon t
; t' <- repTPromotedList ts
; repTapp f t'
}
repTLit :: Core TH.TyLitQ -> DsM (Core TH.TypeQ)
repTLit (MkC lit) = rep2 litTName [lit]
--------- Type constructors --------------
repNamedTyCon :: Core TH.Name -> DsM (Core TH.TypeQ)
repNamedTyCon (MkC s) = rep2 conTName [s]
repTupleTyCon :: Int -> DsM (Core TH.TypeQ)
-- Note: not Core Int; it's easier to be direct here
repTupleTyCon i = rep2 tupleTName [mkIntExprInt i]
repUnboxedTupleTyCon :: Int -> DsM (Core TH.TypeQ)
-- Note: not Core Int; it's easier to be direct here
repUnboxedTupleTyCon i = rep2 unboxedTupleTName [mkIntExprInt i]
repArrowTyCon :: DsM (Core TH.TypeQ)
repArrowTyCon = rep2 arrowTName []
repListTyCon :: DsM (Core TH.TypeQ)
repListTyCon = rep2 listTName []
repPromotedTyCon :: Core TH.Name -> DsM (Core TH.TypeQ)
repPromotedTyCon (MkC s) = rep2 promotedTName [s]
repPromotedTupleTyCon :: Int -> DsM (Core TH.TypeQ)
repPromotedTupleTyCon i = rep2 promotedTupleTName [mkIntExprInt i]
repPromotedNilTyCon :: DsM (Core TH.TypeQ)
repPromotedNilTyCon = rep2 promotedNilTName []
repPromotedConsTyCon :: DsM (Core TH.TypeQ)
repPromotedConsTyCon = rep2 promotedConsTName []
------------ Kinds -------------------
repPlainTV :: Core TH.Name -> DsM (Core TH.TyVarBndr)
repPlainTV (MkC nm) = rep2 plainTVName [nm]
repKindedTV :: Core TH.Name -> Core TH.Kind -> DsM (Core TH.TyVarBndr)
repKindedTV (MkC nm) (MkC ki) = rep2 kindedTVName [nm, ki]
repKVar :: Core TH.Name -> DsM (Core TH.Kind)
repKVar (MkC s) = rep2 varKName [s]
repKCon :: Core TH.Name -> DsM (Core TH.Kind)
repKCon (MkC s) = rep2 conKName [s]
repKTuple :: Int -> DsM (Core TH.Kind)
repKTuple i = rep2 tupleKName [mkIntExprInt i]
repKArrow :: DsM (Core TH.Kind)
repKArrow = rep2 arrowKName []
repKList :: DsM (Core TH.Kind)
repKList = rep2 listKName []
repKApp :: Core TH.Kind -> Core TH.Kind -> DsM (Core TH.Kind)
repKApp (MkC k1) (MkC k2) = rep2 appKName [k1, k2]
repKApps :: Core TH.Kind -> [Core TH.Kind] -> DsM (Core TH.Kind)
repKApps f [] = return f
repKApps f (k:ks) = do { f' <- repKApp f k; repKApps f' ks }
repKStar :: DsM (Core TH.Kind)
repKStar = rep2 starKName []
repKConstraint :: DsM (Core TH.Kind)
repKConstraint = rep2 constraintKName []
----------------------------------------------------------
-- Literals
repLiteral :: HsLit -> DsM (Core TH.Lit)
repLiteral lit
= do lit' <- case lit of
HsIntPrim i -> mk_integer i
HsWordPrim w -> mk_integer w
HsInt i -> mk_integer i
HsFloatPrim r -> mk_rational r
HsDoublePrim r -> mk_rational r
_ -> return lit
lit_expr <- dsLit lit'
case mb_lit_name of
Just lit_name -> rep2 lit_name [lit_expr]
Nothing -> notHandled "Exotic literal" (ppr lit)
where
mb_lit_name = case lit of
HsInteger _ _ -> Just integerLName
HsInt _ -> Just integerLName
HsIntPrim _ -> Just intPrimLName
HsWordPrim _ -> Just wordPrimLName
HsFloatPrim _ -> Just floatPrimLName
HsDoublePrim _ -> Just doublePrimLName
HsChar _ -> Just charLName
HsString _ -> Just stringLName
HsRat _ _ -> Just rationalLName
_ -> Nothing
mk_integer :: Integer -> DsM HsLit
mk_integer i = do integer_ty <- lookupType integerTyConName
return $ HsInteger i integer_ty
mk_rational :: FractionalLit -> DsM HsLit
mk_rational r = do rat_ty <- lookupType rationalTyConName
return $ HsRat r rat_ty
mk_string :: FastString -> DsM HsLit
mk_string s = return $ HsString s
repOverloadedLiteral :: HsOverLit Name -> DsM (Core TH.Lit)
repOverloadedLiteral (OverLit { ol_val = val})
= do { lit <- mk_lit val; repLiteral lit }
-- The type Rational will be in the environment, becuase
-- the smart constructor 'TH.Syntax.rationalL' uses it in its type,
-- and rationalL is sucked in when any TH stuff is used
mk_lit :: OverLitVal -> DsM HsLit
mk_lit (HsIntegral i) = mk_integer i
mk_lit (HsFractional f) = mk_rational f
mk_lit (HsIsString s) = mk_string s
--------------- Miscellaneous -------------------
repGensym :: Core String -> DsM (Core (TH.Q TH.Name))
repGensym (MkC lit_str) = rep2 newNameName [lit_str]
repBindQ :: Type -> Type -- a and b
-> Core (TH.Q a) -> Core (a -> TH.Q b) -> DsM (Core (TH.Q b))
repBindQ ty_a ty_b (MkC x) (MkC y)
= rep2 bindQName [Type ty_a, Type ty_b, x, y]
repSequenceQ :: Type -> Core [TH.Q a] -> DsM (Core (TH.Q [a]))
repSequenceQ ty_a (MkC list)
= rep2 sequenceQName [Type ty_a, list]
------------ Lists and Tuples -------------------
-- turn a list of patterns into a single pattern matching a list
coreList :: Name -- Of the TyCon of the element type
-> [Core a] -> DsM (Core [a])
coreList tc_name es
= do { elt_ty <- lookupType tc_name; return (coreList' elt_ty es) }
coreList' :: Type -- The element type
-> [Core a] -> Core [a]
coreList' elt_ty es = MkC (mkListExpr elt_ty (map unC es ))
nonEmptyCoreList :: [Core a] -> Core [a]
-- The list must be non-empty so we can get the element type
-- Otherwise use coreList
nonEmptyCoreList [] = panic "coreList: empty argument"
nonEmptyCoreList xs@(MkC x:_) = MkC (mkListExpr (exprType x) (map unC xs))
coreStringLit :: String -> DsM (Core String)
coreStringLit s = do { z <- mkStringExpr s; return(MkC z) }
------------ Literals & Variables -------------------
coreIntLit :: Int -> DsM (Core Int)
coreIntLit i = return (MkC (mkIntExprInt i))
coreVar :: Id -> Core TH.Name -- The Id has type Name
coreVar id = MkC (Var id)
----------------- Failure -----------------------
notHandled :: String -> SDoc -> DsM a
notHandled what doc = failWithDs msg
where
msg = hang (text what <+> ptext (sLit "not (yet) handled by Template Haskell"))
2 doc
-- %************************************************************************
-- %* *
-- The known-key names for Template Haskell
-- %* *
-- %************************************************************************
-- To add a name, do three things
--
-- 1) Allocate a key
-- 2) Make a "Name"
-- 3) Add the name to knownKeyNames
templateHaskellNames :: [Name]
-- The names that are implicitly mentioned by ``bracket''
-- Should stay in sync with the import list of DsMeta
templateHaskellNames = [
returnQName, bindQName, sequenceQName, newNameName, liftName,
mkNameName, mkNameG_vName, mkNameG_dName, mkNameG_tcName, mkNameLName,
liftStringName,
-- Lit
charLName, stringLName, integerLName, intPrimLName, wordPrimLName,
floatPrimLName, doublePrimLName, rationalLName,
-- Pat
litPName, varPName, tupPName, unboxedTupPName,
conPName, tildePName, bangPName, infixPName,
asPName, wildPName, recPName, listPName, sigPName, viewPName,
-- FieldPat
fieldPatName,
-- Match
matchName,
-- Clause
clauseName,
-- Exp
varEName, conEName, litEName, appEName, infixEName,
infixAppName, sectionLName, sectionRName, lamEName, lamCaseEName,
tupEName, unboxedTupEName,
condEName, multiIfEName, letEName, caseEName, doEName, compEName,
fromEName, fromThenEName, fromToEName, fromThenToEName,
listEName, sigEName, recConEName, recUpdEName,
-- FieldExp
fieldExpName,
-- Body
guardedBName, normalBName,
-- Guard
normalGEName, patGEName,
-- Stmt
bindSName, letSName, noBindSName, parSName,
-- Dec
funDName, valDName, dataDName, newtypeDName, tySynDName,
classDName, instanceDName, sigDName, forImpDName,
pragInlDName, pragSpecDName, pragSpecInlDName, pragSpecInstDName,
pragRuleDName,
familyNoKindDName, familyKindDName, dataInstDName, newtypeInstDName,
tySynInstDName, infixLDName, infixRDName, infixNDName,
-- Cxt
cxtName,
-- Pred
classPName, equalPName,
-- Strict
isStrictName, notStrictName, unpackedName,
-- Con
normalCName, recCName, infixCName, forallCName,
-- StrictType
strictTypeName,
-- VarStrictType
varStrictTypeName,
-- Type
forallTName, varTName, conTName, appTName,
tupleTName, unboxedTupleTName, arrowTName, listTName, sigTName, litTName,
promotedTName, promotedTupleTName, promotedNilTName, promotedConsTName,
-- TyLit
numTyLitName, strTyLitName,
-- TyVarBndr
plainTVName, kindedTVName,
-- Kind
varKName, conKName, tupleKName, arrowKName, listKName, appKName,
starKName, constraintKName,
-- Callconv
cCallName, stdCallName,
-- Safety
unsafeName,
safeName,
interruptibleName,
-- Inline
noInlineDataConName, inlineDataConName, inlinableDataConName,
-- RuleMatch
conLikeDataConName, funLikeDataConName,
-- Phases
allPhasesDataConName, fromPhaseDataConName, beforePhaseDataConName,
-- RuleBndr
ruleVarName, typedRuleVarName,
-- FunDep
funDepName,
-- FamFlavour
typeFamName, dataFamName,
-- And the tycons
qTyConName, nameTyConName, patTyConName, fieldPatTyConName, matchQTyConName,
clauseQTyConName, expQTyConName, fieldExpTyConName, predTyConName,
stmtQTyConName, decQTyConName, conQTyConName, strictTypeQTyConName,
varStrictTypeQTyConName, typeQTyConName, expTyConName, decTyConName,
typeTyConName, tyVarBndrTyConName, matchTyConName, clauseTyConName,
patQTyConName, fieldPatQTyConName, fieldExpQTyConName, funDepTyConName,
predQTyConName, decsQTyConName, ruleBndrQTyConName,
-- Quasiquoting
quoteDecName, quoteTypeName, quoteExpName, quotePatName]
thSyn, thLib, qqLib :: Module
thSyn = mkTHModule (fsLit "Language.Haskell.TH.Syntax")
thLib = mkTHModule (fsLit "Language.Haskell.TH.Lib")
qqLib = mkTHModule (fsLit "Language.Haskell.TH.Quote")
mkTHModule :: FastString -> Module
mkTHModule m = mkModule thPackageId (mkModuleNameFS m)
libFun, libTc, thFun, thTc, thCon, qqFun :: FastString -> Unique -> Name
libFun = mk_known_key_name OccName.varName thLib
libTc = mk_known_key_name OccName.tcName thLib
thFun = mk_known_key_name OccName.varName thSyn
thTc = mk_known_key_name OccName.tcName thSyn
thCon = mk_known_key_name OccName.dataName thSyn
qqFun = mk_known_key_name OccName.varName qqLib
-------------------- TH.Syntax -----------------------
qTyConName, nameTyConName, fieldExpTyConName, patTyConName,
fieldPatTyConName, expTyConName, decTyConName, typeTyConName,
tyVarBndrTyConName, matchTyConName, clauseTyConName, funDepTyConName,
predTyConName :: Name
qTyConName = thTc (fsLit "Q") qTyConKey
nameTyConName = thTc (fsLit "Name") nameTyConKey
fieldExpTyConName = thTc (fsLit "FieldExp") fieldExpTyConKey
patTyConName = thTc (fsLit "Pat") patTyConKey
fieldPatTyConName = thTc (fsLit "FieldPat") fieldPatTyConKey
expTyConName = thTc (fsLit "Exp") expTyConKey
decTyConName = thTc (fsLit "Dec") decTyConKey
typeTyConName = thTc (fsLit "Type") typeTyConKey
tyVarBndrTyConName= thTc (fsLit "TyVarBndr") tyVarBndrTyConKey
matchTyConName = thTc (fsLit "Match") matchTyConKey
clauseTyConName = thTc (fsLit "Clause") clauseTyConKey
funDepTyConName = thTc (fsLit "FunDep") funDepTyConKey
predTyConName = thTc (fsLit "Pred") predTyConKey
returnQName, bindQName, sequenceQName, newNameName, liftName,
mkNameName, mkNameG_vName, mkNameG_dName, mkNameG_tcName,
mkNameLName, liftStringName :: Name
returnQName = thFun (fsLit "returnQ") returnQIdKey
bindQName = thFun (fsLit "bindQ") bindQIdKey
sequenceQName = thFun (fsLit "sequenceQ") sequenceQIdKey
newNameName = thFun (fsLit "newName") newNameIdKey
liftName = thFun (fsLit "lift") liftIdKey
liftStringName = thFun (fsLit "liftString") liftStringIdKey
mkNameName = thFun (fsLit "mkName") mkNameIdKey
mkNameG_vName = thFun (fsLit "mkNameG_v") mkNameG_vIdKey
mkNameG_dName = thFun (fsLit "mkNameG_d") mkNameG_dIdKey
mkNameG_tcName = thFun (fsLit "mkNameG_tc") mkNameG_tcIdKey
mkNameLName = thFun (fsLit "mkNameL") mkNameLIdKey
-------------------- TH.Lib -----------------------
-- data Lit = ...
charLName, stringLName, integerLName, intPrimLName, wordPrimLName,
floatPrimLName, doublePrimLName, rationalLName :: Name
charLName = libFun (fsLit "charL") charLIdKey
stringLName = libFun (fsLit "stringL") stringLIdKey
integerLName = libFun (fsLit "integerL") integerLIdKey
intPrimLName = libFun (fsLit "intPrimL") intPrimLIdKey
wordPrimLName = libFun (fsLit "wordPrimL") wordPrimLIdKey
floatPrimLName = libFun (fsLit "floatPrimL") floatPrimLIdKey
doublePrimLName = libFun (fsLit "doublePrimL") doublePrimLIdKey
rationalLName = libFun (fsLit "rationalL") rationalLIdKey
-- data Pat = ...
litPName, varPName, tupPName, unboxedTupPName, conPName, infixPName, tildePName, bangPName,
asPName, wildPName, recPName, listPName, sigPName, viewPName :: Name
litPName = libFun (fsLit "litP") litPIdKey
varPName = libFun (fsLit "varP") varPIdKey
tupPName = libFun (fsLit "tupP") tupPIdKey
unboxedTupPName = libFun (fsLit "unboxedTupP") unboxedTupPIdKey
conPName = libFun (fsLit "conP") conPIdKey
infixPName = libFun (fsLit "infixP") infixPIdKey
tildePName = libFun (fsLit "tildeP") tildePIdKey
bangPName = libFun (fsLit "bangP") bangPIdKey
asPName = libFun (fsLit "asP") asPIdKey
wildPName = libFun (fsLit "wildP") wildPIdKey
recPName = libFun (fsLit "recP") recPIdKey
listPName = libFun (fsLit "listP") listPIdKey
sigPName = libFun (fsLit "sigP") sigPIdKey
viewPName = libFun (fsLit "viewP") viewPIdKey
-- type FieldPat = ...
fieldPatName :: Name
fieldPatName = libFun (fsLit "fieldPat") fieldPatIdKey
-- data Match = ...
matchName :: Name
matchName = libFun (fsLit "match") matchIdKey
-- data Clause = ...
clauseName :: Name
clauseName = libFun (fsLit "clause") clauseIdKey
-- data Exp = ...
varEName, conEName, litEName, appEName, infixEName, infixAppName,
sectionLName, sectionRName, lamEName, lamCaseEName, tupEName,
unboxedTupEName, condEName, multiIfEName, letEName, caseEName,
doEName, compEName :: Name
varEName = libFun (fsLit "varE") varEIdKey
conEName = libFun (fsLit "conE") conEIdKey
litEName = libFun (fsLit "litE") litEIdKey
appEName = libFun (fsLit "appE") appEIdKey
infixEName = libFun (fsLit "infixE") infixEIdKey
infixAppName = libFun (fsLit "infixApp") infixAppIdKey
sectionLName = libFun (fsLit "sectionL") sectionLIdKey
sectionRName = libFun (fsLit "sectionR") sectionRIdKey
lamEName = libFun (fsLit "lamE") lamEIdKey
lamCaseEName = libFun (fsLit "lamCaseE") lamCaseEIdKey
tupEName = libFun (fsLit "tupE") tupEIdKey
unboxedTupEName = libFun (fsLit "unboxedTupE") unboxedTupEIdKey
condEName = libFun (fsLit "condE") condEIdKey
multiIfEName = libFun (fsLit "multiIfE") multiIfEIdKey
letEName = libFun (fsLit "letE") letEIdKey
caseEName = libFun (fsLit "caseE") caseEIdKey
doEName = libFun (fsLit "doE") doEIdKey
compEName = libFun (fsLit "compE") compEIdKey
-- ArithSeq skips a level
fromEName, fromThenEName, fromToEName, fromThenToEName :: Name
fromEName = libFun (fsLit "fromE") fromEIdKey
fromThenEName = libFun (fsLit "fromThenE") fromThenEIdKey
fromToEName = libFun (fsLit "fromToE") fromToEIdKey
fromThenToEName = libFun (fsLit "fromThenToE") fromThenToEIdKey
-- end ArithSeq
listEName, sigEName, recConEName, recUpdEName :: Name
listEName = libFun (fsLit "listE") listEIdKey
sigEName = libFun (fsLit "sigE") sigEIdKey
recConEName = libFun (fsLit "recConE") recConEIdKey
recUpdEName = libFun (fsLit "recUpdE") recUpdEIdKey
-- type FieldExp = ...
fieldExpName :: Name
fieldExpName = libFun (fsLit "fieldExp") fieldExpIdKey
-- data Body = ...
guardedBName, normalBName :: Name
guardedBName = libFun (fsLit "guardedB") guardedBIdKey
normalBName = libFun (fsLit "normalB") normalBIdKey
-- data Guard = ...
normalGEName, patGEName :: Name
normalGEName = libFun (fsLit "normalGE") normalGEIdKey
patGEName = libFun (fsLit "patGE") patGEIdKey
-- data Stmt = ...
bindSName, letSName, noBindSName, parSName :: Name
bindSName = libFun (fsLit "bindS") bindSIdKey
letSName = libFun (fsLit "letS") letSIdKey
noBindSName = libFun (fsLit "noBindS") noBindSIdKey
parSName = libFun (fsLit "parS") parSIdKey
-- data Dec = ...
funDName, valDName, dataDName, newtypeDName, tySynDName, classDName,
instanceDName, sigDName, forImpDName, pragInlDName, pragSpecDName,
pragSpecInlDName, pragSpecInstDName, pragRuleDName, familyNoKindDName,
familyKindDName, dataInstDName, newtypeInstDName, tySynInstDName,
infixLDName, infixRDName, infixNDName :: Name
funDName = libFun (fsLit "funD") funDIdKey
valDName = libFun (fsLit "valD") valDIdKey
dataDName = libFun (fsLit "dataD") dataDIdKey
newtypeDName = libFun (fsLit "newtypeD") newtypeDIdKey
tySynDName = libFun (fsLit "tySynD") tySynDIdKey
classDName = libFun (fsLit "classD") classDIdKey
instanceDName = libFun (fsLit "instanceD") instanceDIdKey
sigDName = libFun (fsLit "sigD") sigDIdKey
forImpDName = libFun (fsLit "forImpD") forImpDIdKey
pragInlDName = libFun (fsLit "pragInlD") pragInlDIdKey
pragSpecDName = libFun (fsLit "pragSpecD") pragSpecDIdKey
pragSpecInlDName = libFun (fsLit "pragSpecInlD") pragSpecInlDIdKey
pragSpecInstDName = libFun (fsLit "pragSpecInstD") pragSpecInstDIdKey
pragRuleDName = libFun (fsLit "pragRuleD") pragRuleDIdKey
familyNoKindDName = libFun (fsLit "familyNoKindD") familyNoKindDIdKey
familyKindDName = libFun (fsLit "familyKindD") familyKindDIdKey
dataInstDName = libFun (fsLit "dataInstD") dataInstDIdKey
newtypeInstDName = libFun (fsLit "newtypeInstD") newtypeInstDIdKey
tySynInstDName = libFun (fsLit "tySynInstD") tySynInstDIdKey
infixLDName = libFun (fsLit "infixLD") infixLDIdKey
infixRDName = libFun (fsLit "infixRD") infixRDIdKey
infixNDName = libFun (fsLit "infixND") infixNDIdKey
-- type Ctxt = ...
cxtName :: Name
cxtName = libFun (fsLit "cxt") cxtIdKey
-- data Pred = ...
classPName, equalPName :: Name
classPName = libFun (fsLit "classP") classPIdKey
equalPName = libFun (fsLit "equalP") equalPIdKey
-- data Strict = ...
isStrictName, notStrictName, unpackedName :: Name
isStrictName = libFun (fsLit "isStrict") isStrictKey
notStrictName = libFun (fsLit "notStrict") notStrictKey
unpackedName = libFun (fsLit "unpacked") unpackedKey
-- data Con = ...
normalCName, recCName, infixCName, forallCName :: Name
normalCName = libFun (fsLit "normalC") normalCIdKey
recCName = libFun (fsLit "recC") recCIdKey
infixCName = libFun (fsLit "infixC") infixCIdKey
forallCName = libFun (fsLit "forallC") forallCIdKey
-- type StrictType = ...
strictTypeName :: Name
strictTypeName = libFun (fsLit "strictType") strictTKey
-- type VarStrictType = ...
varStrictTypeName :: Name
varStrictTypeName = libFun (fsLit "varStrictType") varStrictTKey
-- data Type = ...
forallTName, varTName, conTName, tupleTName, unboxedTupleTName, arrowTName,
listTName, appTName, sigTName, litTName,
promotedTName, promotedTupleTName,
promotedNilTName, promotedConsTName :: Name
forallTName = libFun (fsLit "forallT") forallTIdKey
varTName = libFun (fsLit "varT") varTIdKey
conTName = libFun (fsLit "conT") conTIdKey
tupleTName = libFun (fsLit "tupleT") tupleTIdKey
unboxedTupleTName = libFun (fsLit "unboxedTupleT") unboxedTupleTIdKey
arrowTName = libFun (fsLit "arrowT") arrowTIdKey
listTName = libFun (fsLit "listT") listTIdKey
appTName = libFun (fsLit "appT") appTIdKey
sigTName = libFun (fsLit "sigT") sigTIdKey
litTName = libFun (fsLit "litT") litTIdKey
promotedTName = libFun (fsLit "promotedT") promotedTIdKey
promotedTupleTName = libFun (fsLit "promotedTupleT") promotedTupleTIdKey
promotedNilTName = libFun (fsLit "promotedNilT") promotedNilTIdKey
promotedConsTName = libFun (fsLit "promotedConsT") promotedConsTIdKey
-- data TyLit = ...
numTyLitName, strTyLitName :: Name
numTyLitName = libFun (fsLit "numTyLit") numTyLitIdKey
strTyLitName = libFun (fsLit "strTyLit") strTyLitIdKey
-- data TyVarBndr = ...
plainTVName, kindedTVName :: Name
plainTVName = libFun (fsLit "plainTV") plainTVIdKey
kindedTVName = libFun (fsLit "kindedTV") kindedTVIdKey
-- data Kind = ...
varKName, conKName, tupleKName, arrowKName, listKName, appKName,
starKName, constraintKName :: Name
varKName = libFun (fsLit "varK") varKIdKey
conKName = libFun (fsLit "conK") conKIdKey
tupleKName = libFun (fsLit "tupleK") tupleKIdKey
arrowKName = libFun (fsLit "arrowK") arrowKIdKey
listKName = libFun (fsLit "listK") listKIdKey
appKName = libFun (fsLit "appK") appKIdKey
starKName = libFun (fsLit "starK") starKIdKey
constraintKName = libFun (fsLit "constraintK") constraintKIdKey
-- data Callconv = ...
cCallName, stdCallName :: Name
cCallName = libFun (fsLit "cCall") cCallIdKey
stdCallName = libFun (fsLit "stdCall") stdCallIdKey
-- data Safety = ...
unsafeName, safeName, interruptibleName :: Name
unsafeName = libFun (fsLit "unsafe") unsafeIdKey
safeName = libFun (fsLit "safe") safeIdKey
interruptibleName = libFun (fsLit "interruptible") interruptibleIdKey
-- data Inline = ...
noInlineDataConName, inlineDataConName, inlinableDataConName :: Name
noInlineDataConName = thCon (fsLit "NoInline") noInlineDataConKey
inlineDataConName = thCon (fsLit "Inline") inlineDataConKey
inlinableDataConName = thCon (fsLit "Inlinable") inlinableDataConKey
-- data RuleMatch = ...
conLikeDataConName, funLikeDataConName :: Name
conLikeDataConName = thCon (fsLit "ConLike") conLikeDataConKey
funLikeDataConName = thCon (fsLit "FunLike") funLikeDataConKey
-- data Phases = ...
allPhasesDataConName, fromPhaseDataConName, beforePhaseDataConName :: Name
allPhasesDataConName = thCon (fsLit "AllPhases") allPhasesDataConKey
fromPhaseDataConName = thCon (fsLit "FromPhase") fromPhaseDataConKey
beforePhaseDataConName = thCon (fsLit "BeforePhase") beforePhaseDataConKey
-- data RuleBndr = ...
ruleVarName, typedRuleVarName :: Name
ruleVarName = libFun (fsLit ("ruleVar")) ruleVarIdKey
typedRuleVarName = libFun (fsLit ("typedRuleVar")) typedRuleVarIdKey
-- data FunDep = ...
funDepName :: Name
funDepName = libFun (fsLit "funDep") funDepIdKey
-- data FamFlavour = ...
typeFamName, dataFamName :: Name
typeFamName = libFun (fsLit "typeFam") typeFamIdKey
dataFamName = libFun (fsLit "dataFam") dataFamIdKey
matchQTyConName, clauseQTyConName, expQTyConName, stmtQTyConName,
decQTyConName, conQTyConName, strictTypeQTyConName,
varStrictTypeQTyConName, typeQTyConName, fieldExpQTyConName,
patQTyConName, fieldPatQTyConName, predQTyConName, decsQTyConName,
ruleBndrQTyConName :: Name
matchQTyConName = libTc (fsLit "MatchQ") matchQTyConKey
clauseQTyConName = libTc (fsLit "ClauseQ") clauseQTyConKey
expQTyConName = libTc (fsLit "ExpQ") expQTyConKey
stmtQTyConName = libTc (fsLit "StmtQ") stmtQTyConKey
decQTyConName = libTc (fsLit "DecQ") decQTyConKey
decsQTyConName = libTc (fsLit "DecsQ") decsQTyConKey -- Q [Dec]
conQTyConName = libTc (fsLit "ConQ") conQTyConKey
strictTypeQTyConName = libTc (fsLit "StrictTypeQ") strictTypeQTyConKey
varStrictTypeQTyConName = libTc (fsLit "VarStrictTypeQ") varStrictTypeQTyConKey
typeQTyConName = libTc (fsLit "TypeQ") typeQTyConKey
fieldExpQTyConName = libTc (fsLit "FieldExpQ") fieldExpQTyConKey
patQTyConName = libTc (fsLit "PatQ") patQTyConKey
fieldPatQTyConName = libTc (fsLit "FieldPatQ") fieldPatQTyConKey
predQTyConName = libTc (fsLit "PredQ") predQTyConKey
ruleBndrQTyConName = libTc (fsLit "RuleBndrQ") ruleBndrQTyConKey
-- quasiquoting
quoteExpName, quotePatName, quoteDecName, quoteTypeName :: Name
quoteExpName = qqFun (fsLit "quoteExp") quoteExpKey
quotePatName = qqFun (fsLit "quotePat") quotePatKey
quoteDecName = qqFun (fsLit "quoteDec") quoteDecKey
quoteTypeName = qqFun (fsLit "quoteType") quoteTypeKey
-- TyConUniques available: 200-299
-- Check in PrelNames if you want to change this
expTyConKey, matchTyConKey, clauseTyConKey, qTyConKey, expQTyConKey,
decQTyConKey, patTyConKey, matchQTyConKey, clauseQTyConKey,
stmtQTyConKey, conQTyConKey, typeQTyConKey, typeTyConKey, tyVarBndrTyConKey,
decTyConKey, varStrictTypeQTyConKey, strictTypeQTyConKey,
fieldExpTyConKey, fieldPatTyConKey, nameTyConKey, patQTyConKey,
fieldPatQTyConKey, fieldExpQTyConKey, funDepTyConKey, predTyConKey,
predQTyConKey, decsQTyConKey, ruleBndrQTyConKey :: Unique
expTyConKey = mkPreludeTyConUnique 200
matchTyConKey = mkPreludeTyConUnique 201
clauseTyConKey = mkPreludeTyConUnique 202
qTyConKey = mkPreludeTyConUnique 203
expQTyConKey = mkPreludeTyConUnique 204
decQTyConKey = mkPreludeTyConUnique 205
patTyConKey = mkPreludeTyConUnique 206
matchQTyConKey = mkPreludeTyConUnique 207
clauseQTyConKey = mkPreludeTyConUnique 208
stmtQTyConKey = mkPreludeTyConUnique 209
conQTyConKey = mkPreludeTyConUnique 210
typeQTyConKey = mkPreludeTyConUnique 211
typeTyConKey = mkPreludeTyConUnique 212
decTyConKey = mkPreludeTyConUnique 213
varStrictTypeQTyConKey = mkPreludeTyConUnique 214
strictTypeQTyConKey = mkPreludeTyConUnique 215
fieldExpTyConKey = mkPreludeTyConUnique 216
fieldPatTyConKey = mkPreludeTyConUnique 217
nameTyConKey = mkPreludeTyConUnique 218
patQTyConKey = mkPreludeTyConUnique 219
fieldPatQTyConKey = mkPreludeTyConUnique 220
fieldExpQTyConKey = mkPreludeTyConUnique 221
funDepTyConKey = mkPreludeTyConUnique 222
predTyConKey = mkPreludeTyConUnique 223
predQTyConKey = mkPreludeTyConUnique 224
tyVarBndrTyConKey = mkPreludeTyConUnique 225
decsQTyConKey = mkPreludeTyConUnique 226
ruleBndrQTyConKey = mkPreludeTyConUnique 227
-- IdUniques available: 200-499
-- If you want to change this, make sure you check in PrelNames
returnQIdKey, bindQIdKey, sequenceQIdKey, liftIdKey, newNameIdKey,
mkNameIdKey, mkNameG_vIdKey, mkNameG_dIdKey, mkNameG_tcIdKey,
mkNameLIdKey :: Unique
returnQIdKey = mkPreludeMiscIdUnique 200
bindQIdKey = mkPreludeMiscIdUnique 201
sequenceQIdKey = mkPreludeMiscIdUnique 202
liftIdKey = mkPreludeMiscIdUnique 203
newNameIdKey = mkPreludeMiscIdUnique 204
mkNameIdKey = mkPreludeMiscIdUnique 205
mkNameG_vIdKey = mkPreludeMiscIdUnique 206
mkNameG_dIdKey = mkPreludeMiscIdUnique 207
mkNameG_tcIdKey = mkPreludeMiscIdUnique 208
mkNameLIdKey = mkPreludeMiscIdUnique 209
-- data Lit = ...
charLIdKey, stringLIdKey, integerLIdKey, intPrimLIdKey, wordPrimLIdKey,
floatPrimLIdKey, doublePrimLIdKey, rationalLIdKey :: Unique
charLIdKey = mkPreludeMiscIdUnique 220
stringLIdKey = mkPreludeMiscIdUnique 221
integerLIdKey = mkPreludeMiscIdUnique 222
intPrimLIdKey = mkPreludeMiscIdUnique 223
wordPrimLIdKey = mkPreludeMiscIdUnique 224
floatPrimLIdKey = mkPreludeMiscIdUnique 225
doublePrimLIdKey = mkPreludeMiscIdUnique 226
rationalLIdKey = mkPreludeMiscIdUnique 227
liftStringIdKey :: Unique
liftStringIdKey = mkPreludeMiscIdUnique 228
-- data Pat = ...
litPIdKey, varPIdKey, tupPIdKey, unboxedTupPIdKey, conPIdKey, infixPIdKey, tildePIdKey, bangPIdKey,
asPIdKey, wildPIdKey, recPIdKey, listPIdKey, sigPIdKey, viewPIdKey :: Unique
litPIdKey = mkPreludeMiscIdUnique 240
varPIdKey = mkPreludeMiscIdUnique 241
tupPIdKey = mkPreludeMiscIdUnique 242
unboxedTupPIdKey = mkPreludeMiscIdUnique 243
conPIdKey = mkPreludeMiscIdUnique 244
infixPIdKey = mkPreludeMiscIdUnique 245
tildePIdKey = mkPreludeMiscIdUnique 246
bangPIdKey = mkPreludeMiscIdUnique 247
asPIdKey = mkPreludeMiscIdUnique 248
wildPIdKey = mkPreludeMiscIdUnique 249
recPIdKey = mkPreludeMiscIdUnique 250
listPIdKey = mkPreludeMiscIdUnique 251
sigPIdKey = mkPreludeMiscIdUnique 252
viewPIdKey = mkPreludeMiscIdUnique 253
-- type FieldPat = ...
fieldPatIdKey :: Unique
fieldPatIdKey = mkPreludeMiscIdUnique 260
-- data Match = ...
matchIdKey :: Unique
matchIdKey = mkPreludeMiscIdUnique 261
-- data Clause = ...
clauseIdKey :: Unique
clauseIdKey = mkPreludeMiscIdUnique 262
-- data Exp = ...
varEIdKey, conEIdKey, litEIdKey, appEIdKey, infixEIdKey, infixAppIdKey,
sectionLIdKey, sectionRIdKey, lamEIdKey, lamCaseEIdKey, tupEIdKey,
unboxedTupEIdKey, condEIdKey, multiIfEIdKey,
letEIdKey, caseEIdKey, doEIdKey, compEIdKey,
fromEIdKey, fromThenEIdKey, fromToEIdKey, fromThenToEIdKey,
listEIdKey, sigEIdKey, recConEIdKey, recUpdEIdKey :: Unique
varEIdKey = mkPreludeMiscIdUnique 270
conEIdKey = mkPreludeMiscIdUnique 271
litEIdKey = mkPreludeMiscIdUnique 272
appEIdKey = mkPreludeMiscIdUnique 273
infixEIdKey = mkPreludeMiscIdUnique 274
infixAppIdKey = mkPreludeMiscIdUnique 275
sectionLIdKey = mkPreludeMiscIdUnique 276
sectionRIdKey = mkPreludeMiscIdUnique 277
lamEIdKey = mkPreludeMiscIdUnique 278
lamCaseEIdKey = mkPreludeMiscIdUnique 279
tupEIdKey = mkPreludeMiscIdUnique 280
unboxedTupEIdKey = mkPreludeMiscIdUnique 281
condEIdKey = mkPreludeMiscIdUnique 282
multiIfEIdKey = mkPreludeMiscIdUnique 283
letEIdKey = mkPreludeMiscIdUnique 284
caseEIdKey = mkPreludeMiscIdUnique 285
doEIdKey = mkPreludeMiscIdUnique 286
compEIdKey = mkPreludeMiscIdUnique 287
fromEIdKey = mkPreludeMiscIdUnique 288
fromThenEIdKey = mkPreludeMiscIdUnique 289
fromToEIdKey = mkPreludeMiscIdUnique 290
fromThenToEIdKey = mkPreludeMiscIdUnique 291
listEIdKey = mkPreludeMiscIdUnique 292
sigEIdKey = mkPreludeMiscIdUnique 293
recConEIdKey = mkPreludeMiscIdUnique 294
recUpdEIdKey = mkPreludeMiscIdUnique 295
-- type FieldExp = ...
fieldExpIdKey :: Unique
fieldExpIdKey = mkPreludeMiscIdUnique 310
-- data Body = ...
guardedBIdKey, normalBIdKey :: Unique
guardedBIdKey = mkPreludeMiscIdUnique 311
normalBIdKey = mkPreludeMiscIdUnique 312
-- data Guard = ...
normalGEIdKey, patGEIdKey :: Unique
normalGEIdKey = mkPreludeMiscIdUnique 313
patGEIdKey = mkPreludeMiscIdUnique 314
-- data Stmt = ...
bindSIdKey, letSIdKey, noBindSIdKey, parSIdKey :: Unique
bindSIdKey = mkPreludeMiscIdUnique 320
letSIdKey = mkPreludeMiscIdUnique 321
noBindSIdKey = mkPreludeMiscIdUnique 322
parSIdKey = mkPreludeMiscIdUnique 323
-- data Dec = ...
funDIdKey, valDIdKey, dataDIdKey, newtypeDIdKey, tySynDIdKey,
classDIdKey, instanceDIdKey, sigDIdKey, forImpDIdKey, pragInlDIdKey,
pragSpecDIdKey, pragSpecInlDIdKey, pragSpecInstDIdKey, pragRuleDIdKey,
familyNoKindDIdKey, familyKindDIdKey,
dataInstDIdKey, newtypeInstDIdKey, tySynInstDIdKey,
infixLDIdKey, infixRDIdKey, infixNDIdKey :: Unique
funDIdKey = mkPreludeMiscIdUnique 330
valDIdKey = mkPreludeMiscIdUnique 331
dataDIdKey = mkPreludeMiscIdUnique 332
newtypeDIdKey = mkPreludeMiscIdUnique 333
tySynDIdKey = mkPreludeMiscIdUnique 334
classDIdKey = mkPreludeMiscIdUnique 335
instanceDIdKey = mkPreludeMiscIdUnique 336
sigDIdKey = mkPreludeMiscIdUnique 337
forImpDIdKey = mkPreludeMiscIdUnique 338
pragInlDIdKey = mkPreludeMiscIdUnique 339
pragSpecDIdKey = mkPreludeMiscIdUnique 340
pragSpecInlDIdKey = mkPreludeMiscIdUnique 341
pragSpecInstDIdKey = mkPreludeMiscIdUnique 412
pragRuleDIdKey = mkPreludeMiscIdUnique 413
familyNoKindDIdKey = mkPreludeMiscIdUnique 342
familyKindDIdKey = mkPreludeMiscIdUnique 343
dataInstDIdKey = mkPreludeMiscIdUnique 344
newtypeInstDIdKey = mkPreludeMiscIdUnique 345
tySynInstDIdKey = mkPreludeMiscIdUnique 346
infixLDIdKey = mkPreludeMiscIdUnique 347
infixRDIdKey = mkPreludeMiscIdUnique 348
infixNDIdKey = mkPreludeMiscIdUnique 349
-- type Cxt = ...
cxtIdKey :: Unique
cxtIdKey = mkPreludeMiscIdUnique 360
-- data Pred = ...
classPIdKey, equalPIdKey :: Unique
classPIdKey = mkPreludeMiscIdUnique 361
equalPIdKey = mkPreludeMiscIdUnique 362
-- data Strict = ...
isStrictKey, notStrictKey, unpackedKey :: Unique
isStrictKey = mkPreludeMiscIdUnique 363
notStrictKey = mkPreludeMiscIdUnique 364
unpackedKey = mkPreludeMiscIdUnique 365
-- data Con = ...
normalCIdKey, recCIdKey, infixCIdKey, forallCIdKey :: Unique
normalCIdKey = mkPreludeMiscIdUnique 370
recCIdKey = mkPreludeMiscIdUnique 371
infixCIdKey = mkPreludeMiscIdUnique 372
forallCIdKey = mkPreludeMiscIdUnique 373
-- type StrictType = ...
strictTKey :: Unique
strictTKey = mkPreludeMiscIdUnique 374
-- type VarStrictType = ...
varStrictTKey :: Unique
varStrictTKey = mkPreludeMiscIdUnique 375
-- data Type = ...
forallTIdKey, varTIdKey, conTIdKey, tupleTIdKey, unboxedTupleTIdKey, arrowTIdKey,
listTIdKey, appTIdKey, sigTIdKey, litTIdKey,
promotedTIdKey, promotedTupleTIdKey,
promotedNilTIdKey, promotedConsTIdKey :: Unique
forallTIdKey = mkPreludeMiscIdUnique 380
varTIdKey = mkPreludeMiscIdUnique 381
conTIdKey = mkPreludeMiscIdUnique 382
tupleTIdKey = mkPreludeMiscIdUnique 383
unboxedTupleTIdKey = mkPreludeMiscIdUnique 384
arrowTIdKey = mkPreludeMiscIdUnique 385
listTIdKey = mkPreludeMiscIdUnique 386
appTIdKey = mkPreludeMiscIdUnique 387
sigTIdKey = mkPreludeMiscIdUnique 388
litTIdKey = mkPreludeMiscIdUnique 389
promotedTIdKey = mkPreludeMiscIdUnique 390
promotedTupleTIdKey = mkPreludeMiscIdUnique 391
promotedNilTIdKey = mkPreludeMiscIdUnique 392
promotedConsTIdKey = mkPreludeMiscIdUnique 393
-- data TyLit = ...
numTyLitIdKey, strTyLitIdKey :: Unique
numTyLitIdKey = mkPreludeMiscIdUnique 394
strTyLitIdKey = mkPreludeMiscIdUnique 395
-- data TyVarBndr = ...
plainTVIdKey, kindedTVIdKey :: Unique
plainTVIdKey = mkPreludeMiscIdUnique 396
kindedTVIdKey = mkPreludeMiscIdUnique 397
-- data Kind = ...
varKIdKey, conKIdKey, tupleKIdKey, arrowKIdKey, listKIdKey, appKIdKey,
starKIdKey, constraintKIdKey :: Unique
varKIdKey = mkPreludeMiscIdUnique 398
conKIdKey = mkPreludeMiscIdUnique 399
tupleKIdKey = mkPreludeMiscIdUnique 400
arrowKIdKey = mkPreludeMiscIdUnique 401
listKIdKey = mkPreludeMiscIdUnique 402
appKIdKey = mkPreludeMiscIdUnique 403
starKIdKey = mkPreludeMiscIdUnique 404
constraintKIdKey = mkPreludeMiscIdUnique 405
-- data Callconv = ...
cCallIdKey, stdCallIdKey :: Unique
cCallIdKey = mkPreludeMiscIdUnique 406
stdCallIdKey = mkPreludeMiscIdUnique 407
-- data Safety = ...
unsafeIdKey, safeIdKey, interruptibleIdKey :: Unique
unsafeIdKey = mkPreludeMiscIdUnique 408
safeIdKey = mkPreludeMiscIdUnique 409
interruptibleIdKey = mkPreludeMiscIdUnique 411
-- data Inline = ...
noInlineDataConKey, inlineDataConKey, inlinableDataConKey :: Unique
noInlineDataConKey = mkPreludeDataConUnique 40
inlineDataConKey = mkPreludeDataConUnique 41
inlinableDataConKey = mkPreludeDataConUnique 42
-- data RuleMatch = ...
conLikeDataConKey, funLikeDataConKey :: Unique
conLikeDataConKey = mkPreludeDataConUnique 43
funLikeDataConKey = mkPreludeDataConUnique 44
-- data Phases = ...
allPhasesDataConKey, fromPhaseDataConKey, beforePhaseDataConKey :: Unique
allPhasesDataConKey = mkPreludeDataConUnique 45
fromPhaseDataConKey = mkPreludeDataConUnique 46
beforePhaseDataConKey = mkPreludeDataConUnique 47
-- data FunDep = ...
funDepIdKey :: Unique
funDepIdKey = mkPreludeMiscIdUnique 414
-- data FamFlavour = ...
typeFamIdKey, dataFamIdKey :: Unique
typeFamIdKey = mkPreludeMiscIdUnique 415
dataFamIdKey = mkPreludeMiscIdUnique 416
-- quasiquoting
quoteExpKey, quotePatKey, quoteDecKey, quoteTypeKey :: Unique
quoteExpKey = mkPreludeMiscIdUnique 418
quotePatKey = mkPreludeMiscIdUnique 419
quoteDecKey = mkPreludeMiscIdUnique 420
quoteTypeKey = mkPreludeMiscIdUnique 421
-- data RuleBndr = ...
ruleVarIdKey, typedRuleVarIdKey :: Unique
ruleVarIdKey = mkPreludeMiscIdUnique 422
typedRuleVarIdKey = mkPreludeMiscIdUnique 423
| nomeata/ghc | compiler/deSugar/DsMeta.hs | bsd-3-clause | 103,047 | 339 | 21 | 24,790 | 29,747 | 15,416 | 14,331 | -1 | -1 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
import Control.Monad
import Control.Monad.Identity
import Control.Monad.Trans
import Reflex.Dom
import qualified Data.Text as T
import Control.Concurrent
import Control.Monad.State.Strict
import Data.Functor.Misc
import Data.Monoid
import Data.Word
import qualified Data.Map as Map
import qualified Data.Dependent.Map as DMap
import Data.Dependent.Sum
import qualified Reflex.Patch.DMapWithMove as PatchDMapWithMove
main :: IO ()
main = mainWidget w
w :: forall t m. (MonadWidget t m, DomRenderHook t m, MountableDomBuilder t m) => m ()
w = do
let slow :: forall m'. (MonadWidget t m', DomRenderHook t m') => m' ()
{-
performEventChain = do
postBuild <- delay 0 =<< getPostBuild
rec let maxN = 10000
n = leftmost [0 <$ postBuild, ffilter (<=maxN) $ succ <$> n']
n' <- performEvent $ return <$> n
pausedUntil $ ffilter (==maxN) n'
_ <- widgetHold (text "Starting") $ text . T.pack . show <$> n
return ()
-}
-- {- Many dyns
slow = elAttr "div" ("style" =: "position:relative;width:256px;height:256px") $ go maxDepth
where maxDepth = 6 :: Int
go 0 = blank
go n = void $ dyn $ pure $ do
let bgcolor = "rgba(0,0,0," <> T.pack (show (1 - (fromIntegral n / fromIntegral maxDepth) :: Double)) <> ")"
s pos = pos <> ";position:absolute;border:1px solid white;background-color:" <> bgcolor
elAttr "div" ("style" =: s "left:0;right:50%;top:0;bottom:50%") $ go $ pred n
elAttr "div" ("style" =: s "left:50%;right:0;top:0;bottom:50%") $ go $ pred n
elAttr "div" ("style" =: s "left:50%;right:0;top:50%;bottom:0") $ go $ pred n
elAttr "div" ("style" =: s "left:0;right:50%;top:50%;bottom:0") $ go $ pred n
-- -}
{- Many elDynAttrs
slow = do
let size = 64
replicateM_ size $ elAttr "div" ("style" =: ("height:4px;width:" <> T.pack (show (size*4)) <> "px;line-height:0;background-color:gray")) $ do
replicateM_ size $ elDynAttr "div" (pure $ "style" =: "display:inline-block;width:4px;height:4px;background-color:black") blank
-}
{- Many dynTexts
slow = el "table" $ do
let size = 64
replicateM_ size $ el "tr" $ do
replicateM_ size $ el "td" $ do
dynText $ pure "."
-}
{- Many simultaneous performEvents
slow = do
postBuild <- getPostBuild
replicateM_ ((2 :: Int) ^ (14 :: Int)) $ performEvent_ $ return () <$ postBuild
done <- performEvent $ return () <$ postBuild
_ <- widgetHold (text "Doing performEvent") $ text "Done" <$ done
return ()
-}
{-
slow = do
postBuild <- getPostBuild
postBuild' <- performEvent . (return () <$) =<< performEvent . (return () <$) =<< getPostBuild
let f x = Map.fromList [(n, x) | n <- [1 :: Int .. 4096]]
listHoldWithKey (f False) (f (Just True) <$ postBuild') $ \k -> \case
False -> do
text "X "
notReadyUntil =<< getPostBuild
True -> do
text ". "
return ()
-}
{-
slow = do
let f :: forall a. EitherTag () () a -> Const2 () () a -> m' (Const2 () () a)
f _ (Const2 ()) = do
notReadyUntil =<< delay 0.5 =<< getPostBuild
text "Done"
return $ Const2 ()
postBuild <- getPostBuild
traverseDMapWithKeyWithAdjustWithMove f (DMap.singleton LeftTag $ Const2 ()) $ (PatchDMapWithMove.moveDMapKey LeftTag RightTag) <$ postBuild
return ()
-}
{-
slow = do
let h x = do
liftIO $ putStrLn "render hook"
result <- x
liftIO $ putStrLn "render hook done"
return result
f :: forall a. Const2 () () a -> Identity a -> m' (Identity a)
f (Const2 ()) (Identity ()) = do
liftIO $ putStrLn "f"
widgetHold notReady . (blank <$) =<< delay 0.1 =<< getPostBuild
liftIO $ putStrLn "f done"
return $ Identity ()
withRenderHook h $ do
postBuild <- getPostBuild
_ <- traverseDMapWithKeyWithAdjust f mempty $ PatchDMap (DMap.singleton (Const2 () :: Const2 () () ()) (ComposeMaybe $ Just $ Identity ())) <$ postBuild
return ()
-}
el "div" $ do
draw <- button "Draw"
widgetHold blank $ ffor draw $ \_ -> do
_ <- untilReady (text "Loading...") slow
return ()
return ()
#ifdef EXPERIMENTAL_DEPENDENT_SUM_INSTANCES
instance {-# INCOHERENT #-} (Show (f a), Show (f b)) => ShowTag (EitherTag a b) f where
showTagToShow e _ = case e of
LeftTag -> id
RightTag -> id
#endif
| mightybyte/reflex-dom | test/prebuild.hs | bsd-3-clause | 5,028 | 0 | 27 | 1,537 | 611 | 321 | 290 | 42 | 2 |
{-|
Module : Diplomacy.Occupation
Description : Definition of Zone/ProvinceTarget occupation.
Copyright : (c) Alexander Vieth, 2015
Licence : BSD3
Maintainer : aovieth@gmail.com
Stability : experimental
Portability : non-portable (GHC only)
-}
{-# LANGUAGE AutoDeriveTypeable #-}
module Diplomacy.Occupation (
Occupation
, emptyOccupation
, occupy
, occupier
, provinceOccupier
, occupies
, unitOccupies
, occupied
, zoneOccupied
, allSubjects
) where
import qualified Data.Map as M
import Data.MapUtil
import Data.Maybe (isJust)
import Diplomacy.Aligned
import Diplomacy.Unit
import Diplomacy.Province
import Diplomacy.Zone
import Diplomacy.Subject
import Diplomacy.GreatPower
-- | Each Zone is occupied by at most one Aligned Unit, but the functions on
-- Occupation work with ProvinceTarget; the use of Zone as a key here is just
-- to guarantee that we don't have, for instance, units on both of Spain's
-- coasts simultaneously.
type Occupation = M.Map Zone (Aligned Unit)
emptyOccupation :: Occupation
emptyOccupation = M.empty
occupy :: ProvinceTarget -> Maybe (Aligned Unit) -> Occupation -> Occupation
occupy pt maunit = M.alter (const maunit) (Zone pt)
-- | Must be careful with this one! We can't just lookup the Zone corresponding
-- to the ProvinceTarget; we must also check that the key matching that Zone,
-- if there is one in the map, is also ProvinceTarget-equal.
occupier :: ProvinceTarget -> Occupation -> Maybe (Aligned Unit)
occupier pt occupation = case lookupWithKey (Zone pt) occupation of
Just (zone, value) ->
if zoneProvinceTarget zone == pt
then Just value
else Nothing
_ -> Nothing
provinceOccupier :: Province -> Occupation -> Maybe (Aligned Unit)
provinceOccupier pr occupation = case lookupWithKey (Zone (Normal pr)) occupation of
Just (zone, value) ->
if zoneProvinceTarget zone == Normal pr
then Just value
else Nothing
_ -> Nothing
occupies :: Aligned Unit -> ProvinceTarget -> Occupation -> Bool
occupies aunit pt = (==) (Just aunit) . occupier pt
unitOccupies :: Unit -> ProvinceTarget -> Occupation -> Bool
unitOccupies unit pt = (==) (Just unit) . fmap alignedThing . occupier pt
occupied :: ProvinceTarget -> Occupation -> Bool
occupied pt = isJust . occupier pt
zoneOccupied :: Zone -> Occupation -> Bool
zoneOccupied zone = isJust . M.lookup zone
allSubjects :: Maybe GreatPower -> Occupation -> [Subject]
allSubjects maybeGreatPower = M.foldWithKey f []
where
f zone aunit =
let subject = (alignedThing aunit, zoneProvinceTarget zone)
in if maybeGreatPower == Nothing || Just (alignedGreatPower aunit) == maybeGreatPower
then (:) subject
else id
| avieth/diplomacy | Diplomacy/Occupation.hs | bsd-3-clause | 2,765 | 0 | 14 | 563 | 630 | 333 | 297 | 55 | 3 |
{-- snippet modifyMVar --}
import Control.Concurrent (MVar, putMVar, takeMVar)
import Control.Exception (block, catch, throw, unblock)
import Prelude hiding (catch) -- use Control.Exception's version
modifyMVar :: MVar a -> (a -> IO (a,b)) -> IO b
modifyMVar m io =
block $ do
a <- takeMVar m
(b,r) <- unblock (io a) `catch` \e ->
putMVar m a >> throw e
putMVar m b
return r
{-- /snippet modifyMVar --}
| binesiyu/ifl | examples/ch24/ModifyMVar.hs | mit | 436 | 0 | 12 | 102 | 166 | 88 | 78 | 11 | 1 |
{-# LANGUAGE TemplateHaskell #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
{-| Unittests for "Ganeti.Runtime".
-}
{-
Copyright (C) 2013 Google Inc.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301, USA.
-}
module Test.Ganeti.Runtime (testRuntime) where
import Test.HUnit
import qualified Text.JSON as J
import Test.Ganeti.TestHelper
import Test.Ganeti.TestCommon
import Ganeti.Runtime
{-# ANN module "HLint: ignore Use camelCase" #-}
-- | Tests the compatibility between Haskell and Python log files.
case_LogFiles :: Assertion
case_LogFiles = do
let daemons = [minBound..maxBound]::[GanetiDaemon]
dnames = map daemonName daemons
dfiles <- mapM daemonLogFile daemons
let serialized = J.encode dnames
py_stdout <-
runPython "from ganeti import constants\n\
\from ganeti import serializer\n\
\import sys\n\
\daemons = serializer.Load(sys.stdin.read())\n\
\logfiles = [constants.DAEMONS_LOGFILES[d] for d in daemons]\n\
\print serializer.Dump(logfiles)" serialized
>>= checkPythonResult
let deserialised = J.decode py_stdout::J.Result [String]
decoded <- case deserialised of
J.Ok ops -> return ops
J.Error msg ->
assertFailure ("Unable to decode log files: " ++ msg)
-- this already raised an expection, but we need it
-- for proper types
>> fail "Unable to decode log files"
assertEqual "Mismatch in number of returned log files"
(length decoded) (length daemons)
mapM_ (uncurry (assertEqual "Different result after encoding/decoding")
) $ zip dfiles decoded
-- | Tests the compatibility between Haskell and Python users.
case_UsersGroups :: Assertion
case_UsersGroups = do
-- note: we don't have here a programatic way to list all users, so
-- we harcode some parts of the two (hs/py) lists
let daemons = [minBound..maxBound]::[GanetiDaemon]
users = map daemonUser daemons
groups = map daemonGroup $
map DaemonGroup daemons ++ map ExtraGroup [minBound..maxBound]
py_stdout <-
runPython "from ganeti import constants\n\
\from ganeti import serializer\n\
\import sys\n\
\users = [constants.MASTERD_USER,\n\
\ constants.NODED_USER,\n\
\ constants.RAPI_USER,\n\
\ constants.CONFD_USER,\n\
\ constants.WCONFD_USER,\n\
\ constants.KVMD_USER,\n\
\ constants.LUXID_USER,\n\
\ constants.METAD_USER,\n\
\ constants.MOND_USER,\n\
\ ]\n\
\groups = [constants.MASTERD_GROUP,\n\
\ constants.NODED_GROUP,\n\
\ constants.RAPI_GROUP,\n\
\ constants.CONFD_GROUP,\n\
\ constants.WCONFD_GROUP,\n\
\ constants.KVMD_GROUP,\n\
\ constants.LUXID_GROUP,\n\
\ constants.METAD_GROUP,\n\
\ constants.MOND_GROUP,\n\
\ constants.DAEMONS_GROUP,\n\
\ constants.ADMIN_GROUP,\n\
\ ]\n\
\encoded = (users, groups)\n\
\print serializer.Dump(encoded)" ""
>>= checkPythonResult
let deserialised = J.decode py_stdout::J.Result ([String], [String])
(py_users, py_groups) <-
case deserialised of
J.Ok ops -> return ops
J.Error msg ->
assertFailure ("Unable to decode users/groups: " ++ msg)
-- this already raised an expection, but we need it for proper
-- types
>> fail "Unable to decode users/groups"
assertEqual "Mismatch in number of returned users"
(length py_users) (length users)
assertEqual "Mismatch in number of returned users"
(length py_groups) (length groups)
mapM_ (uncurry (assertEqual "Different result for users")
) $ zip users py_users
mapM_ (uncurry (assertEqual "Different result for groups")
) $ zip groups py_groups
testSuite "Runtime"
[ 'case_LogFiles
, 'case_UsersGroups
]
| ribag/ganeti-experiments | test/hs/Test/Ganeti/Runtime.hs | gpl-2.0 | 4,893 | 0 | 14 | 1,444 | 558 | 282 | 276 | 57 | 2 |
module TypeBug6 where
f :: [[String]]->[String]
f [x] = []
f [x,y] = x ++ filter (not.eqString (unwords(concat x y))) y
f (x:y:z) = f (x:y) ++ f (x:z)
| roberth/uu-helium | test/simple/typeerrors/Examples/TypeBug6.hs | gpl-3.0 | 158 | 0 | 12 | 36 | 123 | 66 | 57 | 5 | 1 |
{-|
A 'TimeclockEntry' is a clock-in, clock-out, or other directive in a timeclock
file (see timeclock.el or the command-line version). These can be
converted to 'Transactions' and queried like a ledger.
-}
{-# LANGUAGE OverloadedStrings #-}
module Hledger.Data.Timeclock (
timeclockEntriesToTransactions
,tests_Timeclock
)
where
import Data.Maybe (fromMaybe)
import qualified Data.Text as T
import Data.Time.Calendar (addDays)
import Data.Time.Clock (addUTCTime, getCurrentTime)
import Data.Time.Format (defaultTimeLocale, formatTime, parseTimeM)
import Data.Time.LocalTime (LocalTime(..), TimeOfDay(..), getCurrentTimeZone,
localTimeToUTC, midnight, utc, utcToLocalTime)
import Text.Printf (printf)
import Hledger.Utils
import Hledger.Data.Types
import Hledger.Data.Dates
import Hledger.Data.Amount
import Hledger.Data.Posting
import Hledger.Data.Transaction
instance Show TimeclockEntry where
show t = printf "%s %s %s %s" (show $ tlcode t) (show $ tldatetime t) (tlaccount t) (tldescription t)
instance Show TimeclockCode where
show SetBalance = "b"
show SetRequiredHours = "h"
show In = "i"
show Out = "o"
show FinalOut = "O"
instance Read TimeclockCode where
readsPrec _ ('b' : xs) = [(SetBalance, xs)]
readsPrec _ ('h' : xs) = [(SetRequiredHours, xs)]
readsPrec _ ('i' : xs) = [(In, xs)]
readsPrec _ ('o' : xs) = [(Out, xs)]
readsPrec _ ('O' : xs) = [(FinalOut, xs)]
readsPrec _ _ = []
-- | Convert time log entries to journal transactions. When there is no
-- clockout, add one with the provided current time. Sessions crossing
-- midnight are split into days to give accurate per-day totals.
timeclockEntriesToTransactions :: LocalTime -> [TimeclockEntry] -> [Transaction]
timeclockEntriesToTransactions _ [] = []
timeclockEntriesToTransactions now [i]
| tlcode i /= In = errorExpectedCodeButGot In i
| odate > idate = entryFromTimeclockInOut i o' : timeclockEntriesToTransactions now [i',o]
| otherwise = [entryFromTimeclockInOut i o]
where
o = TimeclockEntry (tlsourcepos i) Out end "" ""
end = if itime > now then itime else now
(itime,otime) = (tldatetime i,tldatetime o)
(idate,odate) = (localDay itime,localDay otime)
o' = o{tldatetime=itime{localDay=idate, localTimeOfDay=TimeOfDay 23 59 59}}
i' = i{tldatetime=itime{localDay=addDays 1 idate, localTimeOfDay=midnight}}
timeclockEntriesToTransactions now (i:o:rest)
| tlcode i /= In = errorExpectedCodeButGot In i
| tlcode o /= Out =errorExpectedCodeButGot Out o
| odate > idate = entryFromTimeclockInOut i o' : timeclockEntriesToTransactions now (i':o:rest)
| otherwise = entryFromTimeclockInOut i o : timeclockEntriesToTransactions now rest
where
(itime,otime) = (tldatetime i,tldatetime o)
(idate,odate) = (localDay itime,localDay otime)
o' = o{tldatetime=itime{localDay=idate, localTimeOfDay=TimeOfDay 23 59 59}}
i' = i{tldatetime=itime{localDay=addDays 1 idate, localTimeOfDay=midnight}}
{- HLINT ignore timeclockEntriesToTransactions -}
errorExpectedCodeButGot expected actual = errorWithSourceLine line $ "expected timeclock code " ++ (show expected) ++ " but got " ++ show (tlcode actual)
where line = unPos . sourceLine $ tlsourcepos actual
errorWithSourceLine line msg = error $ "line " ++ show line ++ ": " ++ msg
-- | Convert a timeclock clockin and clockout entry to an equivalent journal
-- transaction, representing the time expenditure. Note this entry is not balanced,
-- since we omit the \"assets:time\" transaction for simpler output.
entryFromTimeclockInOut :: TimeclockEntry -> TimeclockEntry -> Transaction
entryFromTimeclockInOut i o
| otime >= itime = t
| otherwise = error' . T.unpack $
"clock-out time less than clock-in time in:\n" <> showTransaction t -- PARTIAL:
where
t = Transaction {
tindex = 0,
tsourcepos = (tlsourcepos i, tlsourcepos i),
tdate = idate,
tdate2 = Nothing,
tstatus = Cleared,
tcode = "",
tdescription = desc,
tcomment = "",
ttags = [],
tpostings = ps,
tprecedingcomment=""
}
itime = tldatetime i
otime = tldatetime o
itod = localTimeOfDay itime
otod = localTimeOfDay otime
idate = localDay itime
desc | T.null (tldescription i) = T.pack $ showtime itod ++ "-" ++ showtime otod
| otherwise = tldescription i
showtime = take 5 . show
hours = elapsedSeconds (toutc otime) (toutc itime) / 3600 where toutc = localTimeToUTC utc
acctname = tlaccount i
-- Generate an hours amount. Unusually, we also round the internal Decimal value,
-- since otherwise it will often have large recurring decimal parts which (since 1.21)
-- print would display all 255 digits of. timeclock amounts have one second resolution,
-- so two decimal places is precise enough (#1527).
amount = mixedAmount $ setAmountInternalPrecision 2 $ hrs hours
ps = [posting{paccount=acctname, pamount=amount, ptype=VirtualPosting, ptransaction=Just t}]
-- tests
tests_Timeclock = testGroup "Timeclock" [
testCaseSteps "timeclockEntriesToTransactions tests" $ \step -> do
step "gathering data"
today <- getCurrentDay
now' <- getCurrentTime
tz <- getCurrentTimeZone
let now = utcToLocalTime tz now'
nowstr = showtime now
yesterday = prevday today
clockin = TimeclockEntry (initialPos "") In
mktime d = LocalTime d . fromMaybe midnight .
parseTimeM True defaultTimeLocale "%H:%M:%S"
showtime = formatTime defaultTimeLocale "%H:%M"
txndescs = map (T.unpack . tdescription) . timeclockEntriesToTransactions now
future = utcToLocalTime tz $ addUTCTime 100 now'
futurestr = showtime future
step "started yesterday, split session at midnight"
txndescs [clockin (mktime yesterday "23:00:00") "" ""] @?= ["23:00-23:59","00:00-"++nowstr]
step "split multi-day sessions at each midnight"
txndescs [clockin (mktime (addDays (-2) today) "23:00:00") "" ""] @?= ["23:00-23:59","00:00-23:59","00:00-"++nowstr]
step "auto-clock-out if needed"
txndescs [clockin (mktime today "00:00:00") "" ""] @?= ["00:00-"++nowstr]
step "use the clockin time for auto-clockout if it's in the future"
txndescs [clockin future "" ""] @?= [printf "%s-%s" futurestr futurestr]
]
| adept/hledger | hledger-lib/Hledger/Data/Timeclock.hs | gpl-3.0 | 6,665 | 0 | 20 | 1,567 | 1,747 | 926 | 821 | 110 | 2 |
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd">
<helpset version="2.0" xml:lang="ja-JP">
<title>TLS デバッグ | ZAP拡張</title>
<maps>
<homeID>top</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>コンテンツ</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>インデックス</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>検索</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>お気に入り</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset> | veggiespam/zap-extensions | addOns/tlsdebug/src/main/javahelp/org/zaproxy/zap/extension/tlsdebug/resources/help_ja_JP/helpset_ja_JP.hs | apache-2.0 | 1,000 | 91 | 61 | 159 | 404 | 205 | 199 | -1 | -1 |
module VarPtr where
import Data.Var
data Record = Record Int
main = do
v <- newVar $ Record 5
subscribeAndRead v $ \y -> case y of
Record a -> putStrLn . show $ a
set v $ Record 10
| beni55/fay | tests/VarPtr.hs | bsd-3-clause | 195 | 0 | 13 | 54 | 86 | 42 | 44 | 8 | 1 |
-- (c) The University of Glasgow 2006
{-# LANGUAGE CPP, DeriveFunctor #-}
module Unify (
-- Matching of types:
-- the "tc" prefix indicates that matching always
-- respects newtypes (rather than looking through them)
tcMatchTy, tcUnifyTyWithTFs, tcMatchTys, tcMatchTyX, tcMatchTysX,
ruleMatchTyX, tcMatchPreds,
MatchEnv(..), matchList,
typesCantMatch,
-- Side-effect free unification
tcUnifyTy, tcUnifyTys, BindFlag(..),
UnifyResultM(..), UnifyResult, tcUnifyTysFG
) where
#include "HsVersions.h"
import Var
import VarEnv
import VarSet
import Kind
import Type
import TyCon
import TypeRep
import Util ( filterByList )
import Outputable
import FastString (sLit)
import Control.Monad (liftM, foldM, ap)
#if __GLASGOW_HASKELL__ < 709
import Control.Applicative (Applicative(..))
#endif
{-
************************************************************************
* *
Matching
* *
************************************************************************
Matching is much tricker than you might think.
1. The substitution we generate binds the *template type variables*
which are given to us explicitly.
2. We want to match in the presence of foralls;
e.g (forall a. t1) ~ (forall b. t2)
That is what the RnEnv2 is for; it does the alpha-renaming
that makes it as if a and b were the same variable.
Initialising the RnEnv2, so that it can generate a fresh
binder when necessary, entails knowing the free variables of
both types.
3. We must be careful not to bind a template type variable to a
locally bound variable. E.g.
(forall a. x) ~ (forall b. b)
where x is the template type variable. Then we do not want to
bind x to a/b! This is a kind of occurs check.
The necessary locals accumulate in the RnEnv2.
-}
data MatchEnv
= ME { me_tmpls :: VarSet -- Template variables
, me_env :: RnEnv2 -- Renaming envt for nested foralls
} -- In-scope set includes template variables
-- Nota Bene: MatchEnv isn't specific to Types. It is used
-- for matching terms and coercions as well as types
tcMatchTy :: TyVarSet -- Template tyvars
-> Type -- Template
-> Type -- Target
-> Maybe TvSubst -- One-shot; in principle the template
-- variables could be free in the target
tcMatchTy tmpls ty1 ty2
= tcMatchTyX tmpls init_subst ty1 ty2
where
init_subst = mkTvSubst in_scope emptyTvSubstEnv
in_scope = mkInScopeSet (tmpls `unionVarSet` tyVarsOfType ty2)
-- We're assuming that all the interesting
-- tyvars in ty1 are in tmpls
tcMatchTys :: TyVarSet -- Template tyvars
-> [Type] -- Template
-> [Type] -- Target
-> Maybe TvSubst -- One-shot; in principle the template
-- variables could be free in the target
tcMatchTys tmpls tys1 tys2
= tcMatchTysX tmpls init_subst tys1 tys2
where
init_subst = mkTvSubst in_scope emptyTvSubstEnv
in_scope = mkInScopeSet (tmpls `unionVarSet` tyVarsOfTypes tys2)
tcMatchTyX :: TyVarSet -- Template tyvars
-> TvSubst -- Substitution to extend
-> Type -- Template
-> Type -- Target
-> Maybe TvSubst
tcMatchTyX tmpls (TvSubst in_scope subst_env) ty1 ty2
= case match menv subst_env ty1 ty2 of
Just subst_env' -> Just (TvSubst in_scope subst_env')
Nothing -> Nothing
where
menv = ME {me_tmpls = tmpls, me_env = mkRnEnv2 in_scope}
tcMatchTysX :: TyVarSet -- Template tyvars
-> TvSubst -- Substitution to extend
-> [Type] -- Template
-> [Type] -- Target
-> Maybe TvSubst -- One-shot; in principle the template
-- variables could be free in the target
tcMatchTysX tmpls (TvSubst in_scope subst_env) tys1 tys2
= case match_tys menv subst_env tys1 tys2 of
Just subst_env' -> Just (TvSubst in_scope subst_env')
Nothing -> Nothing
where
menv = ME { me_tmpls = tmpls, me_env = mkRnEnv2 in_scope }
tcMatchPreds
:: [TyVar] -- Bind these
-> [PredType] -> [PredType]
-> Maybe TvSubstEnv
tcMatchPreds tmpls ps1 ps2
= matchList (match menv) emptyTvSubstEnv ps1 ps2
where
menv = ME { me_tmpls = mkVarSet tmpls, me_env = mkRnEnv2 in_scope_tyvars }
in_scope_tyvars = mkInScopeSet (tyVarsOfTypes ps1 `unionVarSet` tyVarsOfTypes ps2)
-- This one is called from the expression matcher, which already has a MatchEnv in hand
ruleMatchTyX :: MatchEnv
-> TvSubstEnv -- Substitution to extend
-> Type -- Template
-> Type -- Target
-> Maybe TvSubstEnv
ruleMatchTyX menv subst ty1 ty2 = match menv subst ty1 ty2 -- Rename for export
-- Now the internals of matching
-- | Workhorse matching function. Our goal is to find a substitution
-- on all of the template variables (specified by @me_tmpls menv@) such
-- that @ty1@ and @ty2@ unify. This substitution is accumulated in @subst@.
-- If a variable is not a template variable, we don't attempt to find a
-- substitution for it; it must match exactly on both sides. Furthermore,
-- only @ty1@ can have template variables.
--
-- This function handles binders, see 'RnEnv2' for more details on
-- how that works.
match :: MatchEnv -- For the most part this is pushed downwards
-> TvSubstEnv -- Substitution so far:
-- Domain is subset of template tyvars
-- Free vars of range is subset of
-- in-scope set of the RnEnv2
-> Type -> Type -- Template and target respectively
-> Maybe TvSubstEnv
match menv subst ty1 ty2 | Just ty1' <- coreView ty1 = match menv subst ty1' ty2
| Just ty2' <- coreView ty2 = match menv subst ty1 ty2'
match menv subst (TyVarTy tv1) ty2
| Just ty1' <- lookupVarEnv subst tv1' -- tv1' is already bound
= if eqTypeX (nukeRnEnvL rn_env) ty1' ty2
-- ty1 has no locally-bound variables, hence nukeRnEnvL
then Just subst
else Nothing -- ty2 doesn't match
| tv1' `elemVarSet` me_tmpls menv
= if any (inRnEnvR rn_env) (varSetElems (tyVarsOfType ty2))
then Nothing -- Occurs check
-- ezyang: Is this really an occurs check? It seems
-- to just reject matching \x. A against \x. x (maintaining
-- the invariant that the free vars of the range of @subst@
-- are a subset of the in-scope set in @me_env menv@.)
else do { subst1 <- match_kind menv subst (tyVarKind tv1) (typeKind ty2)
-- Note [Matching kinds]
; return (extendVarEnv subst1 tv1' ty2) }
| otherwise -- tv1 is not a template tyvar
= case ty2 of
TyVarTy tv2 | tv1' == rnOccR rn_env tv2 -> Just subst
_ -> Nothing
where
rn_env = me_env menv
tv1' = rnOccL rn_env tv1
match menv subst (ForAllTy tv1 ty1) (ForAllTy tv2 ty2)
= do { subst' <- match_kind menv subst (tyVarKind tv1) (tyVarKind tv2)
; match menv' subst' ty1 ty2 }
where -- Use the magic of rnBndr2 to go under the binders
menv' = menv { me_env = rnBndr2 (me_env menv) tv1 tv2 }
match menv subst (TyConApp tc1 tys1) (TyConApp tc2 tys2)
| tc1 == tc2 = match_tys menv subst tys1 tys2
match menv subst (FunTy ty1a ty1b) (FunTy ty2a ty2b)
= do { subst' <- match menv subst ty1a ty2a
; match menv subst' ty1b ty2b }
match menv subst (AppTy ty1a ty1b) ty2
| Just (ty2a, ty2b) <- repSplitAppTy_maybe ty2
-- 'repSplit' used because the tcView stuff is done above
= do { subst' <- match menv subst ty1a ty2a
; match menv subst' ty1b ty2b }
match _ subst (LitTy x) (LitTy y) | x == y = return subst
match _ _ _ _
= Nothing
--------------
match_kind :: MatchEnv -> TvSubstEnv -> Kind -> Kind -> Maybe TvSubstEnv
-- Match the kind of the template tyvar with the kind of Type
-- Note [Matching kinds]
match_kind menv subst k1 k2
| k2 `isSubKind` k1
= return subst
| otherwise
= match menv subst k1 k2
-- Note [Matching kinds]
-- ~~~~~~~~~~~~~~~~~~~~~
-- For ordinary type variables, we don't want (m a) to match (n b)
-- if say (a::*) and (b::*->*). This is just a yes/no issue.
--
-- For coercion kinds matters are more complicated. If we have a
-- coercion template variable co::a~[b], where a,b are presumably also
-- template type variables, then we must match co's kind against the
-- kind of the actual argument, so as to give bindings to a,b.
--
-- In fact I have no example in mind that *requires* this kind-matching
-- to instantiate template type variables, but it seems like the right
-- thing to do. C.f. Note [Matching variable types] in Rules.hs
--------------
match_tys :: MatchEnv -> TvSubstEnv -> [Type] -> [Type] -> Maybe TvSubstEnv
match_tys menv subst tys1 tys2 = matchList (match menv) subst tys1 tys2
--------------
matchList :: (env -> a -> b -> Maybe env)
-> env -> [a] -> [b] -> Maybe env
matchList _ subst [] [] = Just subst
matchList fn subst (a:as) (b:bs) = do { subst' <- fn subst a b
; matchList fn subst' as bs }
matchList _ _ _ _ = Nothing
{-
************************************************************************
* *
GADTs
* *
************************************************************************
Note [Pruning dead case alternatives]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider data T a where
T1 :: T Int
T2 :: T a
newtype X = MkX Int
newtype Y = MkY Char
type family F a
type instance F Bool = Int
Now consider case x of { T1 -> e1; T2 -> e2 }
The question before the house is this: if I know something about the type
of x, can I prune away the T1 alternative?
Suppose x::T Char. It's impossible to construct a (T Char) using T1,
Answer = YES we can prune the T1 branch (clearly)
Suppose x::T (F a), where 'a' is in scope. Then 'a' might be instantiated
to 'Bool', in which case x::T Int, so
ANSWER = NO (clearly)
We see here that we want precisely the apartness check implemented within
tcUnifyTysFG. So that's what we do! Two types cannot match if they are surely
apart. Note that since we are simply dropping dead code, a conservative test
suffices.
-}
-- | Given a list of pairs of types, are any two members of a pair surely
-- apart, even after arbitrary type function evaluation and substitution?
typesCantMatch :: [(Type,Type)] -> Bool
-- See Note [Pruning dead case alternatives]
typesCantMatch prs = any (\(s,t) -> cant_match s t) prs
where
cant_match :: Type -> Type -> Bool
cant_match t1 t2 = case tcUnifyTysFG (const BindMe) [t1] [t2] of
SurelyApart -> True
_ -> False
{-
************************************************************************
* *
Unification
* *
************************************************************************
Note [Fine-grained unification]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Do the types (x, x) and ([y], y) unify? The answer is seemingly "no" --
no substitution to finite types makes these match. But, a substitution to
*infinite* types can unify these two types: [x |-> [[[...]]], y |-> [[[...]]] ].
Why do we care? Consider these two type family instances:
type instance F x x = Int
type instance F [y] y = Bool
If we also have
type instance Looper = [Looper]
then the instances potentially overlap. The solution is to use unification
over infinite terms. This is possible (see [1] for lots of gory details), but
a full algorithm is a little more power than we need. Instead, we make a
conservative approximation and just omit the occurs check.
[1]: http://research.microsoft.com/en-us/um/people/simonpj/papers/ext-f/axioms-extended.pdf
tcUnifyTys considers an occurs-check problem as the same as general unification
failure.
tcUnifyTysFG ("fine-grained") returns one of three results: success, occurs-check
failure ("MaybeApart"), or general failure ("SurelyApart").
See also Trac #8162.
It's worth noting that unification in the presence of infinite types is not
complete. This means that, sometimes, a closed type family does not reduce
when it should. See test case indexed-types/should_fail/Overlap15 for an
example.
Note [The substitution in MaybeApart]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The constructor MaybeApart carries data with it, typically a TvSubstEnv. Why?
Because consider unifying these:
(a, a, Int) ~ (b, [b], Bool)
If we go left-to-right, we start with [a |-> b]. Then, on the middle terms, we
apply the subst we have so far and discover that we need [b |-> [b]]. Because
this fails the occurs check, we say that the types are MaybeApart (see above
Note [Fine-grained unification]). But, we can't stop there! Because if we
continue, we discover that Int is SurelyApart from Bool, and therefore the
types are apart. This has practical consequences for the ability for closed
type family applications to reduce. See test case
indexed-types/should_compile/Overlap14.
Note [Unifying with skolems]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
If we discover that two types unify if and only if a skolem variable is
substituted, we can't properly unify the types. But, that skolem variable
may later be instantiated with a unifyable type. So, we return maybeApart
in these cases.
Note [Lists of different lengths are MaybeApart]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
It is unusual to call tcUnifyTys or tcUnifyTysFG with lists of different
lengths. The place where we know this can happen is from compatibleBranches in
FamInstEnv, when checking data family instances. Data family instances may be
eta-reduced; see Note [Eta reduction for data family axioms] in TcInstDcls.
We wish to say that
D :: * -> * -> *
axDF1 :: D Int ~ DFInst1
axDF2 :: D Int Bool ~ DFInst2
overlap. If we conclude that lists of different lengths are SurelyApart, then
it will look like these do *not* overlap, causing disaster. See Trac #9371.
In usages of tcUnifyTys outside of family instances, we always use tcUnifyTys,
which can't tell the difference between MaybeApart and SurelyApart, so those
usages won't notice this design choice.
-}
tcUnifyTy :: Type -> Type -- All tyvars are bindable
-> Maybe TvSubst -- A regular one-shot (idempotent) substitution
-- Simple unification of two types; all type variables are bindable
tcUnifyTy ty1 ty2
= case initUM (const BindMe) (unify ty1 ty2) of
Unifiable subst -> Just subst
_other -> Nothing
-- | Unify two types, treating type family applications as possibly unifying
-- with anything and looking through injective type family applications.
tcUnifyTyWithTFs :: Bool -> Type -> Type -> Maybe TvSubst
-- This algorithm is a direct implementation of the "Algorithm U" presented in
-- the paper "Injective type families for Haskell", Figures 2 and 3. Equation
-- numbers in the comments refer to equations from the paper.
tcUnifyTyWithTFs twoWay t1 t2 = niFixTvSubst `fmap` go t1 t2 emptyTvSubstEnv
where
go :: Type -> Type -> TvSubstEnv -> Maybe TvSubstEnv
-- look through type synonyms
go t1 t2 theta | Just t1' <- tcView t1 = go t1' t2 theta
go t1 t2 theta | Just t2' <- tcView t2 = go t1 t2' theta
-- proper unification
go (TyVarTy tv) t2 theta
-- Equation (1)
| Just t1' <- lookupVarEnv theta tv
= go t1' t2 theta
| otherwise = let t2' = Type.substTy (niFixTvSubst theta) t2
in if tv `elemVarEnv` tyVarsOfType t2'
-- Equation (2)
then Just theta
-- Equation (3)
else Just $ extendVarEnv theta tv t2'
-- Equation (4)
go t1 t2@(TyVarTy _) theta | twoWay = go t2 t1 theta
-- Equation (5)
go (AppTy s1 s2) ty theta | Just(t1, t2) <- splitAppTy_maybe ty =
go s1 t1 theta >>= go s2 t2
go ty (AppTy s1 s2) theta | Just(t1, t2) <- splitAppTy_maybe ty =
go s1 t1 theta >>= go s2 t2
go (TyConApp tc1 tys1) (TyConApp tc2 tys2) theta
-- Equation (6)
| isAlgTyCon tc1 && isAlgTyCon tc2 && tc1 == tc2
= let tys = zip tys1 tys2
in foldM (\theta' (t1,t2) -> go t1 t2 theta') theta tys
-- Equation (7)
| isTypeFamilyTyCon tc1 && isTypeFamilyTyCon tc2 && tc1 == tc2
, Injective inj <- familyTyConInjectivityInfo tc1
= let tys1' = filterByList inj tys1
tys2' = filterByList inj tys2
injTys = zip tys1' tys2'
in foldM (\theta' (t1,t2) -> go t1 t2 theta') theta injTys
-- Equations (8)
| isTypeFamilyTyCon tc1
= Just theta
-- Equations (9)
| isTypeFamilyTyCon tc2, twoWay
= Just theta
-- Equation (10)
go _ _ _ = Nothing
-----------------
tcUnifyTys :: (TyVar -> BindFlag)
-> [Type] -> [Type]
-> Maybe TvSubst -- A regular one-shot (idempotent) substitution
-- The two types may have common type variables, and indeed do so in the
-- second call to tcUnifyTys in FunDeps.checkClsFD
tcUnifyTys bind_fn tys1 tys2
= case tcUnifyTysFG bind_fn tys1 tys2 of
Unifiable subst -> Just subst
_ -> Nothing
-- This type does double-duty. It is used in the UM (unifier monad) and to
-- return the final result. See Note [Fine-grained unification]
type UnifyResult = UnifyResultM TvSubst
data UnifyResultM a = Unifiable a -- the subst that unifies the types
| MaybeApart a -- the subst has as much as we know
-- it must be part of an most general unifier
-- See Note [The substitution in MaybeApart]
| SurelyApart
deriving Functor
-- See Note [Fine-grained unification]
tcUnifyTysFG :: (TyVar -> BindFlag)
-> [Type] -> [Type]
-> UnifyResult
tcUnifyTysFG bind_fn tys1 tys2
= initUM bind_fn (unify_tys tys1 tys2)
instance Outputable a => Outputable (UnifyResultM a) where
ppr SurelyApart = ptext (sLit "SurelyApart")
ppr (Unifiable x) = ptext (sLit "Unifiable") <+> ppr x
ppr (MaybeApart x) = ptext (sLit "MaybeApart") <+> ppr x
{-
************************************************************************
* *
Non-idempotent substitution
* *
************************************************************************
Note [Non-idempotent substitution]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
During unification we use a TvSubstEnv that is
(a) non-idempotent
(b) loop-free; ie repeatedly applying it yields a fixed point
Note [Finding the substitution fixpoint]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Finding the fixpoint of a non-idempotent substitution arising from a
unification is harder than it looks, because of kinds. Consider
T k (H k (f:k)) ~ T * (g:*)
If we unify, we get the substitution
[ k -> *
, g -> H k (f:k) ]
To make it idempotent we don't want to get just
[ k -> *
, g -> H * (f:k) ]
We also want to substitute inside f's kind, to get
[ k -> *
, g -> H k (f:*) ]
If we don't do this, we may apply the substitition to something,
and get an ill-formed type, i.e. one where typeKind will fail.
This happened, for example, in Trac #9106.
This is the reason for extending env with [f:k -> f:*], in the
definition of env' in niFixTvSubst
-}
niFixTvSubst :: TvSubstEnv -> TvSubst
-- Find the idempotent fixed point of the non-idempotent substitution
-- See Note [Finding the substitution fixpoint]
-- ToDo: use laziness instead of iteration?
niFixTvSubst env = f env
where
f env | not_fixpoint = f (mapVarEnv (substTy subst') env)
| otherwise = subst
where
not_fixpoint = foldVarSet ((||) . in_domain) False all_range_tvs
in_domain tv = tv `elemVarEnv` env
range_tvs = foldVarEnv (unionVarSet . tyVarsOfType) emptyVarSet env
all_range_tvs = closeOverKinds range_tvs
subst = mkTvSubst (mkInScopeSet all_range_tvs) env
-- env' extends env by replacing any free type with
-- that same tyvar with a substituted kind
-- See note [Finding the substitution fixpoint]
env' = extendVarEnvList env [ (rtv, mkTyVarTy $ setTyVarKind rtv $
substTy subst $ tyVarKind rtv)
| rtv <- varSetElems range_tvs
, not (in_domain rtv) ]
subst' = mkTvSubst (mkInScopeSet all_range_tvs) env'
niSubstTvSet :: TvSubstEnv -> TyVarSet -> TyVarSet
-- Apply the non-idempotent substitution to a set of type variables,
-- remembering that the substitution isn't necessarily idempotent
-- This is used in the occurs check, before extending the substitution
niSubstTvSet subst tvs
= foldVarSet (unionVarSet . get) emptyVarSet tvs
where
get tv = case lookupVarEnv subst tv of
Nothing -> unitVarSet tv
Just ty -> niSubstTvSet subst (tyVarsOfType ty)
{-
************************************************************************
* *
The workhorse
* *
************************************************************************
-}
unify :: Type -> Type -> UM ()
-- Respects newtypes, PredTypes
-- in unify, any NewTcApps/Preds should be taken at face value
unify (TyVarTy tv1) ty2 = uVar tv1 ty2
unify ty1 (TyVarTy tv2) = uVar tv2 ty1
unify ty1 ty2 | Just ty1' <- tcView ty1 = unify ty1' ty2
unify ty1 ty2 | Just ty2' <- tcView ty2 = unify ty1 ty2'
unify ty1 ty2
| Just (tc1, tys1) <- splitTyConApp_maybe ty1
, Just (tc2, tys2) <- splitTyConApp_maybe ty2
= if tc1 == tc2
then if isInjectiveTyCon tc1 Nominal
then unify_tys tys1 tys2
else don'tBeSoSure $ unify_tys tys1 tys2
else -- tc1 /= tc2
if isGenerativeTyCon tc1 Nominal && isGenerativeTyCon tc2 Nominal
then surelyApart
else maybeApart
-- Applications need a bit of care!
-- They can match FunTy and TyConApp, so use splitAppTy_maybe
-- NB: we've already dealt with type variables and Notes,
-- so if one type is an App the other one jolly well better be too
unify (AppTy ty1a ty1b) ty2
| Just (ty2a, ty2b) <- repSplitAppTy_maybe ty2
= do { unify ty1a ty2a
; unify ty1b ty2b }
unify ty1 (AppTy ty2a ty2b)
| Just (ty1a, ty1b) <- repSplitAppTy_maybe ty1
= do { unify ty1a ty2a
; unify ty1b ty2b }
unify (LitTy x) (LitTy y) | x == y = return ()
unify _ _ = surelyApart
-- ForAlls??
------------------------------
unify_tys :: [Type] -> [Type] -> UM ()
unify_tys orig_xs orig_ys
= go orig_xs orig_ys
where
go [] [] = return ()
go (x:xs) (y:ys) = do { unify x y
; go xs ys }
go _ _ = maybeApart -- See Note [Lists of different lengths are MaybeApart]
---------------------------------
uVar :: TyVar -- Type variable to be unified
-> Type -- with this type
-> UM ()
uVar tv1 ty
= do { subst <- umGetTvSubstEnv
-- Check to see whether tv1 is refined by the substitution
; case (lookupVarEnv subst tv1) of
Just ty' -> unify ty' ty -- Yes, call back into unify'
Nothing -> uUnrefined subst tv1 ty ty } -- No, continue
uUnrefined :: TvSubstEnv -- environment to extend (from the UM monad)
-> TyVar -- Type variable to be unified
-> Type -- with this type
-> Type -- (version w/ expanded synonyms)
-> UM ()
-- We know that tv1 isn't refined
uUnrefined subst tv1 ty2 ty2'
| Just ty2'' <- tcView ty2'
= uUnrefined subst tv1 ty2 ty2'' -- Unwrap synonyms
-- This is essential, in case we have
-- type Foo a = a
-- and then unify a ~ Foo a
uUnrefined subst tv1 ty2 (TyVarTy tv2)
| tv1 == tv2 -- Same type variable
= return ()
-- Check to see whether tv2 is refined
| Just ty' <- lookupVarEnv subst tv2
= uUnrefined subst tv1 ty' ty'
| otherwise
= do { -- So both are unrefined; unify the kinds
; unify (tyVarKind tv1) (tyVarKind tv2)
-- And then bind one or the other,
-- depending on which is bindable
-- NB: unlike TcUnify we do not have an elaborate sub-kinding
-- story. That is relevant only during type inference, and
-- (I very much hope) is not relevant here.
; b1 <- tvBindFlag tv1
; b2 <- tvBindFlag tv2
; let ty1 = TyVarTy tv1
; case (b1, b2) of
(Skolem, Skolem) -> maybeApart -- See Note [Unification with skolems]
(BindMe, _) -> extendSubst tv1 ty2
(_, BindMe) -> extendSubst tv2 ty1 }
uUnrefined subst tv1 ty2 ty2' -- ty2 is not a type variable
| tv1 `elemVarSet` niSubstTvSet subst (tyVarsOfType ty2')
= maybeApart -- Occurs check
-- See Note [Fine-grained unification]
| otherwise
= do { unify k1 k2
-- Note [Kinds Containing Only Literals]
; bindTv tv1 ty2 } -- Bind tyvar to the synonym if poss
where
k1 = tyVarKind tv1
k2 = typeKind ty2'
bindTv :: TyVar -> Type -> UM ()
bindTv tv ty -- ty is not a type variable
= do { b <- tvBindFlag tv
; case b of
Skolem -> maybeApart -- See Note [Unification with skolems]
BindMe -> extendSubst tv ty
}
{-
************************************************************************
* *
Binding decisions
* *
************************************************************************
-}
data BindFlag
= BindMe -- A regular type variable
| Skolem -- This type variable is a skolem constant
-- Don't bind it; it only matches itself
{-
************************************************************************
* *
Unification monad
* *
************************************************************************
-}
newtype UM a = UM { unUM :: (TyVar -> BindFlag)
-> TvSubstEnv
-> UnifyResultM (a, TvSubstEnv) }
instance Functor UM where
fmap = liftM
instance Applicative UM where
pure a = UM (\_tvs subst -> Unifiable (a, subst))
(<*>) = ap
instance Monad UM where
return = pure
fail _ = UM (\_tvs _subst -> SurelyApart) -- failed pattern match
m >>= k = UM (\tvs subst -> case unUM m tvs subst of
Unifiable (v, subst') -> unUM (k v) tvs subst'
MaybeApart (v, subst') ->
case unUM (k v) tvs subst' of
Unifiable (v', subst'') -> MaybeApart (v', subst'')
other -> other
SurelyApart -> SurelyApart)
-- returns an idempotent substitution
initUM :: (TyVar -> BindFlag) -> UM () -> UnifyResult
initUM badtvs um = fmap (niFixTvSubst . snd) $ unUM um badtvs emptyTvSubstEnv
tvBindFlag :: TyVar -> UM BindFlag
tvBindFlag tv = UM (\tv_fn subst -> Unifiable (tv_fn tv, subst))
-- | Extend the TvSubstEnv in the UM monad
extendSubst :: TyVar -> Type -> UM ()
extendSubst tv ty = UM (\_tv_fn subst -> Unifiable ((), extendVarEnv subst tv ty))
-- | Retrive the TvSubstEnv from the UM monad
umGetTvSubstEnv :: UM TvSubstEnv
umGetTvSubstEnv = UM $ \_tv_fn subst -> Unifiable (subst, subst)
-- | Converts any SurelyApart to a MaybeApart
don'tBeSoSure :: UM () -> UM ()
don'tBeSoSure um = UM $ \tv_fn subst -> case unUM um tv_fn subst of
SurelyApart -> MaybeApart ((), subst)
other -> other
maybeApart :: UM ()
maybeApart = UM (\_tv_fn subst -> MaybeApart ((), subst))
surelyApart :: UM a
surelyApart = UM (\_tv_fn _subst -> SurelyApart)
| AlexanderPankiv/ghc | compiler/types/Unify.hs | bsd-3-clause | 29,646 | 15 | 16 | 9,074 | 4,744 | 2,473 | 2,271 | 324 | 9 |
--------------------------------------------------------------------------------
-- |
-- Module : Graphics.Rendering.OpenGL.GL.Texturing.Specification
-- Copyright : (c) Sven Panne 2002-2013
-- License : BSD3
--
-- Maintainer : Sven Panne <svenpanne@gmail.com>
-- Stability : stable
-- Portability : portable
--
-- This module corresponds to section 3.8.1 (Texture Image Specification),
-- section 3.8.2 (Alternate Texture Image Specification Commands), and section
-- 3.8.3 (Compressed Texture Images) of the OpenGL 2.1 specs.
--
--------------------------------------------------------------------------------
module Graphics.Rendering.OpenGL.GL.Texturing.Specification (
-- * Texture Targets
-- ** One-Dimensional Texture Targets
TextureTarget1D(..),
-- ** Two-Dimensional Texture Targets
TextureTarget2D(..),
TextureTarget2DMultisample(..),
TextureTargetCubeMap(..),
TextureTargetCubeMapFace(..),
-- ** Three-Dimensional Texture Targets
TextureTarget3D(..),
TextureTarget2DMultisampleArray(..),
-- ** Texture Buffer Target
TextureTargetBuffer(..),
-- ** Texture Target Classification
BindableTextureTarget,
ParameterizedTextureTarget,
OneDimensionalTextureTarget,
TwoDimensionalTextureTarget,
ThreeDimensionalTextureTarget,
QueryableTextureTarget,
GettableTextureTarget,
-- * Texture-related Data Types
Level, Border,
TexturePosition1D(..), TexturePosition2D(..), TexturePosition3D(..),
TextureSize1D(..), TextureSize2D(..), TextureSize3D(..),
-- * Texture Image Specification
texImage1D, texImage2D, texImage3D,
copyTexImage1D, copyTexImage2D,
texSubImage1D, texSubImage2D, texSubImage3D,
getTexImage,
-- * Alternate Texture Image Specification Commands
copyTexSubImage1D, copyTexSubImage2D, copyTexSubImage3D,
-- * Compressed Texture Images
CompressedTextureFormat(..), compressedTextureFormats,
CompressedPixelData(..),
compressedTexImage1D, compressedTexImage2D, compressedTexImage3D,
compressedTexSubImage1D, compressedTexSubImage2D, compressedTexSubImage3D,
getCompressedTexImage,
-- * Multisample Texture Images
SampleLocations(..), texImage2DMultisample, texImage3DMultisample,
-- * Implementation-Dependent Limits
maxTextureSize, maxCubeMapTextureSize, maxRectangleTextureSize,
max3DTextureSize, maxArrayTextureLayers, maxSampleMaskWords,
maxColorTextureSamples, maxDepthTextureSamples, maxIntegerSamples
) where
import Foreign.Ptr
import Graphics.Rendering.OpenGL.GL.CoordTrans
import Graphics.Rendering.OpenGL.GL.FramebufferObjects.RenderbufferTarget
import Graphics.Rendering.OpenGL.GL.GLboolean
import Graphics.Rendering.OpenGL.GL.PixelData
import Graphics.Rendering.OpenGL.GL.PixelRectangles
import Graphics.Rendering.OpenGL.GL.QueryUtils
import Graphics.Rendering.OpenGL.GL.StateVar
import Graphics.Rendering.OpenGL.GL.Texturing.PixelInternalFormat
import Graphics.Rendering.OpenGL.GL.Texturing.TextureTarget
import Graphics.Rendering.OpenGL.Raw
--------------------------------------------------------------------------------
type Level = GLint
type Border = GLint
newtype TexturePosition1D = TexturePosition1D GLint
deriving ( Eq, Ord, Show )
data TexturePosition2D = TexturePosition2D !GLint !GLint
deriving ( Eq, Ord, Show )
data TexturePosition3D = TexturePosition3D !GLint !GLint !GLint
deriving ( Eq, Ord, Show )
newtype TextureSize1D = TextureSize1D GLsizei
deriving ( Eq, Ord, Show )
data TextureSize2D = TextureSize2D !GLsizei !GLsizei
deriving ( Eq, Ord, Show )
data TextureSize3D = TextureSize3D !GLsizei !GLsizei !GLsizei
deriving ( Eq, Ord, Show )
--------------------------------------------------------------------------------
texImage1D :: OneDimensionalTextureTarget t => t -> Proxy -> Level -> PixelInternalFormat -> TextureSize1D -> Border -> PixelData a -> IO ()
texImage1D target proxy level int (TextureSize1D w) border pd =
withPixelData pd $
glTexImage1D
(marshalOneDimensionalTextureTarget proxy target)
level (marshalPixelInternalFormat int) w border
--------------------------------------------------------------------------------
texImage2D :: TwoDimensionalTextureTarget t => t -> Proxy -> Level -> PixelInternalFormat -> TextureSize2D -> Border -> PixelData a -> IO ()
texImage2D target proxy level int (TextureSize2D w h) border pd =
withPixelData pd $
glTexImage2D (marshalTwoDimensionalTextureTarget proxy target) level (marshalPixelInternalFormat int) w h border
--------------------------------------------------------------------------------
texImage3D :: ThreeDimensionalTextureTarget t => t -> Proxy -> Level -> PixelInternalFormat -> TextureSize3D -> Border -> PixelData a -> IO ()
texImage3D target proxy level int (TextureSize3D w h d) border pd =
withPixelData pd $
glTexImage3D
(marshalThreeDimensionalTextureTarget proxy target)
level (marshalPixelInternalFormat int) w h d border
--------------------------------------------------------------------------------
getTexImage :: GettableTextureTarget t => t -> Level -> PixelData a -> IO ()
getTexImage target level pd =
withPixelData pd $
glGetTexImage (marshalGettableTextureTarget target) level
--------------------------------------------------------------------------------
copyTexImage1D :: OneDimensionalTextureTarget t => t -> Level -> PixelInternalFormat -> Position -> TextureSize1D -> Border -> IO ()
copyTexImage1D target level int (Position x y) (TextureSize1D w) border =
glCopyTexImage1D
(marshalOneDimensionalTextureTarget NoProxy target) level
(marshalPixelInternalFormat' int) x y w border
--------------------------------------------------------------------------------
copyTexImage2D :: TwoDimensionalTextureTarget t => t -> Level -> PixelInternalFormat -> Position -> TextureSize2D -> Border -> IO ()
copyTexImage2D target level int (Position x y) (TextureSize2D w h) border =
glCopyTexImage2D
(marshalTwoDimensionalTextureTarget NoProxy target) level
(marshalPixelInternalFormat' int) x y w h border
--------------------------------------------------------------------------------
texSubImage1D :: OneDimensionalTextureTarget t => t -> Level -> TexturePosition1D -> TextureSize1D -> PixelData a -> IO ()
texSubImage1D target level (TexturePosition1D xOff) (TextureSize1D w) pd =
withPixelData pd $
glTexSubImage1D (marshalOneDimensionalTextureTarget NoProxy target) level xOff w
--------------------------------------------------------------------------------
texSubImage2D :: TwoDimensionalTextureTarget t => t -> Level -> TexturePosition2D -> TextureSize2D -> PixelData a -> IO ()
texSubImage2D target level (TexturePosition2D xOff yOff) (TextureSize2D w h) pd =
withPixelData pd $
glTexSubImage2D (marshalTwoDimensionalTextureTarget NoProxy target) level xOff yOff w h
--------------------------------------------------------------------------------
texSubImage3D :: ThreeDimensionalTextureTarget t => t -> Level -> TexturePosition3D -> TextureSize3D -> PixelData a -> IO ()
texSubImage3D target level (TexturePosition3D xOff yOff zOff) (TextureSize3D w h d) pd =
withPixelData pd $
glTexSubImage3D (marshalThreeDimensionalTextureTarget NoProxy target) level xOff yOff zOff w h d
--------------------------------------------------------------------------------
copyTexSubImage1D :: OneDimensionalTextureTarget t => t -> Level -> TexturePosition1D -> Position -> TextureSize1D -> IO ()
copyTexSubImage1D target level (TexturePosition1D xOff) (Position x y) (TextureSize1D w) =
glCopyTexSubImage1D (marshalOneDimensionalTextureTarget NoProxy target) level xOff x y w
--------------------------------------------------------------------------------
copyTexSubImage2D :: TwoDimensionalTextureTarget t => t -> Level -> TexturePosition2D -> Position -> TextureSize2D -> IO ()
copyTexSubImage2D target level (TexturePosition2D xOff yOff) (Position x y) (TextureSize2D w h) =
glCopyTexSubImage2D (marshalTwoDimensionalTextureTarget NoProxy target) level xOff yOff x y w h
--------------------------------------------------------------------------------
copyTexSubImage3D :: ThreeDimensionalTextureTarget t => t -> Level -> TexturePosition3D -> Position -> TextureSize2D -> IO ()
copyTexSubImage3D target level (TexturePosition3D xOff yOff zOff) (Position x y) (TextureSize2D w h) =
glCopyTexSubImage3D (marshalThreeDimensionalTextureTarget NoProxy target) level xOff yOff zOff x y w h
--------------------------------------------------------------------------------
newtype CompressedTextureFormat = CompressedTextureFormat GLenum
deriving ( Eq, Ord, Show )
compressedTextureFormats :: GettableStateVar [CompressedTextureFormat]
compressedTextureFormats =
makeGettableStateVar $ do
n <- getInteger1 fromIntegral GetNumCompressedTextureFormats
getEnumN CompressedTextureFormat GetCompressedTextureFormats n
--------------------------------------------------------------------------------
data CompressedPixelData a =
CompressedPixelData !CompressedTextureFormat GLsizei (Ptr a)
deriving ( Eq, Ord, Show )
withCompressedPixelData ::
CompressedPixelData a -> (GLenum -> GLsizei -> Ptr a -> b) -> b
withCompressedPixelData
(CompressedPixelData (CompressedTextureFormat fmt) size ptr) f =
f fmt size ptr
--------------------------------------------------------------------------------
compressedTexImage1D :: OneDimensionalTextureTarget t => t -> Proxy -> Level -> TextureSize1D -> Border -> CompressedPixelData a -> IO ()
compressedTexImage1D target proxy level (TextureSize1D w) border cpd =
withCompressedPixelData cpd $ \fmt ->
glCompressedTexImage1D
(marshalOneDimensionalTextureTarget proxy target) level fmt w border
--------------------------------------------------------------------------------
-- Note that the spec currently disallows TextureRectangle, but then again the
-- extension specification explicitly allows a relaxation in the future.
compressedTexImage2D :: TwoDimensionalTextureTarget t => t -> Proxy -> Level -> TextureSize2D -> Border -> CompressedPixelData a -> IO ()
compressedTexImage2D target proxy level (TextureSize2D w h) border cpd =
withCompressedPixelData cpd $ \fmt ->
glCompressedTexImage2D (marshalTwoDimensionalTextureTarget proxy target) level fmt w h border
--------------------------------------------------------------------------------
compressedTexImage3D :: ThreeDimensionalTextureTarget t => t -> Proxy -> Level -> TextureSize3D -> Border -> CompressedPixelData a -> IO ()
compressedTexImage3D target proxy level (TextureSize3D w h d) border cpd =
withCompressedPixelData cpd $ \fmt ->
glCompressedTexImage3D
(marshalThreeDimensionalTextureTarget proxy target) level fmt w h d border
--------------------------------------------------------------------------------
getCompressedTexImage :: GettableTextureTarget t => t -> Level -> Ptr a -> IO ()
getCompressedTexImage = glGetCompressedTexImage . marshalGettableTextureTarget
--------------------------------------------------------------------------------
compressedTexSubImage1D :: OneDimensionalTextureTarget t => t -> Level -> TexturePosition1D -> TextureSize1D -> CompressedPixelData a -> IO ()
compressedTexSubImage1D target level (TexturePosition1D xOff) (TextureSize1D w) cpd =
withCompressedPixelData cpd $
glCompressedTexSubImage1D (marshalOneDimensionalTextureTarget NoProxy target) level xOff w
--------------------------------------------------------------------------------
compressedTexSubImage2D :: TwoDimensionalTextureTarget t => t -> Level -> TexturePosition2D -> TextureSize2D -> CompressedPixelData a -> IO ()
compressedTexSubImage2D target level (TexturePosition2D xOff yOff) (TextureSize2D w h) cpd =
withCompressedPixelData cpd $
glCompressedTexSubImage2D (marshalTwoDimensionalTextureTarget NoProxy target) level xOff yOff w h
--------------------------------------------------------------------------------
-- see texImage3D, but no proxies
compressedTexSubImage3D :: ThreeDimensionalTextureTarget t => t -> Level -> TexturePosition3D -> TextureSize3D -> CompressedPixelData a -> IO ()
compressedTexSubImage3D target level (TexturePosition3D xOff yOff zOff) (TextureSize3D w h d) cpd =
withCompressedPixelData cpd $
glCompressedTexSubImage3D (marshalThreeDimensionalTextureTarget NoProxy target) level xOff yOff zOff w h d
--------------------------------------------------------------------------------
data SampleLocations =
FlexibleSampleLocations
| FixedSampleLocations
deriving ( Eq, Ord, Show )
marshalSampleLocations :: SampleLocations -> GLboolean
marshalSampleLocations = marshalGLboolean . (FixedSampleLocations ==)
{-
unmarshalSampleLocations :: GLboolean -> SampleLocations
unmarshalSampleLocations x =
if unmarshalGLboolean x
then FixedSampleLocations
else FlexibleSampleLocations
-}
--------------------------------------------------------------------------------
texImage2DMultisample :: TextureTarget2DMultisample
-> Proxy
-> Samples
-> PixelInternalFormat
-> TextureSize2D
-> SampleLocations
-> IO ()
texImage2DMultisample target proxy (Samples s) int (TextureSize2D w h) loc =
glTexImage2DMultisample
(marshalMultisample proxy target) s (marshalPixelInternalFormat int)
w h (marshalSampleLocations loc)
marshalMultisample :: ParameterizedTextureTarget t => Proxy -> t -> GLenum
marshalMultisample proxy = case proxy of
NoProxy -> marshalParameterizedTextureTarget
Proxy -> marshalParameterizedTextureTargetProxy
texImage3DMultisample :: TextureTarget2DMultisampleArray
-> Proxy
-> Samples
-> PixelInternalFormat
-> TextureSize3D
-> SampleLocations
-> IO ()
texImage3DMultisample target proxy (Samples s) int (TextureSize3D w h d) loc =
glTexImage3DMultisample
(marshalMultisample proxy target) s (marshalPixelInternalFormat int)
w h d (marshalSampleLocations loc)
--------------------------------------------------------------------------------
maxTextureSize :: GettableStateVar GLsizei
maxTextureSize = maxTextureSizeWith GetMaxTextureSize
maxCubeMapTextureSize :: GettableStateVar GLsizei
maxCubeMapTextureSize = maxTextureSizeWith GetMaxCubeMapTextureSize
maxRectangleTextureSize :: GettableStateVar GLsizei
maxRectangleTextureSize = maxTextureSizeWith GetMaxRectangleTextureSize
max3DTextureSize :: GettableStateVar GLsizei
max3DTextureSize = maxTextureSizeWith GetMax3DTextureSize
maxArrayTextureLayers :: GettableStateVar GLsizei
maxArrayTextureLayers = maxTextureSizeWith GetMaxArrayTextureLayers
maxSampleMaskWords :: GettableStateVar GLsizei
maxSampleMaskWords = maxTextureSizeWith GetMaxSampleMaskWords
maxColorTextureSamples :: GettableStateVar GLsizei
maxColorTextureSamples = maxTextureSizeWith GetMaxColorTextureSamples
maxDepthTextureSamples :: GettableStateVar GLsizei
maxDepthTextureSamples = maxTextureSizeWith GetMaxDepthTextureSamples
maxIntegerSamples :: GettableStateVar GLsizei
maxIntegerSamples = maxTextureSizeWith GetMaxIntegerSamples
maxTextureSizeWith :: PName1I -> GettableStateVar GLsizei
maxTextureSizeWith = makeGettableStateVar . getInteger1 fromIntegral
| IreneKnapp/direct-opengl | Graphics/Rendering/OpenGL/GL/Texturing/Specification.hs | bsd-3-clause | 15,581 | 0 | 14 | 2,231 | 3,051 | 1,601 | 1,450 | 226 | 2 |
{-# language OverloadedStrings #-}
module Yi.Keymap.Vim.Substitution
( substituteE
, substituteConfirmE
, repeatSubstitutionE
, repeatSubstitutionFlaglessE
) where
import Control.Monad (void)
import Data.Monoid
import Yi.MiniBuffer
import Yi.Keymap (Keymap)
import qualified Yi.Rope as R
import Yi.Regex
import Yi.Buffer
import Yi.Editor
import Yi.Search
import Yi.Keymap.Keys (char, choice, (?>>!))
import Yi.Keymap.Vim.Common
import Yi.Keymap.Vim.StateUtils
substituteE :: Substitution -> BufferM Region -> EditorM ()
substituteE s@(Substitution from to global caseInsensitive confirm) regionB = do
let opts = if caseInsensitive then [IgnoreCase] else []
lines' <- withCurrentBuffer $ regionB >>= linesOfRegionB
regex <- if R.null from
then getRegexE
else return . (either (const Nothing) Just)
. makeSearchOptsM opts . R.toString $ from
case regex of
Nothing -> printMsg "No previous search pattern"
Just regex' -> do
saveSubstitutionE s
if confirm
then substituteConfirmE regex' to global lines'
else do
withCurrentBuffer $ do
-- We need to reverse the lines' here so that replacing
-- does not effect the regions in question.
mapM_ (void . searchAndRepRegion0 regex' to global) (reverse lines')
moveToSol
-- | Run substitution in confirm mode
substituteConfirmE :: SearchExp -> R.YiString -> Bool -> [Region] -> EditorM ()
substituteConfirmE regex to global lines' = do
-- TODO This highlights all matches, even in non-global mode
-- and could potentially be classified as a bug. Fixing requires
-- changing the regex highlighting api.
setRegexE regex
regions <- withCurrentBuffer $ findMatches regex global lines'
substituteMatch to 0 False regions
-- | All matches to replace under given flags
findMatches :: SearchExp -> Bool -> [Region] -> BufferM [Region]
findMatches regex global lines' = do
let f = if global then id else take 1
concat <$> mapM (fmap f . regexRegionB regex) lines'
-- | Runs a list of matches using itself as a continuation
substituteMatch :: R.YiString -> Int -> Bool -> [Region] -> EditorM ()
substituteMatch _ _ _ [] = resetRegexE
substituteMatch to co autoAll (m:ms) = do
let m' = offsetRegion co m
withCurrentBuffer . moveTo $ regionStart m'
len <- withCurrentBuffer $ R.length <$> readRegionB m'
let diff = R.length to - len
tex = "replace with " <> R.toText to <> " (y/n/a/q)?"
if autoAll
then do withCurrentBuffer $ replaceRegionB m' to
substituteMatch to (co + diff) True ms
else void . spawnMinibufferE tex . const $ askKeymap to co (co + diff) m ms
-- | Offsets a region (to account for a region prior being modified)
offsetRegion :: Int -> Region -> Region
offsetRegion k reg = mkRegion (regionStart reg + k') (regionEnd reg + k')
where k' = fromIntegral k
-- | Actual choices during confirm mode.
askKeymap :: R.YiString -> Int -> Int -> Region -> [Region] -> Keymap
askKeymap to co co' m ms = choice [
char 'n' ?>>! cleanUp >> substituteMatch to co False ms
, char 'a' ?>>! do cleanUp
replace
substituteMatch to co' True ms
, char 'y' ?>>! do cleanUp
replace
substituteMatch to co' False ms
, char 'q' ?>>! cleanUp >> resetRegexE
]
where cleanUp = closeBufferAndWindowE
replace = withCurrentBuffer $ replaceRegionB (offsetRegion co m) to
repeatSubstitutionFlaglessE :: Substitution -> EditorM ()
repeatSubstitutionFlaglessE (Substitution from to _ _ _) =
substituteE (Substitution from to False False False) (regionOfB Line)
repeatSubstitutionE :: Substitution -> EditorM ()
repeatSubstitutionE s = substituteE s (regionOfB Line)
| noughtmare/yi | yi-keymap-vim/src/Yi/Keymap/Vim/Substitution.hs | gpl-2.0 | 4,036 | 0 | 21 | 1,103 | 1,067 | 540 | 527 | 77 | 5 |
{- data size display and parsing
-
- Copyright 2011 Joey Hess <id@joeyh.name>
-
- License: BSD-2-clause
-
-
- And now a rant:
-
- In the beginning, we had powers of two, and they were good.
-
- Disk drive manufacturers noticed that some powers of two were
- sorta close to some powers of ten, and that rounding down to the nearest
- power of ten allowed them to advertise their drives were bigger. This
- was sorta annoying.
-
- Then drives got big. Really, really big. This was good.
-
- Except that the small rounding error perpretrated by the drive
- manufacturers suffered the fate of a small error, and became a large
- error. This was bad.
-
- So, a committee was formed. And it arrived at a committee-like decision,
- which satisfied noone, confused everyone, and made the world an uglier
- place. As with all committees, this was meh.
-
- And the drive manufacturers happily continued selling drives that are
- increasingly smaller than you'd expect, if you don't count on your
- fingers. But that are increasingly too big for anyone to much notice.
- This caused me to need git-annex.
-
- Thus, I use units here that I loathe. Because if I didn't, people would
- be confused that their drives seem the wrong size, and other people would
- complain at me for not being standards compliant. And we call this
- progress?
-}
module Utility.DataUnits (
dataUnits,
storageUnits,
memoryUnits,
bandwidthUnits,
oldSchoolUnits,
Unit(..),
roughSize,
compareSizes,
readSize
) where
import Data.List
import Data.Char
import Utility.HumanNumber
type ByteSize = Integer
type Name = String
type Abbrev = String
data Unit = Unit ByteSize Abbrev Name
deriving (Ord, Show, Eq)
dataUnits :: [Unit]
dataUnits = storageUnits ++ memoryUnits
{- Storage units are (stupidly) powers of ten. -}
storageUnits :: [Unit]
storageUnits =
[ Unit (p 8) "YB" "yottabyte"
, Unit (p 7) "ZB" "zettabyte"
, Unit (p 6) "EB" "exabyte"
, Unit (p 5) "PB" "petabyte"
, Unit (p 4) "TB" "terabyte"
, Unit (p 3) "GB" "gigabyte"
, Unit (p 2) "MB" "megabyte"
, Unit (p 1) "kB" "kilobyte" -- weird capitalization thanks to committe
, Unit (p 0) "B" "byte"
]
where
p :: Integer -> Integer
p n = 1000^n
{- Memory units are (stupidly named) powers of 2. -}
memoryUnits :: [Unit]
memoryUnits =
[ Unit (p 8) "YiB" "yobibyte"
, Unit (p 7) "ZiB" "zebibyte"
, Unit (p 6) "EiB" "exbibyte"
, Unit (p 5) "PiB" "pebibyte"
, Unit (p 4) "TiB" "tebibyte"
, Unit (p 3) "GiB" "gibibyte"
, Unit (p 2) "MiB" "mebibyte"
, Unit (p 1) "KiB" "kibibyte"
, Unit (p 0) "B" "byte"
]
where
p :: Integer -> Integer
p n = 2^(n*10)
{- Bandwidth units are only measured in bits if you're some crazy telco. -}
bandwidthUnits :: [Unit]
bandwidthUnits = error "stop trying to rip people off"
{- Do you yearn for the days when men were men and megabytes were megabytes? -}
oldSchoolUnits :: [Unit]
oldSchoolUnits = zipWith (curry mingle) storageUnits memoryUnits
where
mingle (Unit _ a n, Unit s' _ _) = Unit s' a n
{- approximate display of a particular number of bytes -}
roughSize :: [Unit] -> Bool -> ByteSize -> String
roughSize units short i
| i < 0 = '-' : findUnit units' (negate i)
| otherwise = findUnit units' i
where
units' = sortBy (flip compare) units -- largest first
findUnit (u@(Unit s _ _):us) i'
| i' >= s = showUnit i' u
| otherwise = findUnit us i'
findUnit [] i' = showUnit i' (last units') -- bytes
showUnit x (Unit size abbrev name) = s ++ " " ++ unit
where
v = (fromInteger x :: Double) / fromInteger size
s = showImprecise 2 v
unit
| short = abbrev
| s == "1" = name
| otherwise = name ++ "s"
{- displays comparison of two sizes -}
compareSizes :: [Unit] -> Bool -> ByteSize -> ByteSize -> String
compareSizes units abbrev old new
| old > new = roughSize units abbrev (old - new) ++ " smaller"
| old < new = roughSize units abbrev (new - old) ++ " larger"
| otherwise = "same"
{- Parses strings like "10 kilobytes" or "0.5tb". -}
readSize :: [Unit] -> String -> Maybe ByteSize
readSize units input
| null parsednum || null parsedunit = Nothing
| otherwise = Just $ round $ number * fromIntegral multiplier
where
(number, rest) = head parsednum
multiplier = head parsedunit
unitname = takeWhile isAlpha $ dropWhile isSpace rest
parsednum = reads input :: [(Double, String)]
parsedunit = lookupUnit units unitname
lookupUnit _ [] = [1] -- no unit given, assume bytes
lookupUnit [] _ = []
lookupUnit (Unit s a n:us) v
| a ~~ v || n ~~ v = [s]
| plural n ~~ v || a ~~ byteabbrev v = [s]
| otherwise = lookupUnit us v
a ~~ b = map toLower a == map toLower b
plural n = n ++ "s"
byteabbrev a = a ++ "b"
| avengerpenguin/propellor | src/Utility/DataUnits.hs | bsd-2-clause | 4,700 | 34 | 13 | 1,008 | 1,292 | 663 | 629 | 90 | 3 |
{-# LANGUAGE LambdaCase, RankNTypes, ScopedTypeVariables #-}
module Stream.Folding.Prelude (
break
, concats
, cons
, drop
, lenumFrom
, lenumFromStepN
, lenumFromTo
, lenumFromToStep
, filter
, filterM
, foldl
, iterate
, iterateM
, joinFold
, map
, mapM
, maps
, repeat
, repeatM
, replicate
, replicateM
, scanr
, span
, splitAt
, splitAt_
, sum
, take
, takeWhile
, yield ) where
import Stream.Types
import Control.Monad hiding (filterM, mapM, replicateM)
import Data.Functor.Identity
import Control.Monad.Trans
import qualified System.IO as IO
import Prelude hiding (map, filter, drop, take, sum
, iterate, repeat, replicate, splitAt
, takeWhile, enumFrom, enumFromTo
, mapM, scanr, span, break, foldl)
-- ---------------
-- ---------------
-- Prelude
-- ---------------
-- ---------------
-- ---------------
-- yield
-- ---------------
yield :: Monad m => a -> Folding (Of a) m ()
yield r = Folding (\construct wrap done -> construct (r :> done ()))
{-# INLINE yield #-}
-- ---------------
-- sum
-- ---------------
sum :: (Monad m, Num a) => Folding (Of a) m () -> m a
sum = \(Folding phi) -> phi (\(n :> mm) -> mm >>= \m -> return (m+n))
join
(\_ -> return 0)
{-# INLINE sum #-}
-- ---------------
-- replicate
-- ---------------
replicate :: Monad m => Int -> a -> Folding (Of a) m ()
replicate n a = Folding (take_ (repeat_ a) n)
{-# INLINE replicate #-}
replicateM :: Monad m => Int -> m a -> Folding (Of a) m ()
replicateM n a = Folding (take_ (repeatM_ a) n)
{-# INLINE replicateM #-}
-- ---------------
-- iterate
-- ---------------
-- this can clearly be made non-recursive with eg numbers
iterate_ :: (a -> a) -> a -> Folding_ (Of a) m r
iterate_ f a = \construct wrap done ->
construct (a :> iterate_ f (f a) construct wrap done)
{-# INLINE iterate_ #-}
iterate :: (a -> a) -> a -> Folding (Of a) m r
iterate f a = Folding (iterate_ f a)
{-# INLINE iterate #-}
iterateM_ :: Monad m => (a -> m a) -> m a -> Folding_ (Of a) m r
iterateM_ f ma = \construct wrap done ->
let loop mx = wrap $ liftM (\x -> construct (x :> loop (f x))) mx
in loop ma
{-# INLINE iterateM_ #-}
iterateM :: Monad m => (a -> m a) -> m a -> Folding (Of a) m r
iterateM f a = Folding (iterateM_ f a)
{-# INLINE iterateM #-}
-- ---------------
-- repeat
-- ---------------
repeat_ :: a -> Folding_ (Of a) m r
repeat_ = \a construct wrap done ->
let loop = construct (a :> loop) in loop
{-# INLINE repeat_ #-}
repeat :: a -> Folding (Of a) m r
repeat a = Folding (repeat_ a)
{-# INLINE repeat #-}
repeatM_ :: Monad m => m a -> Folding_ (Of a) m r
repeatM_ ma = \construct wrap done ->
let loop = liftM (\a -> construct (a :> wrap loop)) ma in wrap loop
{-# INLINE repeatM_ #-}
repeatM :: Monad m => m a -> Folding (Of a) m r
repeatM ma = Folding (repeatM_ ma)
{-# INLINE repeatM #-}
-- ---------------
-- filter
-- ---------------
filter :: Monad m => (a -> Bool) -> Folding (Of a) m r -> Folding (Of a) m r
filter pred = \(Folding phi) -> Folding (filter_ phi pred)
{-# INLINE filter #-}
filter_ :: (Monad m) => Folding_ (Of a) m r -> (a -> Bool) -> Folding_ (Of a) m r
filter_ phi pred0 = \construct wrap done ->
phi (\aa@(a :> x) pred-> if pred a then construct (a :> x pred) else x pred)
(\mp pred -> wrap $ liftM ($pred) mp)
(\r pred -> done r)
pred0
{-# INLINE filter_ #-}
filterM_ :: (Monad m) => Folding_ (Of a) m r -> (a -> m Bool) -> Folding_ (Of a) m r
filterM_ phi pred0 = \construct wrap done ->
phi ( \aa@(a :> x) pred -> wrap $ do p <- pred a
return $ if p then construct (a :> x pred)
else x pred )
( \mp pred -> wrap $ liftM ($pred) mp )
( \r pred -> done r )
pred0
{-# INLINE filterM_ #-}
filterM :: Monad m => (a -> m Bool) -> Folding (Of a) m r -> Folding (Of a) m r
filterM pred = \(Folding phi) -> Folding (filterM_ phi pred)
-- ---------------
-- drop
-- ---------------
drop :: Monad m => Int -> Folding (Of a) m r -> Folding (Of a) m r
drop n = \(Folding phi) -> Folding (drop_ phi n)
{-# INLINE drop #-}
jdrop :: Monad m => Int -> Folding_ (Of a) m r -> Folding_ (Of a) m r
jdrop = \m phi construct wrap done ->
phi
(\(a :> fn) n -> if n <= m then fn (n+1) else construct (a :> (fn (n+1))))
(\m n -> wrap (m >>= \fn -> return (fn n)))
(\r _ -> done r)
1
{-# INLINE jdrop #-}
drop_ :: Monad m => Folding_ (Of a) m r -> Int -> Folding_ (Of a) m r
drop_ phi n0 = \construct wrap done ->
phi
(\(a :> fn) n -> if n >= 0 then fn (n-1) else construct (a :> (fn (n-1))))
(\m n -> wrap (m >>= \fn -> return (fn n)))
(\r _ -> done r)
n0
{-# INLINE drop_ #-}
-- ---------------
-- concats concat/join
-- ---------------
concats :: Monad m => Folding (Folding (Of a) m) m r -> Folding (Of a) m r
concats (Folding phi) = Folding $ \construct wrap done ->
phi (\(Folding phi') -> phi' construct wrap id)
wrap
done
{-# INLINE concats #-}
concats1 :: Monad m => Folding_ (Folding (Of a) m) m r -> Folding_ (Of a) m r
concats1 phi = \construct wrap done ->
phi (\(Folding phi') -> phi' construct wrap id)
wrap
done
{-# INLINE concats1 #-}
concats0 :: Monad m => Folding_ (Folding_ (Of a) m) m r -> Folding_ (Of a) m r
concats0 phi = \construct wrap done ->
phi (\phi' -> phi' construct wrap id)
wrap
done
{-# INLINE concats0 #-}
joinFold_ :: (Monad m, Functor f) => Folding_ f m (Folding_ f m r) -> Folding_ f m r
joinFold_ phi = \c w d -> phi c w (\folding -> folding c w d)
{-# INLINE joinFold_ #-}
joinFold (Folding phi) = Folding $ \c w d ->
phi c w (\folding -> getFolding folding c w d)
{-# INLINE joinFold #-}
-- ---------------
-- map
-- ---------------
map :: Monad m => (a -> b) -> Folding (Of a) m r -> Folding (Of b) m r
map f = \(Folding phi) -> Folding (map_ phi f)
{-# INLINE map #-}
map_ :: Monad m => Folding_ (Of a) m r -> (a -> b) -> Folding_ (Of b) m r
map_ phi f0 = \construct wrap done ->
phi (\(a :> x) f -> construct (f a :> x f))
(\mf f -> wrap (liftM ($f) mf))
(\r f -> done r)
f0
{-# INLINE map_ #-}
mapM :: Monad m => (a -> m b) -> Folding (Of a) m r -> Folding (Of b) m r
mapM f = \(Folding phi) -> Folding (mapM__ phi f)
where
mapM__ :: Monad m => Folding_ (Of a) m r -> (a -> m b) -> Folding_ (Of b) m r
mapM__ phi f0 = \construct wrap done ->
phi (\(a :> x) f -> wrap $ liftM (\z -> construct (z :> x f)) (f a) )
(\mff f -> wrap (liftM ($f) mff))
(\r _ -> done r)
f0
{-# INLINE mapM__ #-}
{-# INLINE mapM #-}
maps :: (Monad m, Functor g) => (forall x . f x -> g x) -> Folding f m r -> Folding g m r
maps morph (Folding phi) = Folding $ \construct wrap done ->
phi (construct . morph)
wrap
done
-- ---------------
-- take
-- ---------------
take_ :: (Monad m, Functor f) => Folding_ f m r -> Int -> Folding_ f m ()
take_ phi n = \construct wrap done -> phi
(\fx n -> if n <= 0 then done () else construct (fmap ($(n-1)) fx))
(\mx n -> if n <= 0 then done () else wrap (liftM ($n) mx))
(\r n -> done ())
n
{-# INLINE take_ #-}
take :: (Monad m, Functor f) => Int -> Folding f m r -> Folding f m ()
take n = \(Folding phi) -> Folding (take_ phi n)
{-# INLINE take #-}
takeWhile :: Monad m => (a -> Bool) -> Folding (Of a) m r -> Folding (Of a) m ()
takeWhile pred = \(Folding fold) -> Folding (takeWhile_ fold pred)
{-# INLINE takeWhile #-}
takeWhile_ :: Monad m => Folding_ (Of a) m r -> (a -> Bool) -> Folding_ (Of a) m ()
takeWhile_ phi pred0 = \construct wrap done ->
phi (\(a :> fn) p pred_ -> if not (pred_ a)
then done ()
else construct (a :> (fn True pred_)))
(\m p pred_ -> if not p then done () else wrap (liftM (\fn -> fn p pred_) m))
(\r p pred_ -> done ())
True
pred0
{-# INLINE takeWhile_ #-}
-- -------
lenumFrom n = \construct wrap done ->
let loop m = construct (m :> loop (succ m)) in loop n
lenumFromTo n m = \construct wrap done ->
let loop k = if k <= m then construct (k :> loop (succ k))
else done ()
in loop n
lenumFromToStep n m k = \construct wrap done ->
let loop p = if p <= k then construct (p :> loop (p + m))
else done ()
in loop n
lenumFromStepN start step n = \construct wrap done ->
let loop p 0 = done ()
loop p now = construct (p :> loop (p + step) (now-1))
in loop start n
foldl_ :: Monad m => Folding_ (Of a) m r -> (b -> a -> b) -> b -> m b
foldl_ phi = \ op b0 ->
phi (\(a :> fn) b -> fn $! flip op a $! b)
(\mf b -> mf >>= \f -> f b)
(\_ b -> return $! b)
b0
{-# INLINE foldl_ #-}
--
foldl :: Monad m => (b -> a -> b) -> b -> Folding (Of a) m r -> m b
foldl op b = \(Folding phi) -> foldl_ phi op b
{-# INLINE foldl #-}
jscanr :: Monad m => (a -> b -> b) -> b
-> Folding_ (Of a) m r -> Folding_ (Of b) m r
jscanr op b phi = phi
(\(a :> fx) b c w d -> c (b :> fx (op a b) c w d))
(\mfx b c w d -> w (liftM (\fx -> c (b :> fx b c w d)) mfx))
(\r b c w d -> c (b :> d r))
b
{-# INLINE jscanr #-}
scanr :: Monad m => (a -> b -> b) -> b
-> Folding (Of a) m r -> Folding (Of b) m r
scanr op b = \(Folding phi) -> Folding (lscanr_ phi op b)
lscanr_ :: Monad m => Folding_ (Of a) m r
-> (a -> b -> b) -> b -> Folding_ (Of b) m r
lscanr_ phi = phi
(\(a :> fx) op b c w d -> c (b :> fx op (op a b) c w d))
(\mfx op b c w d -> w (liftM (\fx -> c (b :> fx op b c w d)) mfx))
(\r op b c w d -> c (b :> d r))
{-# INLINE lscanr_ #-}
-----
chunksOf :: Monad m
=> Int
-> Folding (Of a) m r
-> Folding (Folding (Of a) m) m r
chunksOf = undefined
{-# INLINE chunksOf #-}
chunksOf_ :: Monad m
=> Folding_ (Of a) m r
-> Int
-> Folding_ (Folding_ (Of a) m) m r
chunksOf_ phi n = \construct wrap done -> undefined
-- --------
-- cons
-- --------
cons :: Monad m => a -> Folding (Of a) m r -> Folding (Of a) m r
cons a_ (Folding phi) = Folding $ \construct wrap done ->
phi (\(a :> a2p) a0 -> construct (a0 :> a2p a)
)
(\m a0 -> wrap $ liftM ($ a0) m
)
(\r a0 -> construct (a0 :> done r)
)
a_
-- --------
-- span
-- --------
span :: Monad m => (a -> Bool) -> Folding (Of a) m r
-> Folding (Of a) m (Folding (Of a) m r)
span pred0 (Folding phi) =
phi
(\ (a :> folding) ->
\pred ->
if pred a
then Folding $ \construct wrap done ->
construct (a :> getFolding (folding pred) construct wrap done)
else Folding $ \construct wrap done ->
done $ a `cons` joinFold (folding pred)
)
(\m ->
\pred ->
Folding $ \c w r ->
w (m >>= \folding -> return $ getFolding (folding pred) c w r)
)
(\r ->
\pred ->
Folding $ \construct wrap done ->
done (Folding $ \c w d -> d r)
)
pred0
{-# INLINE span #-}
-- --------
-- break
-- --------
break
:: Monad m =>
(a -> Bool)
-> Folding (Of a) m r -> Folding (Of a) m (Folding (Of a) m r)
break predicate = span (not . predicate)
-- --------
-- splitAt
-- --------
splitAt_ :: Monad m => Int -> Folding (Of a) m r
-> Folding (Of a) m (Folding (Of a) m r)
splitAt_ m (Folding phi) =
phi
(\ (a :> n2prod) n ->
if n > (0 :: Int)
then Folding $ \construct wrap done ->
construct (a :> getFolding (n2prod (n-1)) construct wrap done)
else Folding $ \construct wrap done ->
done $ a `cons` joinFold (n2prod (n))
)
(\m n -> Folding $ \c w r -> w (m >>= \n2fold -> return $ getFolding (n2fold n) c w r)
)
(\r n -> Folding $ \construct wrap done -> done (Folding $ \c w d -> d r)
)
m
{-# INLINE splitAt_ #-}
splitAt :: (Monad m, Functor f) => Int -> Folding f m r
-> Folding f m (Folding f m r)
splitAt m (Folding phi) =
phi
(\ fold n -> -- fold :: f (Int -> Folding f m (Folding f m r))
if n > (0 :: Int)
then Folding $ \construct wrap done ->
construct $ fmap (\f -> getFolding (f (n-1))
construct
wrap
done)
fold
else Folding $ \construct wrap done ->
done $ Folding $ \c w d ->
c $ fmap (\f -> getFolding (f n)
c
w
(\(Folding psi) -> psi c w d))
fold
)
(\m n -> Folding $ \c w r -> w (m >>= \n2fold -> return $ getFolding (n2fold n) c w r)
)
(\r n -> Folding $ \construct wrap done -> done (Folding $ \c w d -> d r)
)
m
{-# INLINE splitAt #-}
j :: (Monad m, Functor f) =>
f (Folding f m (Folding f m r)) -> Folding f m r
j ffolding =
Folding $ \cons w nil ->
cons $ fmap (\f -> getFolding f cons w (\(Folding psi) -> psi cons w nil))
ffolding
| haskell-streaming/streaming | benchmarks/old/Stream/Folding/Prelude.hs | bsd-3-clause | 13,598 | 0 | 21 | 4,483 | 6,173 | 3,198 | 2,975 | 323 | 3 |
{-# LANGUAGE PackageImports #-}
import "devel-example" DevelExample (develMain)
main :: IO ()
main = develMain
| s9gf4ult/yesod | yesod-bin/devel-example/app/devel.hs | mit | 112 | 0 | 6 | 16 | 26 | 15 | 11 | 4 | 1 |
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd">
<helpset version="2.0" xml:lang="sq-AL">
<title>Script Console</title>
<maps>
<homeID>top</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>Contents</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>Index</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Search</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>Favorites</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset> | kingthorin/zap-extensions | addOns/scripts/src/main/javahelp/org/zaproxy/zap/extension/scripts/resources/help_sq_AL/helpset_sq_AL.hs | apache-2.0 | 959 | 77 | 66 | 156 | 407 | 206 | 201 | -1 | -1 |
module X (x, D1(..), D2(..))
where
data D1 = D { f :: D2 } -- deriving Show
data D2 = A | B -- deriving Show
x :: D1
x = D { f = A }
| olsner/ghc | testsuite/tests/driver/recomp010/X1.hs | bsd-3-clause | 137 | 0 | 8 | 42 | 68 | 44 | 24 | 5 | 1 |
-- Test for trac #2956
module TH_sections where
two :: Int
two = $( [| (1 +) 1 |] )
three :: Int
three = $( [| (+ 2) 1 |] )
| urbanslug/ghc | testsuite/tests/th/TH_sections.hs | bsd-3-clause | 129 | 0 | 6 | 36 | 39 | 26 | 13 | -1 | -1 |
-- | A primitive expression is an expression where the non-leaves are
-- primitive operators. Our representation does not guarantee that
-- the expression is type-correct.
module Futhark.Analysis.PrimExp
( PrimExp (..)
, evalPrimExp
, primExpType
, coerceIntPrimExp
, module Futhark.Representation.Primitive
) where
import Control.Applicative
import Data.Foldable
import Data.Traversable
import Prelude
import Futhark.Representation.AST.Attributes.Names
import Futhark.Representation.Primitive
import Futhark.Util.IntegralExp
import Futhark.Util.Pretty
-- | A primitive expression parametrised over the representation of free variables.
data PrimExp v = LeafExp v PrimType
| ValueExp PrimValue
| BinOpExp BinOp (PrimExp v) (PrimExp v)
| CmpOpExp CmpOp (PrimExp v) (PrimExp v)
| UnOpExp UnOp (PrimExp v)
| ConvOpExp ConvOp (PrimExp v)
deriving (Ord, Show)
-- The Eq instance upcoerces all integer constants to their largest
-- type before comparing for equality. This is technically not a good
-- idea, but solves annoying problems related to the Num instance
-- always producing Int64s.
instance Eq v => Eq (PrimExp v) where
LeafExp x xt == LeafExp y yt = x == y && xt == yt
ValueExp (IntValue x) == ValueExp (IntValue y) =
intToInt64 x == intToInt64 y
BinOpExp xop x1 x2 == BinOpExp yop y1 y2 =
xop == yop && x1 == y1 && x2 == y2
CmpOpExp xop x1 x2 == CmpOpExp yop y1 y2 =
xop == yop && x1 == y1 && x2 == y2
UnOpExp xop x == UnOpExp yop y =
xop == yop && x == y
ConvOpExp xop x == ConvOpExp yop y =
xop == yop && x == y
_ == _ = False
instance Functor PrimExp where
fmap = fmapDefault
instance Foldable PrimExp where
foldMap = foldMapDefault
instance Traversable PrimExp where
traverse f (LeafExp v t) =
LeafExp <$> f v <*> pure t
traverse _ (ValueExp v) =
pure $ ValueExp v
traverse f (BinOpExp op x y) =
BinOpExp op <$> traverse f x <*> traverse f y
traverse f (CmpOpExp op x y) =
CmpOpExp op <$> traverse f x <*> traverse f y
traverse f (ConvOpExp op x) =
ConvOpExp op <$> traverse f x
traverse f (UnOpExp op x) =
UnOpExp op <$> traverse f x
instance FreeIn v => FreeIn (PrimExp v) where
freeIn = foldMap freeIn
-- The Num instance performs a little bit of magic: whenever an
-- expression and a constant is combined with a binary operator, the
-- type of the constant may be changed to be the type of the
-- expression, if they are not already the same. This permits us to
-- write e.g. @x * 4@, where @x@ is an arbitrary PrimExp, and have the
-- @4@ converted to the proper primitive type. We also support
-- converting integers to floating point values, but not the other way
-- around. All numeric instances assume unsigned integers for such
-- conversions.
--
-- We also perform simple constant folding, in particular to reduce
-- expressions to constants so that the above works. However, it is
-- still a bit of a hack.
instance Pretty v => Num (PrimExp v) where
x + y | zeroIshExp x = y
| zeroIshExp y = x
| IntType t <- primExpType x,
Just z <- constFold (doBinOp $ Add t) x y = z
| FloatType t <- primExpType x,
Just z <- constFold (doBinOp $ FAdd t) x y = z
| Just z <- msum [asIntOp Add x y, asFloatOp FAdd x y] = z
| otherwise = numBad "+" (x,y)
x - y | zeroIshExp y = x
| IntType t <- primExpType x,
Just z <- constFold (doBinOp $ Sub t) x y = z
| FloatType t <- primExpType x,
Just z <- constFold (doBinOp $ FSub t) x y = z
| Just z <- msum [asIntOp Sub x y, asFloatOp FSub x y] = z
| otherwise = numBad "-" (x,y)
x * y | zeroIshExp x = x
| zeroIshExp y = y
| oneIshExp x = y
| oneIshExp y = x
| IntType t <- primExpType x,
Just z <- constFold (doBinOp $ Mul t) x y = z
| FloatType t <- primExpType x,
Just z <- constFold (doBinOp $ FMul t) x y = z
| Just z <- msum [asIntOp Mul x y, asFloatOp FMul x y] = z
| otherwise = numBad "*" (x,y)
abs x | IntType t <- primExpType x = UnOpExp (Abs t) x
| FloatType t <- primExpType x = UnOpExp (FAbs t) x
| otherwise = numBad "abs" x
signum x | IntType t <- primExpType x = UnOpExp (SSignum t) x
| otherwise = numBad "signum" x
fromInteger = ValueExp . IntValue . Int64Value . fromInteger
instance Pretty v => IntegralExp (PrimExp v) where
x `div` y | oneIshExp y = x
| Just z <- msum [asIntOp SDiv x y, asFloatOp FDiv x y] = z
| otherwise = numBad "div" (x,y)
x `mod` y | Just z <- msum [asIntOp SMod x y] = z
| otherwise = numBad "mod" (x,y)
x `quot` y | oneIshExp y = x
| Just z <- msum [asIntOp SQuot x y] = z
| otherwise = numBad "quot" (x,y)
x `rem` y | Just z <- msum [asIntOp SRem x y] = z
| otherwise = numBad "rem" (x,y)
asIntOp :: (IntType -> BinOp) -> PrimExp v -> PrimExp v -> Maybe (PrimExp v)
asIntOp f x y
| IntType t <- primExpType x,
Just y' <- asIntExp t y = Just $ BinOpExp (f t) x y'
| IntType t <- primExpType y,
Just x' <- asIntExp t x = Just $ BinOpExp (f t) x' y
| otherwise = Nothing
asIntExp :: IntType -> PrimExp v -> Maybe (PrimExp v)
asIntExp t e
| primExpType e == IntType t = Just e
asIntExp t (ValueExp (IntValue v)) =
Just $ ValueExp $ IntValue $ doSExt v t
asIntExp _ _ =
Nothing
asFloatOp :: (FloatType -> BinOp) -> PrimExp v -> PrimExp v -> Maybe (PrimExp v)
asFloatOp f x y
| FloatType t <- primExpType x,
Just y' <- asFloatExp t y = Just $ BinOpExp (f t) x y'
| FloatType t <- primExpType y,
Just x' <- asFloatExp t x = Just $ BinOpExp (f t) x' y
| otherwise = Nothing
asFloatExp :: FloatType -> PrimExp v -> Maybe (PrimExp v)
asFloatExp t e
| primExpType e == FloatType t = Just e
asFloatExp t (ValueExp (FloatValue v)) =
Just $ ValueExp $ FloatValue $ doFPConv v t
asFloatExp t (ValueExp (IntValue v)) =
Just $ ValueExp $ FloatValue $ doSIToFP v t
asFloatExp _ _ =
Nothing
constFold :: (PrimValue -> PrimValue -> Maybe PrimValue)
-> PrimExp v -> PrimExp v
-> Maybe (PrimExp v)
constFold f x y = do x' <- valueExp x
y' <- valueExp y
ValueExp <$> f x' y'
numBad :: Pretty a => String -> a -> b
numBad s x =
error $ "Invalid argument to PrimExp method " ++ s ++ ": " ++ pretty x
-- | Evaluate a 'PrimExp' in the given monad. Invokes 'fail' on type
-- errors.
evalPrimExp :: (Pretty v, Monad m) => (v -> m PrimValue) -> PrimExp v -> m PrimValue
evalPrimExp f (LeafExp v _) = f v
evalPrimExp _ (ValueExp v) = return v
evalPrimExp f (BinOpExp op x y) = do
x' <- evalPrimExp f x
y' <- evalPrimExp f y
maybe (evalBad op (x,y)) return $ doBinOp op x' y'
evalPrimExp f (CmpOpExp op x y) = do
x' <- evalPrimExp f x
y' <- evalPrimExp f y
maybe (evalBad op (x,y)) (return . BoolValue) $ doCmpOp op x' y'
evalPrimExp f (UnOpExp op x) = do
x' <- evalPrimExp f x
maybe (evalBad op x) return $ doUnOp op x'
evalPrimExp f (ConvOpExp op x) = do
x' <- evalPrimExp f x
maybe (evalBad op x) return $ doConvOp op x'
evalBad :: (Pretty a, Pretty b, Monad m) => a -> b -> m c
evalBad op arg = fail $ "evalPrimExp: Type error when applying " ++
pretty op ++ " to " ++ pretty arg
-- | The type of values returned by a 'PrimExp'. This function
-- returning does not imply that the 'PrimExp' is type-correct.
primExpType :: PrimExp v -> PrimType
primExpType (LeafExp _ t) = t
primExpType (ValueExp v) = primValueType v
primExpType (BinOpExp op _ _) = binOpType op
primExpType CmpOpExp{} = Bool
primExpType (UnOpExp op _) = unOpType op
primExpType (ConvOpExp op _) = snd $ convOpType op
-- | Is the expression a constant zero of some sort?
zeroIshExp :: PrimExp v -> Bool
zeroIshExp (ValueExp v) = zeroIsh v
zeroIshExp _ = False
-- | Is the expression a constant one of some sort?
oneIshExp :: PrimExp v -> Bool
oneIshExp (ValueExp v) = oneIsh v
oneIshExp _ = False
-- | Is the expression a constant value?
valueExp :: PrimExp v -> Maybe PrimValue
valueExp (ValueExp v) = Just v
valueExp _ = Nothing
-- | If the given 'PrimExp' is a constant of the wrong integer type,
-- coerce it to the given integer type. This is a workaround for an
-- issue in the 'Num' instance.
coerceIntPrimExp :: IntType -> PrimExp v -> PrimExp v
coerceIntPrimExp t (ValueExp (IntValue v)) = ValueExp $ IntValue $ doSExt v t
coerceIntPrimExp _ e = e
-- Prettyprinting instances
instance Pretty v => Pretty (PrimExp v) where
ppr (LeafExp v _) = ppr v
ppr (ValueExp v) = ppr v
ppr (BinOpExp op x y) = ppr op <+> parens (ppr x) <+> parens (ppr y)
ppr (CmpOpExp op x y) = ppr op <+> parens (ppr x) <+> parens (ppr y)
ppr (ConvOpExp op x) = ppr op <+> parens (ppr x)
ppr (UnOpExp op x) = ppr op <+> parens (ppr x)
| ihc/futhark | src/Futhark/Analysis/PrimExp.hs | isc | 9,115 | 0 | 13 | 2,504 | 3,391 | 1,615 | 1,776 | 181 | 1 |
module Oczor.CodeGen.CodeGenJs where
import Oczor.CodeGen.Utl
codeGen :: Ast -> Doc
codeGen = x
where
x = cata $ \case
NoneF -> empty
UniqObjectF {} -> text "{}"
CodeF x -> text x
NotEqualF x y -> sep [x, text "!=", y]
EqualF x y -> sep [x, text "==", y]
LitF value -> lit value
IdentF name -> ident name
VarF name ast -> stmt [text "var", text name, equals, ast]
SetF astl astr -> stmt [astl, equals, astr]
ThrowF error -> stmt [text "throw", dquotes $ text error]
IfF p l r -> hcat [text "if", parens p] <> bracesNest l <> if onull r then empty else text "else" <> bracesNest r
ReturnF ast -> stmt [text "return", ast]
FieldF ast name -> field ast name
HasFieldF ast name -> sep [field ast name, text "!==", text "undefined"]
ObjectF list -> bracesNest $ punctuate comma (list <&> (\(name,ast) -> hsep [ident name, text ":", ast]))
FunctionF params body -> func params body
ScopeF list y -> parens (func [] (list ++ [text "return" <+> y]) ) <> parens empty
CallF name args -> name <> parens (hcat $ punctuate comma args)
OperatorF name param -> (hsep $ case param of {[x] -> [text name, x]; [x,y] -> [x,text name, y]} )
ArrayF list -> jsArray list
ConditionOperatorF astb astl astr -> parens $ hsep [astb, text "?", astl, text ":", astr]
BoolAndsF list -> parens $ hcat $ punctuate (text " && ") list
StmtListF list -> vcat list
ParensF x -> parens x
LabelF x y -> stmt [text "var", text x, equals, y]
func params body = hcat [text "function", parens $ hcat $ punctuate comma (params <&> text) ] <> bracesNest body
lit = createLit show "null" ("true", "false")
keywords = setFromList ["false", "true", "null", "abstract", "arguments", "boolean", "break", "byte case", "catch", "char", "class", "const continue", "debugger", "default", "delete", "do double", "else", "enum", "eval", "export extends", "false", "final", "finally", "float", "for", "function", "goto", "if", "implements import", "in", "instanceof", "int", "interface let", "long", "native", "new", "null package", "private", "protected", "public", "return short", "static", "super", "switch", "synchronized this", "throw", "throws", "transient", "true try", "typeof", "var", "void", "volatile while", "with", "yield"]
ident = createIdent keywords
stmt x = hsep x <> text ";"
field ast name = ast <> dot <> ident name
| ptol/oczor | src/Oczor/CodeGen/CodeGenJs.hs | mit | 2,395 | 0 | 19 | 498 | 1,003 | 523 | 480 | -1 | -1 |
import Test.HUnit
import Q11
import Q12
assertEqualIntList :: String -> [Int] -> [Int] -> Assertion
assertEqualIntList = assertEqual
test1 = TestCase (assertEqualIntList "decodeModified [] should be [] ." ([] ) (decodeModified [] ))
test2 = TestCase (assertEqualIntList "decodeModified [(Single 1)] should be [1] ." ([1] ) (decodeModified [(Single 1)] ))
test3 = TestCase (assertEqualIntList "decodeModified [(Single 1),(Single 2)] should be [1,2] ." ([1,2] ) (decodeModified [(Single 1),(Single 2)] ))
test4 = TestCase (assertEqualIntList "decodeModified [(Single 1),(Single 2),(Single 1)] should be [1,2,1]." ([1,2,1]) (decodeModified [(Single 1),(Single 2),(Single 1)]))
test5 = TestCase (assertEqualIntList "decodeModified [(Multiple 2 1),(Single 2)] should be [1,1,2]." ([1,1,2]) (decodeModified [(Multiple 2 1),(Single 2)] ))
test6 = TestCase (assertEqualIntList "decodeModified [(Single 1),(Multiple 2 2)] should be [1,2,2]." ([1,2,2]) (decodeModified [(Single 1),(Multiple 2 2)] ))
main = runTestTT $ TestList [test1,test2,test3,test4,test5,test6] | cshung/MiscLab | Haskell99/q12.test.hs | mit | 1,227 | 0 | 12 | 302 | 366 | 203 | 163 | 12 | 1 |
------------------------------------------------------------------------------
-- | This module is where all the routes and handlers are defined for your
-- site. The 'app' function is the initializer that combines everything
-- together and is exported by this module.
module Site (app) where
------------------------------------------------------------------------------
import Api.Core
import Data.ByteString (ByteString)
import Snap.Snaplet
------------------------------------------------------------------------------
import Application
------------------------------------------------------------------------------
-- | The application's routes.
routes :: [(ByteString, Handler App App ())]
routes = []
------------------------------------------------------------------------------
-- | The application initializer.
app :: SnapletInit App App
app = makeSnaplet "app" "An snaplet example application." Nothing $ do
api <- nestSnaplet "" api apiInit
addRoutes routes
return $ App api
| thorinii/oldtoby-server | main/src/Site.hs | mit | 1,005 | 0 | 9 | 116 | 128 | 72 | 56 | 12 | 1 |
{-# LANGUAGE TemplateHaskell, MultiParamTypeClasses, PatternGuards #-}
-- Copyright (c) 2004-6 Donald Bruce Stewart - http://www.cse.unsw.edu.au/~dons
-- GPL version 2 or later (see http://www.gnu.org/copyleft/gpl.html)
-- | A Haskell evaluator for the pure part, using plugs
module Plugin.Eval where
import File (findFile)
import Plugin
import Lambdabot.Parser
import Language.Haskell.Exts.Parser
import qualified Language.Haskell.Exts.Syntax as Hs
import qualified Text.Regex as R
import System.Directory
import System.Exit
import Codec.Binary.UTF8.String (decodeString)
import qualified Data.ByteString.Char8 as P
import Control.OldException (try)
$(plugin "Plugs")
instance Module PlugsModule () where
moduleCmds _ = ["run","let","undefine"]
moduleHelp _ "let" = "let <x> = <e>. Add a binding"
moduleHelp _ "undefine" = "undefine. Reset evaluator local bindings"
moduleHelp _ _ = "run <expr>. You have Haskell, 3 seconds and no IO. Go nuts!"
process _ _ to "run" s = ios80 to (plugs s)
process _ _ to "let" s = ios80 to (define s)
process _ _ _ "undefine" _ = do l <- io $ findFile "L.hs"
p <- io $ findFile "Pristine.hs"
io $ copyFile p l
-- x <- io $ comp Nothing
-- return [x]
return []
contextual _ _ to txt
| isEval txt = ios80 to . plugs . dropPrefix $ txt
| otherwise = return []
binary :: String
binary = "mueval"
isEval :: String -> Bool
isEval = ((evalPrefixes config) `arePrefixesWithSpaceOf`)
dropPrefix :: String -> String
dropPrefix = dropWhile (' ' ==) . drop 2
plugs :: String -> IO String
plugs src = do
load <- findFile "L.hs"
-- let args = ["-E", "-XBangPatterns", "-XNoMonomorphismRestriction", "-XViewPatterns", "--no-imports", "-l", load, "--expression=" ++ src, "+RTS", "-N2", "-RTS"]
let args = ["-E", "-XBangPatterns", "-XNoMonomorphismRestriction", "-XViewPatterns", "--no-imports", "-l", load, "--expression=" ++ src, "+RTS", "-N2", "-RTS"]
print args
(out,err,_) <- popen binary args Nothing
case (out,err) of
([],[]) -> return "Terminated\n"
_ -> do
let o = munge out
e = munge err
return $ case () of {_
| null o && null e -> "Terminated\n"
| null o -> " " ++ e
| otherwise -> " " ++ o
}
------------------------------------------------------------------------
-- define a new binding
define :: String -> IO String
define src = case parseModule (decodeString src ++ "\n") of -- extra \n so comments are parsed correctly
(ParseOk (Hs.Module _ _ _ _ (Just [Hs.EVar (Hs.UnQual (Hs.Ident "main"))]) [] ds))
| all okay ds -> comp (Just src)
(ParseFailed _ e) -> return $ " " ++ e
_ -> return "Invalid declaration"
where
okay (Hs.TypeSig {}) = True
okay (Hs.FunBind {}) = True
okay (Hs.PatBind {}) = True
okay (Hs.InfixDecl {}) = True
okay _ = False
-- It parses. then add it to a temporary L.hs and typecheck
comp :: Maybe String -> IO String
comp src = do
l <- findFile "L.hs"
-- Note we copy to .L.hs, not L.hs. This hides the temporary files as dot-files
copyFile l ".L.hs"
case src of
Nothing -> return () -- just reset from Pristine
Just s -> P.appendFile ".L.hs" (P.pack (s ++ "\n"))
-- and compile .L.hs
-- careful with timeouts here. need a wrapper.
(o',e',c) <- popen "ghc" ["-O","-v0","-c"
,"-Werror"
-- ,"-odir", "State/"
-- ,"-hidir","State/"
,".L.hs"] Nothing
-- cleanup, in case of error the files are not generated
try $ removeFile ".L.hi"
try $ removeFile ".L.o"
case (munge o', munge e') of
([],[]) | c /= ExitSuccess -> return "Error."
| otherwise -> do
renameFile ".L.hs" l
return (maybe "Undefined." (const "Defined.") src)
(ee,[]) -> return ee
(_ ,ee) -> return ee
-- test cases
-- lambdabot> undefine
-- Undefined.
--
-- lambdabot> let x = 1
-- Defined.
-- lambdabot> let y = L.x
-- Defined.
-- lambdabot> > L.x + L.y
-- 2
-- lambdabot> let type Z = Int
-- Defined.
-- lambdabot> let newtype P = P Int
-- Defined.
-- lambdabot> > L.P 1 :: L.P
-- add an instance declaration for (Show L.P)
-- lambdabot> let instance Show L.P where show _ = "P"
-- Defined.
-- lambdabot> > L.P 1 :: L.P
-- P
--
munge :: String -> String
munge = expandTab . dropWhile (=='\n') . dropNL . clean_
--
-- Clean up runplugs' output
--
clean_ :: String -> String
clean_ = id
{-
clean_ s| no_io `matches'` s = "No IO allowed\n"
| type_sig `matches'` s = "Add a type signature\n"
| enomem `matches'` s = "Tried to use too much memory\n"
| Just (_,m,_,_) <- ambiguous `R.matchRegexAll` s = m
| Just (_,_,b,_) <- inaninst `R.matchRegexAll` s = clean_ b
| Just (_,_,b,_) <- irc `R.matchRegexAll` s = clean_ b
| Just (_,m,_,_) <- nomatch `R.matchRegexAll` s = m
| Just (_,m,_,_) <- notinscope `R.matchRegexAll` s = m
| Just (_,m,_,_) <- hsplugins `R.matchRegexAll` s = m
| Just (a,_,_,_) <- columnnum `R.matchRegexAll` s = a
| Just (a,_,_,_) <- extraargs `R.matchRegexAll` s = a
| Just (_,_,b,_) <- filename' `R.matchRegexAll` s = clean_ b
| Just (a,_,b,_) <- filename `R.matchRegexAll` s = a ++ clean_ b
| Just (a,_,b,_) <- filepath `R.matchRegexAll` s = a ++ clean_ b
| Just (a,_,b,_) <- runplugs `R.matchRegexAll` s = a ++ clean_ b
| otherwise = s
where
-- s/<[^>]*>:[^:]: //
type_sig = regex' "add a type signature that fixes these type"
no_io = regex' "No instance for \\(Show \\(IO"
irc = regex' "\n*<irc>:[^:]*:[^:]*:\n*"
filename = regex' "\n*<[^>]*>:[^:]*:\\?[^:]*:\\?\n* *"
filename' = regex' "/tmp/.*\\.hs[^\n]*\n"
filepath = regex' "\n*/[^\\.]*.hs:[^:]*:\n* *"
ambiguous = regex' "Ambiguous type variable `a\' in the constraints"
runplugs = regex' "runplugs: "
notinscope = regex' "Variable not in scope:[^\n]*"
hsplugins = regex' "Compiled, but didn't create object"
extraargs = regex' "[ \t\n]*In the [^ ]* argument"
columnnum = regex' " at <[^\\.]*\\.[^\\.]*>:[^ ]*"
nomatch = regex' "Couldn't match[^\n]*\n"
inaninst = regex' "^[ \t]*In a.*$"
enomem = regex' "^Heap exhausted"
-}
------------------------------------------------------------------------
--
-- Plugs tests:
-- * too long, should be terminated.
-- @plugs last [ 1 .. 100000000 ]
-- @plugs last [ 1 .. ]
-- @plugs product [1..]
-- @plugs let loop () = loop () in loop () :: ()
--
-- * stack oflow
-- @plugs scanr (*) 1 [1..]
--
-- * type errors, or module scope errors
-- @plugs unsafePerformIO (return 42)
-- @plugs GHC.Exts.I# 1#
-- @plugs $( Language.Haskell.THSyntax.Q (putStr "heya") >> [| 3 |] )
-- @plugs Data.Array.listArray (minBound::Int,maxBound) (repeat 0)
--
-- * syntax errors
-- @plugs map foo bar
-- @plugs $( [| 1 |] )
--
-- * success
-- @plugs head [ 1 .. ]
-- @plugs [1..]
-- @plugs last $ sort [1..100000 ]
-- @plugs let fibs = 1:1:zipWith (+) fibs (tail fibs) in take 20 fibs
-- @plugs sort [1..10000]
-- @plugs ((error "throw me") :: ())
-- @plugs Random.randomRs (0,747737437443734::Integer) (Random.mkStdGen 1122)
--
-- More at http://www.scannedinavian.org/~shae/joyXlogs.txt
--
| zeekay/lambdabot | Plugin/Eval.hs | mit | 8,059 | 0 | 20 | 2,469 | 1,240 | 668 | 572 | 83 | 7 |
module Assembler.Types where
import Data.Word
-- Constant is either an int or a label which resolves to an int
type Label = String
type Constant = Either Int Label
type RegId = Word8
data Instr = Halt
| Nop
| Rrmovl RegId RegId
| Irmovl RegId Constant
| Rmmovl RegId RegId Int
| Mrmovl RegId RegId Int
| Addl RegId RegId
| Subl RegId RegId
| Andl RegId RegId
| Xorl RegId RegId
| Jmp Label
| Jle Label
| Jl Label
| Je Label
| Jne Label
| Jge Label
| Jg Label
| Cmovle RegId RegId
| Cmovl RegId RegId
| Cmove RegId RegId
| Cmovne RegId RegId
| Cmovge RegId RegId
| Cmovg RegId RegId
| Call Label
| Ret
| Pushl RegId
| Popl RegId
deriving Show
data Entity = Instr (Instr, Int)
| Directive (String, Int)
| Label Label
deriving Show
| aufheben/Y86 | Assembler/src/Assembler/Types.hs | mit | 1,097 | 0 | 7 | 514 | 237 | 141 | 96 | 37 | 0 |
module Vector2D where
type Vector2D = (Double, Double)
zero :: Vector2D
zero = (0, 0)
unit :: Vector2D
unit = (1, 1)
fromScalar :: Double -> Vector2D
fromScalar scalar = (scalar, scalar)
fromAngle :: Double -> Vector2D
fromAngle angle = (cos angle, sin angle)
magnitude :: Vector2D -> Double
magnitude vector = sqrt(magnitudeSquared vector)
magnitudeSquared :: Vector2D -> Double
magnitudeSquared (x, y) = (x*x + y*y)
addVector :: Vector2D -> Vector2D -> Vector2D
addVector (x1, y1) (x2, y2) = (x1 + x2, y1 + y2)
subtractVector :: Vector2D -> Vector2D -> Vector2D
subtractVector (x1, y1) (x2, y2) = (x1 - x2, y1 - y2)
multiplyVector :: Vector2D -> Vector2D -> Vector2D
multiplyVector (x1, y1) (x2, y2) = (x1 * x2, y1 * y2)
multiplyScalar :: Vector2D -> Double -> Vector2D
multiplyScalar vector scalar = multiplyVector vector $ fromScalar scalar
divideVector :: Vector2D -> Vector2D -> Vector2D
divideVector (x1, y1) (x2, y2) = (x1 / x2, y1 / y2)
divideScalar :: Vector2D -> Double -> Vector2D
divideScalar vector scalar = divideVector vector $ fromScalar scalar
distance :: Vector2D -> Vector2D -> Double
distance (x1, y1) (x2, y2) = sqrt $ dx * dx + dy * dx
where dx = x1 - x2
dy = y1 - y2
dot :: Vector2D -> Vector2D -> Double
dot (x1, y1) (x2, y2) = x1*x2 + y1+y2
reflect :: Vector2D -> Vector2D -> Vector2D
reflect vector1@(vectorX, vectorY) vector2@(normalX, normalY) = (vectorX - (2 * dotProduct * normalX), vectorY - (2 * dotProduct * normalY))
where dotProduct = dot vector1 vector2
normalize :: Vector2D -> Vector2D
normalize vector
| vectorMagnitude == 0 || vectorMagnitude == 1 = vector
| otherwise = vector `divideVector` (fromScalar vectorMagnitude)
where vectorMagnitude = magnitude vector
limit :: Vector2D -> Double -> Vector2D
limit vector maximum
| magnitudeSquared vector <= maximum * maximum = vector
| otherwise = (normalize vector) `multiplyScalar` maximum
getAngle :: Vector2D -> Double
getAngle (x, y) = (-1) * (atan2 (-y) x)
rotate :: Vector2D -> Double -> Vector2D
rotate (x, y) angle = (x * (cos angle) - y * (sin angle),
x * (sin angle) - y * (cos angle))
lerp :: Double -> Double -> Double -> Double
lerp start end amount = start + (end - start) * amount
lerpVector :: Vector2D -> Vector2D -> Double -> Vector2D
lerpVector (startX, startY) (endX, endY) amount = (lerp startX endX amount,
lerp startY endY amount)
remap :: Double -> Double -> Double -> Double -> Double -> Double
remap value oldMin oldMax newMin newMax = newMin + (newMax - newMin) * ((value - oldMin) / (oldMax - oldMin))
remapVectorToScalar :: Vector2D -> Double -> Double -> Double -> Double -> Vector2D
remapVectorToScalar (x, y) oldMin oldMax newMin newMax = (remap x oldMin oldMax newMin newMax,
remap y oldMin oldMax newMin newMax)
remapVectorToVectors :: Vector2D -> Vector2D -> Vector2D -> Vector2D -> Vector2D -> Vector2D
remapVectorToVectors (x, y) (oldMinX, oldMinY) (oldMaxX, oldMaxY) (newMinX, newMinY) (newMaxX, newMaxY) = (remap x oldMinX oldMaxX newMinX newMaxX,
remap y oldMinY oldMaxY newMinY newMaxY)
angleBetween :: Vector2D -> Vector2D -> Double
angleBetween vector1 vector2 = acos (enforceAngleConstraints tempValue)
where tempValue = (vector1 `dot` vector2) / (magnitude vector1 * magnitude vector2)
enforceAngleConstraints value
| value <= -1 = pi
| value >= 1 = 0
| otherwise = value
degreesToRadians :: Double -> Double
degreesToRadians degrees = degrees * (pi / 180)
radiansToDegrees :: Double -> Double
radiansToDegrees radians = radians * (180 / pi)
clamp :: Double -> Double -> Double -> Double
clamp input min max
| input < min = min
| input > max = max
| otherwise = input
clampToScalar :: Vector2D -> Double -> Double -> Vector2D
clampToScalar (x, y) min max = (clamp x min max, clamp y min max)
clampToVectors :: Vector2D -> Vector2D -> Vector2D -> Vector2D
clampToVectors (x, y) (minX, minY) (maxX, maxY) = (clamp x minX maxX,
clamp y minY maxY)
negate :: Vector2D -> Vector2D
negate vector = vector `multiplyScalar` (-1)
| jlturner/vector2d-haskell | Vector2D.hs | mit | 4,542 | 0 | 11 | 1,250 | 1,618 | 869 | 749 | 85 | 1 |
{-# LANGUAGE CPP, MultiParamTypeClasses, FlexibleInstances, FlexibleContexts #-}
-----------------------------------------------------------------------------
-- |
-- Module : Crypto.Nettle.Ciphers
-- Copyright : (c) 2013 Stefan Bühler
-- License : MIT-style (see the file COPYING)
--
-- Maintainer : stbuehler@web.de
-- Stability : experimental
-- Portability : portable
--
-- This module exports ciphers supported by nettle:
-- <http://www.lysator.liu.se/~nisse/nettle/>
--
-----------------------------------------------------------------------------
module Crypto.Nettle.Ciphers (
-- * Block ciphers
-- | Only block ciphers with a 128-bit 'blockSize' (16 bytes) support the XTS cipher mode.
--
-- For 'aeadInit' only 'AEAD_GCM' and 'AEAD_CCM' (with 'ccmInitTLS') is supported, and only if the the 'blockSize' is 16 bytes.
-- In all other cases 'aeadInit' just returns 'Nothing'.
-- ** AES
AES
, AES128
, AES192
, AES256
-- ** ARCTWO
, ARCTWO
, arctwoInitEKB
, arctwoInitGutmann
-- ** BLOWFISH
, BLOWFISH
-- ** Camellia
, Camellia
, Camellia128
, Camellia192
, Camellia256
-- ** CAST-128
, CAST128
-- ** DES
, DES
-- ** DES3 (EDE)
, DES_EDE3
-- ** TWOFISH
, TWOFISH
-- ** SERPENT
, SERPENT
-- * Stream ciphers
-- ** Nonce ciphers
, StreamNonceCipher(..)
, streamSetNonceWord64
-- ** ARCFOUR
, ARCFOUR
-- ** ChaCha
, CHACHA
-- ** Salsa20
, SALSA20
, ESTREAM_SALSA20
) where
import Crypto.Cipher.Types
import Crypto.Nettle.CCM
import Data.SecureMem
import qualified Data.ByteString as B
import Data.Word (Word64)
import Data.Bits
import Data.Tagged
import Crypto.Nettle.Ciphers.Internal
import Crypto.Nettle.Ciphers.ForeignImports
import Nettle.Utils
-- internal functions are not camelCase on purpose
{-# ANN module "HLint: ignore Use camelCase" #-}
#define INSTANCE_CIPHER(Typ) \
instance Cipher Typ where \
{ cipherInit = nettle_cipherInit \
; cipherName = witness nc_cipherName \
; cipherKeySize = witness nc_cipherKeySize \
}
#define INSTANCE_BLOCKCIPHER(Typ) \
INSTANCE_CIPHER(Typ); \
instance BlockCipher Typ where \
{ blockSize = witness nbc_blockSize \
; ecbEncrypt = nettle_ecbEncrypt \
; ecbDecrypt = nettle_ecbDecrypt \
; cbcEncrypt = nettle_cbcEncrypt \
; cbcDecrypt = nettle_cbcDecrypt \
; cfbEncrypt = nettle_cfbEncrypt \
; cfbDecrypt = nettle_cfbDecrypt \
; ctrCombine = nettle_ctrCombine \
; aeadInit AEAD_GCM = nettle_gcm_aeadInit \
; aeadInit AEAD_CCM = ccmInitTLS \
; aeadInit _ = \_ _ -> Nothing \
} ; \
instance AEADModeImpl Typ NettleGCM where \
{ aeadStateAppendHeader = nettle_gcm_aeadStateAppendHeader \
; aeadStateEncrypt = nettle_gcm_aeadStateEncrypt \
; aeadStateDecrypt = nettle_gcm_aeadStateDecrypt \
; aeadStateFinalize = nettle_gcm_aeadStateFinalize \
}
#define INSTANCE_STREAMCIPHER(Typ) \
INSTANCE_CIPHER(Typ); \
instance StreamCipher Typ where \
{ streamCombine = nettle_streamCombine \
}
#define INSTANCE_STREAMNONCECIPHER(Typ) \
INSTANCE_STREAMCIPHER(Typ); \
instance StreamNonceCipher Typ where \
{ streamSetNonce = nettle_streamSetNonce \
; streamNonceSize = witness nsc_nonceSize \
}
#define INSTANCE_BLOCKEDSTREAMCIPHER(Typ) \
INSTANCE_CIPHER(Typ); \
instance StreamCipher Typ where \
{ streamCombine = nettle_blockedStreamCombine \
}
#define INSTANCE_BLOCKEDSTREAMNONCECIPHER(Typ) \
INSTANCE_BLOCKEDSTREAMCIPHER(Typ); \
instance StreamNonceCipher Typ where \
{ streamSetNonce = nettle_blockedStreamSetNonce \
; streamNonceSize = witness nbsc_nonceSize \
}
{-|
'AES' is the generic cipher context for the AES cipher, supporting key sizes
of 128, 196 and 256 bits (16, 24 and 32 bytes). The 'blockSize' is always 128 bits (16 bytes).
'aeadInit' only supports the 'AEAD_GCM' mode for now.
-}
newtype AES = AES SecureMem
instance NettleCipher AES where
nc_cipherInit = Tagged c_hs_aes_init
nc_cipherName = Tagged "AES"
nc_cipherKeySize = Tagged $ KeySizeEnum [16,24,32]
nc_ctx_size = Tagged c_hs_aes_ctx_size
nc_ctx (AES c) = c
nc_Ctx = AES
instance NettleBlockCipher AES where
nbc_blockSize = Tagged 16
nbc_ecb_encrypt = Tagged c_hs_aes_encrypt
nbc_ecb_decrypt = Tagged c_hs_aes_decrypt
nbc_fun_encrypt = Tagged p_hs_aes_encrypt
nbc_fun_decrypt = Tagged p_hs_aes_decrypt
INSTANCE_BLOCKCIPHER(AES)
{-|
'AES128' provides the same interface as 'AES', but is restricted to 128-bit keys.
-}
newtype AES128 = AES128 SecureMem
instance NettleCipher AES128 where
nc_cipherInit = Tagged (\ctx _ key -> c_hs_aes128_init ctx key)
nc_cipherName = Tagged "AES-128"
nc_cipherKeySize = Tagged $ KeySizeFixed 16
nc_ctx_size = Tagged c_hs_aes128_ctx_size
nc_ctx (AES128 c) = c
nc_Ctx = AES128
instance NettleBlockCipher AES128 where
nbc_blockSize = Tagged 16
nbc_encrypt_ctx_offset = Tagged c_hs_aes128_ctx_encrypt
nbc_decrypt_ctx_offset = Tagged c_hs_aes128_ctx_decrypt
nbc_ecb_encrypt = Tagged c_aes128_encrypt
nbc_ecb_decrypt = Tagged c_aes128_decrypt
nbc_fun_encrypt = Tagged p_aes128_encrypt
nbc_fun_decrypt = Tagged p_aes128_decrypt
INSTANCE_BLOCKCIPHER(AES128)
{-|
'AES192' provides the same interface as 'AES', but is restricted to 192-bit keys.
-}
newtype AES192 = AES192 SecureMem
instance NettleCipher AES192 where
nc_cipherInit = Tagged (\ctx _ key -> c_hs_aes192_init ctx key)
nc_cipherName = Tagged "AES-192"
nc_cipherKeySize = Tagged $ KeySizeFixed 24
nc_ctx_size = Tagged c_hs_aes192_ctx_size
nc_ctx (AES192 c) = c
nc_Ctx = AES192
instance NettleBlockCipher AES192 where
nbc_blockSize = Tagged 16
nbc_encrypt_ctx_offset = Tagged c_hs_aes192_ctx_encrypt
nbc_decrypt_ctx_offset = Tagged c_hs_aes192_ctx_decrypt
nbc_ecb_encrypt = Tagged c_aes192_encrypt
nbc_ecb_decrypt = Tagged c_aes192_decrypt
nbc_fun_encrypt = Tagged p_aes192_encrypt
nbc_fun_decrypt = Tagged p_aes192_decrypt
INSTANCE_BLOCKCIPHER(AES192)
{-|
'AES256' provides the same interface as 'AES', but is restricted to 256-bit keys.
-}
newtype AES256 = AES256 SecureMem
instance NettleCipher AES256 where
nc_cipherInit = Tagged (\ctx _ key -> c_hs_aes256_init ctx key)
nc_cipherName = Tagged "AES-256"
nc_cipherKeySize = Tagged $ KeySizeFixed 32
nc_ctx_size = Tagged c_hs_aes256_ctx_size
nc_ctx (AES256 c) = c
nc_Ctx = AES256
instance NettleBlockCipher AES256 where
nbc_blockSize = Tagged 16
nbc_encrypt_ctx_offset = Tagged c_hs_aes256_ctx_encrypt
nbc_decrypt_ctx_offset = Tagged c_hs_aes256_ctx_decrypt
nbc_ecb_encrypt = Tagged c_aes256_encrypt
nbc_ecb_decrypt = Tagged c_aes256_decrypt
nbc_fun_encrypt = Tagged p_aes256_encrypt
nbc_fun_decrypt = Tagged p_aes256_decrypt
INSTANCE_BLOCKCIPHER(AES256)
{-|
'ARCTWO' (also known as the trade marked name RC2) is a block cipher specified in RFC 2268.
The default 'cipherInit' uses @ekb = bit-length of the key@; 'arctwoInitEKB' allows to specify ekb manually.
'arctwoInitGutmann' uses @ekb = 1024@ (the maximum).
'ARCTWO' uses keysizes from 1 to 128 bytes, and uses a 'blockSize' of 64 bits (8 bytes).
-}
newtype ARCTWO = ARCTWO SecureMem
instance NettleCipher ARCTWO where
nc_cipherInit = Tagged c_arctwo_set_key
nc_cipherName = Tagged "ARCTWO"
nc_cipherKeySize = Tagged $ KeySizeRange 1 128
nc_ctx_size = Tagged c_arctwo_ctx_size
nc_ctx (ARCTWO c) = c
nc_Ctx = ARCTWO
instance NettleBlockCipher ARCTWO where
nbc_blockSize = Tagged 8
nbc_ecb_encrypt = Tagged c_arctwo_encrypt
nbc_ecb_decrypt = Tagged c_arctwo_decrypt
nbc_fun_encrypt = Tagged p_arctwo_encrypt
nbc_fun_decrypt = Tagged p_arctwo_decrypt
INSTANCE_BLOCKCIPHER(ARCTWO)
{-|
Initialize cipher with an explicit @ekb@ value (valid values from 1 to 1024, 0 meaning the same as 1024).
-}
arctwoInitEKB :: Key ARCTWO -> Word -> ARCTWO
arctwoInitEKB k ekb = nettle_cipherInit' initfun k where
initfun ctxptr ksize ptr = c_arctwo_set_key_ekb ctxptr ksize ptr ekb
{-|
Initialize cipher with @ekb = 1024@.
-}
arctwoInitGutmann :: Key ARCTWO -> ARCTWO
arctwoInitGutmann = nettle_cipherInit' c_arctwo_set_key_gutmann
{-|
'BLOWFISH' is a block cipher designed by Bruce Schneier.
It uses a 'blockSize' of 64 bits (8 bytes), and a variable key size from 64 to 448 bits (8 to 56 bytes).
-}
newtype BLOWFISH = BLOWFISH SecureMem
instance NettleCipher BLOWFISH where
nc_cipherInit = Tagged c_blowfish_set_key
nc_cipherName = Tagged "BLOWFISH"
nc_cipherKeySize = Tagged $ KeySizeRange 1 128
nc_ctx_size = Tagged c_blowfish_ctx_size
nc_ctx (BLOWFISH c) = c
nc_Ctx = BLOWFISH
instance NettleBlockCipher BLOWFISH where
nbc_blockSize = Tagged 8
nbc_ecb_encrypt = Tagged c_blowfish_encrypt
nbc_ecb_decrypt = Tagged c_blowfish_decrypt
nbc_fun_encrypt = Tagged p_blowfish_encrypt
nbc_fun_decrypt = Tagged p_blowfish_decrypt
INSTANCE_BLOCKCIPHER(BLOWFISH)
{-|
Camellia is a block cipher developed by Mitsubishi and Nippon Telegraph and Telephone Corporation,
described in RFC3713, and recommended by some Japanese and European authorities as an alternative to AES.
The algorithm is patented (details see <http://www.lysator.liu.se/~nisse/nettle/nettle.html>).
Camellia uses a the same 'blockSize' and key sizes as 'AES'.
'aeadInit' only supports the 'AEAD_GCM' mode for now.
-}
newtype Camellia = Camellia SecureMem
instance NettleCipher Camellia where
nc_cipherInit = Tagged c_hs_camellia_init
nc_cipherName = Tagged "Camellia"
nc_cipherKeySize = Tagged $ KeySizeEnum [16,24,32]
nc_ctx_size = Tagged c_hs_camellia_ctx_size
nc_ctx (Camellia c) = c
nc_Ctx = Camellia
instance NettleBlockCipher Camellia where
nbc_blockSize = Tagged 16
nbc_ecb_encrypt = Tagged c_hs_camellia_encrypt
nbc_ecb_decrypt = Tagged c_hs_camellia_decrypt
nbc_fun_encrypt = Tagged p_hs_camellia_encrypt
nbc_fun_decrypt = Tagged p_hs_camellia_decrypt
INSTANCE_BLOCKCIPHER(Camellia)
{-|
'Camellia128' provides the same interface as 'Camellia', but is restricted to 128-bit keys.
-}
newtype Camellia128 = Camellia128 SecureMem
instance NettleCipher Camellia128 where
nc_cipherInit = Tagged (\ctx _ key -> c_hs_camellia128_init ctx key)
nc_cipherName = Tagged "Camellia-128"
nc_cipherKeySize = Tagged $ KeySizeFixed 16
nc_ctx_size = Tagged c_hs_camellia128_ctx_size
nc_ctx (Camellia128 c) = c
nc_Ctx = Camellia128
instance NettleBlockCipher Camellia128 where
nbc_blockSize = Tagged 16
nbc_encrypt_ctx_offset = Tagged c_hs_camellia128_ctx_encrypt
nbc_decrypt_ctx_offset = Tagged c_hs_camellia128_ctx_decrypt
nbc_ecb_encrypt = Tagged c_camellia128_crypt
nbc_ecb_decrypt = Tagged c_camellia128_crypt
nbc_fun_encrypt = Tagged p_camellia128_crypt
nbc_fun_decrypt = Tagged p_camellia128_crypt
INSTANCE_BLOCKCIPHER(Camellia128)
{-|
'Camellia192' provides the same interface as 'Camellia', but is restricted to 192-bit keys.
-}
newtype Camellia192 = Camellia192 SecureMem
instance NettleCipher Camellia192 where
nc_cipherInit = Tagged (\ctx _ key -> c_hs_camellia192_init ctx key)
nc_cipherName = Tagged "Camellia-192"
nc_cipherKeySize = Tagged $ KeySizeFixed 24
nc_ctx_size = Tagged c_hs_camellia192_ctx_size
nc_ctx (Camellia192 c) = c
nc_Ctx = Camellia192
instance NettleBlockCipher Camellia192 where
nbc_blockSize = Tagged 16
nbc_encrypt_ctx_offset = Tagged c_hs_camellia192_ctx_encrypt
nbc_decrypt_ctx_offset = Tagged c_hs_camellia192_ctx_decrypt
nbc_ecb_encrypt = Tagged c_camellia192_crypt
nbc_ecb_decrypt = Tagged c_camellia192_crypt
nbc_fun_encrypt = Tagged p_camellia192_crypt
nbc_fun_decrypt = Tagged p_camellia192_crypt
INSTANCE_BLOCKCIPHER(Camellia192)
{-|
'Camellia256' provides the same interface as 'Camellia', but is restricted to 256-bit keys.
-}
newtype Camellia256 = Camellia256 SecureMem
instance NettleCipher Camellia256 where
nc_cipherInit = Tagged (\ctx _ key -> c_hs_camellia256_init ctx key)
nc_cipherName = Tagged "Camellia-256"
nc_cipherKeySize = Tagged $ KeySizeFixed 32
nc_ctx_size = Tagged c_hs_camellia256_ctx_size
nc_ctx (Camellia256 c) = c
nc_Ctx = Camellia256
instance NettleBlockCipher Camellia256 where
nbc_blockSize = Tagged 16
nbc_encrypt_ctx_offset = Tagged c_hs_camellia256_ctx_encrypt
nbc_decrypt_ctx_offset = Tagged c_hs_camellia256_ctx_decrypt
nbc_ecb_encrypt = Tagged c_camellia256_crypt
nbc_ecb_decrypt = Tagged c_camellia256_crypt
nbc_fun_encrypt = Tagged p_camellia256_crypt
nbc_fun_decrypt = Tagged p_camellia256_crypt
INSTANCE_BLOCKCIPHER(Camellia256)
{-|
'CAST128' is a block cipher specified in RFC 2144. It uses a 64 bit (8 bytes) 'blockSize',
and a variable key size of 40 up to 128 bits (5 to 16 bytes).
-}
newtype CAST128 = CAST128 SecureMem
instance NettleCipher CAST128 where
nc_cipherInit = Tagged c_cast5_set_key
nc_cipherName = Tagged "CAST-128"
nc_cipherKeySize = Tagged $ KeySizeRange 5 16
nc_ctx_size = Tagged c_cast128_ctx_size
nc_ctx (CAST128 c) = c
nc_Ctx = CAST128
instance NettleBlockCipher CAST128 where
nbc_blockSize = Tagged 8
nbc_ecb_encrypt = Tagged c_cast128_encrypt
nbc_ecb_decrypt = Tagged c_cast128_decrypt
nbc_fun_encrypt = Tagged p_cast128_encrypt
nbc_fun_decrypt = Tagged p_cast128_decrypt
INSTANCE_BLOCKCIPHER(CAST128)
{-|
'DES' is the old Data Encryption Standard, specified by NIST.
It uses a 'blockSize' of 64 bits (8 bytes), and a key size of 56 bits.
The key is given as 8 bytes, as one bit per byte is used as a parity bit.
The parity bit is ignored by this implementation.
-}
newtype DES = DES SecureMem
instance NettleCipher DES where
nc_cipherInit = Tagged $ \ctxptr _ -> c_des_set_key ctxptr
nc_cipherName = Tagged "DES"
nc_cipherKeySize = Tagged $ KeySizeFixed 8
nc_ctx_size = Tagged c_des_ctx_size
nc_ctx (DES c) = c
nc_Ctx = DES
instance NettleBlockCipher DES where
nbc_blockSize = Tagged 8
nbc_ecb_encrypt = Tagged c_des_encrypt
nbc_ecb_decrypt = Tagged c_des_decrypt
nbc_fun_encrypt = Tagged p_des_encrypt
nbc_fun_decrypt = Tagged p_des_decrypt
INSTANCE_BLOCKCIPHER(DES)
{-|
'DES_EDE3' uses 3 'DES' keys @k1 || k2 || k3@.
Encryption first encrypts with k1, then decrypts with k2, then encrypts with k3.
The 'blockSize' is the same as for 'DES': 64 bits (8 bytes),
and the keys are simply concatenated, forming a 24 byte key string (with 168 bits actually getting used).
-}
newtype DES_EDE3 = DES_EDE3 SecureMem
instance NettleCipher DES_EDE3 where
nc_cipherInit = Tagged $ \ctxptr _ -> c_des3_set_key ctxptr
nc_cipherName = Tagged "DES-EDE3"
nc_cipherKeySize = Tagged $ KeySizeFixed 24
nc_ctx_size = Tagged c_des3_ctx_size
nc_ctx (DES_EDE3 c) = c
nc_Ctx = DES_EDE3
instance NettleBlockCipher DES_EDE3 where
nbc_blockSize = Tagged 8
nbc_ecb_encrypt = Tagged c_des3_encrypt
nbc_ecb_decrypt = Tagged c_des3_decrypt
nbc_fun_encrypt = Tagged p_des3_encrypt
nbc_fun_decrypt = Tagged p_des3_decrypt
INSTANCE_BLOCKCIPHER(DES_EDE3)
{-|
'SERPENT' is one of the AES finalists, designed by Ross Anderson, Eli Biham and Lars Knudsen.
The 'blockSize' is 128 bits (16 bytes), and the valid key sizes are from 128 bits to 256 bits (16 to 32 bytes),
although smaller bits are just padded with zeroes.
'aeadInit' only supports the 'AEAD_GCM' mode for now.
-}
newtype SERPENT = SERPENT SecureMem
instance NettleCipher SERPENT where
nc_cipherInit = Tagged c_serpent_set_key
nc_cipherName = Tagged "SERPENT"
nc_cipherKeySize = Tagged $ KeySizeRange 16 32
nc_ctx_size = Tagged c_serpent_ctx_size
nc_ctx (SERPENT c) = c
nc_Ctx = SERPENT
instance NettleBlockCipher SERPENT where
nbc_blockSize = Tagged 16
nbc_ecb_encrypt = Tagged c_serpent_encrypt
nbc_ecb_decrypt = Tagged c_serpent_decrypt
nbc_fun_encrypt = Tagged p_serpent_encrypt
nbc_fun_decrypt = Tagged p_serpent_decrypt
INSTANCE_BLOCKCIPHER(SERPENT)
{-|
'TWOFISH' is another AES finalist, designed by Bruce Schneier and others.
'TWOFISH' uses a the same 'blockSize' and key sizes as 'AES'.
'aeadInit' only supports the 'AEAD_GCM' mode for now.
-}
newtype TWOFISH = TWOFISH SecureMem
instance NettleCipher TWOFISH where
nc_cipherInit = Tagged c_twofish_set_key
nc_cipherName = Tagged "TWOFISH"
nc_cipherKeySize = Tagged $ KeySizeEnum [16,24,32]
nc_ctx_size = Tagged c_twofish_ctx_size
nc_ctx (TWOFISH c) = c
nc_Ctx = TWOFISH
instance NettleBlockCipher TWOFISH where
nbc_blockSize = Tagged 16
nbc_ecb_encrypt = Tagged c_twofish_encrypt
nbc_ecb_decrypt = Tagged c_twofish_decrypt
nbc_fun_encrypt = Tagged p_twofish_encrypt
nbc_fun_decrypt = Tagged p_twofish_decrypt
INSTANCE_BLOCKCIPHER(TWOFISH)
{-|
'ARCFOUR' is a stream cipher, also known under the trade marked name RC4.
Valid key sizes are from 1 to 256 bytes.
-}
newtype ARCFOUR = ARCFOUR SecureMem
instance NettleCipher ARCFOUR where
nc_cipherInit = Tagged c_arcfour_set_key
nc_cipherName = Tagged "ARCFOUR"
nc_cipherKeySize = Tagged $ KeySizeEnum [16,24,32]
nc_ctx_size = Tagged c_arcfour_ctx_size
nc_ctx (ARCFOUR c) = c
nc_Ctx = ARCFOUR
instance NettleStreamCipher ARCFOUR where
nsc_streamCombine = Tagged c_arcfour_crypt
INSTANCE_STREAMCIPHER(ARCFOUR)
{-|
'StreamNonceCipher' are special stream ciphers that can encrypt many messages with the same key;
setting a nonce restarts the cipher.
A good value for the nonce is a message/packet counter. Usually a nonce should not be reused with the same key.
-}
class StreamCipher cipher => StreamNonceCipher cipher where
streamNonceSize :: cipher -> KeySizeSpecifier
streamSetNonce :: cipher -> B.ByteString -> Maybe cipher
word64BE :: Word64 -> B.ByteString
word64BE value = B.pack $ _work (8::Int) [] value where
_work 0 r _ = r
_work n r v = let d = v `shiftR` 8; m = fromIntegral v :: Word8 in _work (n-1) (m:r) d
{-|
Sets a 'Word64' as 8-byte nonce (bigendian encoded)
-}
streamSetNonceWord64 :: StreamNonceCipher cipher => cipher -> Word64 -> Maybe cipher
streamSetNonceWord64 c nonce = streamSetNonce c $ word64BE nonce
-- set nonce to 0 on init
wrap_chacha_set_key :: Ptr Word8 -> Word -> Ptr Word8 -> IO ()
wrap_chacha_set_key ctxptr _ keyptr = do
c_chacha_set_key ctxptr keyptr
withByteStringPtr (B.replicate 8 0) $ \_ nonceptr ->
c_chacha_set_nonce ctxptr nonceptr
-- check nonce length
wrap_chacha_set_nonce :: Ptr Word8 -> Word -> Ptr Word8 -> IO ()
wrap_chacha_set_nonce ctxptr ivlen ivptr = if ivlen == 8 then c_chacha_set_nonce ctxptr ivptr else fail "Invalid nonce length"
{-|
'CHACHA' is a variant of the 'SALSA20' stream cipher, both designed by D. J. Bernstein.
Key size is 256 bits (32 bytes).
'CHACHA' works similar to 'SALSA20'; it could theoretically also support 128-bit keys, but there is no need for it as they share the same performance.
ChaCha uses a blocksize of 64 bytes internally; if crpyted input isn't aligned to 64 bytes it will
pad it with 0 and store the encrypted padding to xor with future input data.
Each message also requires a 8-byte ('Word64') nonce (which is initialized to 0; you can use a message sequence number).
Don't reuse a nonce with the same key.
Setting a nonce also resets the remaining padding data.
-}
newtype CHACHA = CHACHA (SecureMem, B.ByteString)
instance NettleCipher CHACHA where
nc_cipherInit = Tagged wrap_chacha_set_key
nc_cipherName = Tagged "ChaCha"
nc_cipherKeySize = Tagged $ KeySizeFixed 32
nc_ctx_size = Tagged c_chacha_ctx_size
nc_ctx (CHACHA (c, _)) = c
nc_Ctx c = CHACHA (c, B.empty)
instance NettleBlockedStreamCipher CHACHA where
nbsc_blockSize = Tagged 64
nbsc_IncompleteState (CHACHA (c, _)) inc = CHACHA (c, inc)
nbsc_incompleteState (CHACHA (_, inc)) = inc
nbsc_streamCombine = Tagged c_chacha_crypt
nbsc_nonceSize = Tagged $ KeySizeFixed 8
nbsc_setNonce = Tagged $ Just wrap_chacha_set_nonce
INSTANCE_BLOCKEDSTREAMNONCECIPHER(CHACHA)
-- set nonce to 0 on init
wrap_salsa20_set_key :: Ptr Word8 -> Word -> Ptr Word8 -> IO ()
wrap_salsa20_set_key ctxptr keylen keyptr = do
c_salsa20_set_key ctxptr keylen keyptr
withByteStringPtr (B.replicate 8 0) $ \_ nonceptr ->
c_salsa20_set_nonce ctxptr nonceptr
-- check nonce length
wrap_salsa20_set_nonce :: Ptr Word8 -> Word -> Ptr Word8 -> IO ()
wrap_salsa20_set_nonce ctxptr ivlen ivptr = if ivlen == 8 then c_salsa20_set_nonce ctxptr ivptr else fail "Invalid nonce length"
{-|
'SALSA20' is a fairly recent stream cipher designed by D. J. Bernstein.
Valid key sizes are 128 and 256 bits (16 and 32 bytes).
Salsa20 uses a blocksize of 64 bytes internally; if crpyted input isn't aligned to 64 bytes it will
pad it with 0 and store the encrypted padding to xor with future input data.
Each message also requires a 8-byte ('Word64') nonce (which is initialized to 0; you can use a message sequence number).
Don't reuse a nonce with the same key.
Setting a nonce also resets the remaining padding data.
-}
newtype SALSA20 = SALSA20 (SecureMem, B.ByteString)
instance NettleCipher SALSA20 where
nc_cipherInit = Tagged wrap_salsa20_set_key
nc_cipherName = Tagged "Salsa20"
nc_cipherKeySize = Tagged $ KeySizeEnum [16,32]
nc_ctx_size = Tagged c_salsa20_ctx_size
nc_ctx (SALSA20 (c, _)) = c
nc_Ctx c = SALSA20 (c, B.empty)
instance NettleBlockedStreamCipher SALSA20 where
nbsc_blockSize = Tagged 64
nbsc_IncompleteState (SALSA20 (c, _)) inc = SALSA20 (c, inc)
nbsc_incompleteState (SALSA20 (_, inc)) = inc
nbsc_streamCombine = Tagged c_salsa20_crypt
nbsc_nonceSize = Tagged $ KeySizeFixed 8
nbsc_setNonce = Tagged $ Just wrap_salsa20_set_nonce
INSTANCE_BLOCKEDSTREAMNONCECIPHER(SALSA20)
{-|
'ESTREAM_SALSA20' is the same as 'SALSA20', but uses only 12 instead of 20 rounds in mixing.
-}
newtype ESTREAM_SALSA20 = ESTREAM_SALSA20 (SecureMem, B.ByteString)
instance NettleCipher ESTREAM_SALSA20 where
nc_cipherInit = Tagged wrap_salsa20_set_key
nc_cipherName = Tagged "eSTREAM-Salsa20"
nc_cipherKeySize = Tagged $ KeySizeEnum [16,32]
nc_ctx_size = Tagged c_salsa20_ctx_size
nc_ctx (ESTREAM_SALSA20 (c, _)) = c
nc_Ctx c = ESTREAM_SALSA20 (c, B.empty)
instance NettleBlockedStreamCipher ESTREAM_SALSA20 where
nbsc_blockSize = Tagged 64
nbsc_IncompleteState (ESTREAM_SALSA20 (c, _)) inc = ESTREAM_SALSA20 (c, inc)
nbsc_incompleteState (ESTREAM_SALSA20 (_, inc)) = inc
nbsc_streamCombine = Tagged c_salsa20r12_crypt
nbsc_nonceSize = Tagged $ KeySizeFixed 8
nbsc_setNonce = Tagged $ Just wrap_salsa20_set_nonce
INSTANCE_BLOCKEDSTREAMNONCECIPHER(ESTREAM_SALSA20)
| stbuehler/haskell-nettle | src/Crypto/Nettle/Ciphers.hs | mit | 23,016 | 8 | 11 | 4,318 | 3,722 | 1,942 | 1,780 | -1 | -1 |
{-# LANGUAGE OverloadedStrings, ScopedTypeVariables #-}
module Lib
( someFunc
) where
import Reflex.Dom
import Data.JSString ()
import GHCJS.Types
import GUI.ChannelDrawer
import GUI.Player
import Data.Monoid
someFunc :: IO ()
someFunc = mainWidget mainUI
-- Needed until Reflex.Dom version 0.4 is released
foreign import javascript unsafe
"$1.withCredentials = true;"
setRequestWithCredentials :: JSVal -> IO ()
tvhBaseUrl :: String
tvhBaseUrl = "http://localhost:9981/"
navBar :: MonadWidget t m => m ()
navBar = do
elClass "nav" "navbar navbar-default navbar-static-top" $ do
divClass "container-fluid" $ do
divClass "navbar-header" $ do
divClass "navbar-brand" $ do
text "Tvheadend frontend"
mainUI :: MonadWidget t m => m ()
mainUI = do
navBar
divClass "container-fluid" $ do
divClass "row" $ do
curChannel <- elAttr "div"
("class" =: "col-lg-2" <>
-- height:90vh to fit the list inside the viewport
-- overflow-y:auto to get vertical scrollbar
-- padding-right:0px to pull scrollbar closer to the list
"style" =: "height:90vh;overflow-y:auto;padding-right:0px") $ do
-- create the channel drawer and react to events fired when a channel is selected
channelDrawer tvhBaseUrl
divClass "col-lg-10" $ do
player tvhBaseUrl curChannel
| simonvandel/tvheadend-frontend | src/Lib.hs | mit | 1,429 | 4 | 19 | 367 | 275 | 135 | 140 | 33 | 1 |
module LogicCode
( HuffmanNode,
truthTable,
grayCode,
huffmanCode
) where
data HuffmanNode a = Empty | Leaf (a, Int) | Branch Int (HuffmanNode a) (HuffmanNode a)
--Problem 46 - 49: Problem 48: Truth tables for logical expressions.
--Eg: truthTable 3 (\[a, b, c] -> Logical expr involving a, b, and c)
truthTable :: Int -> ([Bool] -> Bool) -> IO ()
truthTable n fn = printTable $ map (\x -> x ++ [fn x]) (cart n [True, False]) where
printTable :: [[Bool]] -> IO ()
printTable = mapM_ (putStrLn . concatMap showSpace) where
showSpace :: Bool -> String
showSpace True = show True ++ " "
showSpace False = show False ++ " "
cart :: Int -> [a] -> [[a]]
cart 1 xs = foldr (\x acc -> [x] : acc) [] xs
cart l xs = [ x ++ y | x <- cart 1 xs, y <- cart (l - 1) xs]
--Problem 49: Gray codes.
--An n-bit Gray code is a sequence of n-bit strings constructed according to certain rules; for example,
--n = 1: C(1) = ['0','1'].
--n = 2: C(2) = ['00','01','11','10'].
--n = 3: C(3) = ['000','001','011','010',´110´,´111´,´101´,´100´].
grayCode :: Int -> [String]
grayCode 1 = ["0", "1"]
grayCode n = map ('0':) (grayCode $ n - 1) ++ (map ('1':) $ reverse $ grayCode (n - 1))
--Problem 50: Huffman Codes.
--Generate a Huffman code list from a given list of alphabets and their frequencies.
huffmanCode :: (Ord a) => [(a, Int)] -> [(a, String)]
huffmanCode ls = sort' $ process "" $ makeTree $ sort $ turnLeaf ls where
sort :: [HuffmanNode a] -> [HuffmanNode a]
sort [] = []
sort (x : xs) =
let smallerSorted = sort [a | a <- xs, snd' a <= snd' x]
biggerSorted = sort [a | a <- xs, snd' a > snd' x]
in smallerSorted ++ [x] ++ biggerSorted
turnLeaf :: [(a, Int)] -> [HuffmanNode a]
turnLeaf = map Leaf
makeTree :: [HuffmanNode a] -> HuffmanNode a
makeTree [tr] = tr
makeTree (m : n : ys) = makeTree $ sort $ Branch (snd' m + snd' n) m n : ys
process :: String -> HuffmanNode a -> [(a, String)]
process _ Empty = []
process str (Leaf (e, _)) = [(e, str)]
process str (Branch _ ltr rtr) = process (str ++ "0") ltr ++ process (str ++ "1") rtr
snd' :: HuffmanNode a -> Int
snd' (Leaf (_, n)) = n
snd' (Branch n _ _) = n
sort' :: (Ord a) => [(a, String)] -> [(a, String)]
sort' [] = []
sort' (x : xs) =
let smallerSorted = sort' [a | a <- xs, fst a <= fst x]
biggerSorted = sort' [a | a <- xs, fst x < fst a]
in smallerSorted ++ [x] ++ biggerSorted
| 5hubh4m/99-haskell-problems | LogicCode.hs | mit | 2,437 | 0 | 15 | 573 | 1,044 | 555 | 489 | 45 | 7 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE CPP #-}
module Data.Bson.Types
( RegexOption(..)
, RegexOptions
, Value(..)
, Binary(..)
, ObjectId(..)
, Document
, Array
, Label
, Field
) where
import Data.Int (Int32, Int64)
import Data.Time.Clock (UTCTime)
import Data.Time.Format ()
import Data.Typeable (Typeable)
import Data.Word (Word32, Word16)
import qualified Data.ByteString as S
import Data.BitSet.Word (BitSet)
import Data.Vector (Vector)
import Data.Word.Word24 (Word24)
import Data.Text (Text)
import Data.UUID (UUID)
import {-# SOURCE #-} Data.Bson.Document (Document)
-- | Options for 'ValueRegex', constructors order is important because
-- it's binary representation should be encoded in alphabetical order.
data RegexOption = RegexOptionCaseInsensitive -- i
| RegexOptionLocaleDependent -- l
| RegexOptionMultiline -- m
| RegexOptionDotall -- s
| RegexOptionUnicode -- u
| RegexOptionVerbose -- x
deriving (Eq, Show, Typeable, Enum)
type RegexOptions = BitSet RegexOption
-- | A value is one of the following types of values
data Value = ValueDouble {-# UNPACK #-} !Double
| ValueString {-# UNPACK #-} !Text
| ValueDocument !Document
| ValueArray {-# UNPACK #-} !Array
| ValueBinary !Binary
| ValueObjectId {-# UNPACK #-} !ObjectId
| ValueBool !Bool
| ValueUtcTime {-# UNPACK #-} !UTCTime
| ValueNull
| ValueRegex {-# UNPACK #-} !Text !RegexOptions
| ValueJavascript {-# UNPACK #-} !Text
| ValueJavascriptWithScope {-# UNPACK #-} !Text !Document
| ValueInt32 {-# UNPACK #-} !Int32
| ValueInt64 {-# UNPACK #-} !Int64
| ValueTimestamp {-# UNPACK #-} !Int64
| ValueMin
| ValueMax
deriving (Eq, Show, Typeable)
type Label = Text
type Array = Vector Value
type Field = (Label, Value)
data ObjectId = ObjectId
{ objectIdTime :: {-# UNPACK #-} !Word32
, objectIdMachine :: {-# UNPACK #-} !Word24
, objectIdPid :: {-# UNPACK #-} !Word16
, objectIdInc :: {-# UNPACK #-} !Word24
} deriving (Eq, Show, Typeable)
data Binary = BinaryGeneric {-# UNPACK #-} !S.ByteString
| BinaryFunction {-# UNPACK #-} !S.ByteString
| BinaryUuid {-# UNPACK #-} !UUID
| BinaryMd5 {-# UNPACK #-} !S.ByteString
| BinaryUserDefined {-# UNPACK #-} !S.ByteString
deriving (Eq, Show, Typeable)
| lambda-llama/bresson | src/Data/Bson/Types.hs | mit | 2,635 | 0 | 9 | 774 | 515 | 312 | 203 | 75 | 0 |
module Graphics.Urho3D.UI.Internal.Sprite(
Sprite
, spriteCntx
, sharedSpritePtrCntx
, SharedSprite
) where
import qualified Language.C.Inline as C
import qualified Language.C.Inline.Context as C
import qualified Language.C.Types as C
import Graphics.Urho3D.Container.Ptr
import qualified Data.Map as Map
data Sprite
spriteCntx :: C.Context
spriteCntx = mempty {
C.ctxTypesTable = Map.fromList [
(C.TypeName "Sprite", [t| Sprite |])
]
}
sharedPtrImpl "Sprite" | Teaspot-Studio/Urho3D-Haskell | src/Graphics/Urho3D/UI/Internal/Sprite.hs | mit | 494 | 0 | 11 | 89 | 120 | 80 | 40 | -1 | -1 |
-- Examples from chapter 8
-- http://learnyouahaskell.com/making-our-own-types-and-typeclasses
import qualified Data.Map as Map
data Point = Point Float Float deriving (Show)
data Shape = Circle Point Float | Rectangle Point Point deriving (Show)
surface :: Shape -> Float
surface (Circle _ r) = pi * r ^ 2
surface (Rectangle (Point x1 y1) (Point x2 y2)) = (abs $ x2 - x1) * (abs $ y2 - y1)
nudge :: Shape -> Float -> Float -> Shape
nudge (Circle (Point x y) r) a b = Circle (Point (x+a) (y+b)) r
nudge (Rectangle (Point x1 y1) (Point x2 y2)) a b = Rectangle (Point (x1+a) (y1+b)) (Point (x2+a) (y2+b))
baseCircle :: Float -> Shape
baseCircle = Circle (Point 0 0)
baseRect :: Float -> Float -> Shape
baseRect width height = Rectangle (Point 0 0) (Point width height)
data Person = Person { firstName :: String
, lastName :: String
, age :: Int
, height :: Float
, phoneNumber :: String
, flavor :: String
} deriving (Show)
data Day = Monday | Tuesday | Wednesday | Thursday | Friday | Saturday | Sunday
deriving (Eq, Ord, Show, Read, Bounded, Enum)
type PhoneNumber = String
type Name = String
type PhoneBook = [(Name,PhoneNumber)]
type IntMap = Map.Map Int
data LockerState = Taken | Free deriving (Show, Eq)
type Code = String
type LockerMap = Map.Map Int (LockerState, Code)
lockerLookup :: Int -> LockerMap -> Either String Code
lockerLookup lockerNumber map =
case Map.lookup lockerNumber map of
Nothing -> Left $ "Locker number " ++ show lockerNumber ++ " doesn't exist!"
Just (state, code) -> if state /= Taken
then Right code
else Left $ "Locker " ++ show lockerNumber ++ " is already taken!"
lockers :: LockerMap
lockers = Map.fromList
[(100,(Taken,"ZD39I"))
,(101,(Free,"JAH3I"))
,(103,(Free,"IQSA9"))
,(105,(Free,"QOTSA"))
,(109,(Taken,"893JJ"))
,(110,(Taken,"99292"))
]
data Tree a = EmptyTree | Node a (Tree a) (Tree a) deriving (Show, Read, Eq)
singleton :: a -> Tree a
singleton x = Node x EmptyTree EmptyTree
treeInsert :: (Ord a) => a -> Tree a -> Tree a
treeInsert x EmptyTree = singleton x
treeInsert x (Node a left right)
| x == a = Node x left right
| x < a = Node a (treeInsert x left) right
| x > a = Node a left (treeInsert x right)
treeElem :: (Ord a) => a -> Tree a -> Bool
treeElem x EmptyTree = False
treeElem x (Node a left right)
| x == a = True
| x < a = treeElem x left
| x > a = treeElem x right
data TrafficLight = Red | Yellow | Green
instance Eq TrafficLight where
Red == Red = True
Green == Green = True
Yellow == Yellow = True
_ == _ = False
class YesNo a where
yesno :: a -> Bool
instance YesNo Int where
yesno 0 = False
yesno _ = True
instance YesNo [a] where
yesno [] = False
yesno _ = True
instance YesNo Bool where
yesno = id
instance YesNo (Maybe a) where
yesno (Just _) = True
yesno Nothing = False
| Sgoettschkes/learning | haskell/LearnYouAHaskell/08.hs | mit | 3,046 | 0 | 11 | 813 | 1,260 | 670 | 590 | 78 | 3 |
{-|
Module: Flaw.UI.ScrollBox
Description: Scroll box.
License: MIT
-}
module Flaw.UI.ScrollBox
( ScrollBox(..)
, newScrollBox
, ScrollBar(..)
, newScrollBar
, newVerticalScrollBar
, newHorizontalScrollBar
, processScrollBarEvent
, ensureVisibleScrollBoxArea
) where
import Control.Concurrent.STM
import Control.Monad
import Data.Maybe
import Flaw.Graphics
import Flaw.Graphics.Canvas
import Flaw.Input.Mouse
import Flaw.Math
import Flaw.UI
import Flaw.UI.Drawer
data ScrollBox = ScrollBox
{ scrollBoxElement :: !SomeScrollable
-- | Position of left-top corner of child element
-- relative to scroll box' left-top corner, i.e. <= 0.
, scrollBoxScrollVar :: {-# UNPACK #-} !(TVar Position)
, scrollBoxSizeVar :: {-# UNPACK #-} !(TVar Size)
}
newScrollBox :: Scrollable e => e -> STM ScrollBox
newScrollBox element = do
scrollVar <- newTVar $ Vec2 0 0
sizeVar <- newTVar $ Vec2 0 0
return ScrollBox
{ scrollBoxElement = SomeScrollable element
, scrollBoxScrollVar = scrollVar
, scrollBoxSizeVar = sizeVar
}
instance Element ScrollBox where
layoutElement ScrollBox
{ scrollBoxElement = SomeScrollable element
, scrollBoxSizeVar = sizeVar
} size = do
writeTVar sizeVar size
layoutElement element size
dabElement ScrollBox
{ scrollBoxElement = SomeScrollable element
, scrollBoxScrollVar = scrollVar
, scrollBoxSizeVar = sizeVar
} (Vec2 x y) = if x < 0 || y < 0 then return False else do
size <- readTVar sizeVar
let Vec2 sx sy = size
if x < sx && y < sy then do
scroll <- readTVar scrollVar
let Vec2 ox oy = scroll
dabElement element $ Vec2 (x - ox) (y - oy)
else return False
elementMouseCursor ScrollBox
{ scrollBoxElement = SomeScrollable element
} = elementMouseCursor element
renderElement ScrollBox
{ scrollBoxElement = SomeScrollable element
, scrollBoxScrollVar = scrollVar
, scrollBoxSizeVar = sizeVar
} drawer position@(Vec2 px py) = do
scroll <- readTVar scrollVar
size <- readTVar sizeVar
ssize <- scrollableElementSize element
-- correct scroll if needed
let
Vec2 ox oy = scroll
Vec2 sx sy = size
Vec2 ssx ssy = ssize
newScroll@(Vec2 nox noy) = Vec2
(min 0 $ max ox $ sx - ssx)
(min 0 $ max oy $ sy - ssy)
when (scroll /= newScroll) $ writeTVar scrollVar newScroll
r <- renderScrollableElement element drawer (position + newScroll) (Vec4 (-nox) (-noy) (sx - nox) (sy - noy))
return $ do
renderIntersectScissor $ Vec4 px py (px + sx) (py + sy)
r
processInputEvent ScrollBox
{ scrollBoxElement = SomeScrollable element
, scrollBoxScrollVar = scrollVar
} inputEvent inputState = case inputEvent of
MouseInputEvent mouseEvent -> case mouseEvent of
CursorMoveEvent x y -> do
scroll <- readTVar scrollVar
let Vec2 ox oy = scroll
processInputEvent element (MouseInputEvent (CursorMoveEvent (x - ox) (y - oy))) inputState
_ -> processInputEvent element inputEvent inputState
_ -> processInputEvent element inputEvent inputState
focusElement ScrollBox
{ scrollBoxElement = SomeScrollable element
} = focusElement element
unfocusElement ScrollBox
{ scrollBoxElement = SomeScrollable element
} = unfocusElement element
data ScrollBar = ScrollBar
{ scrollBarScrollBox :: !ScrollBox
, scrollBarDirection :: {-# UNPACK #-} !(Vec2 Metric)
, scrollBarSizeVar :: {-# UNPACK #-} !(TVar Size)
, scrollBarLastMousePositionVar :: {-# UNPACK #-} !(TVar (Maybe Position))
, scrollBarPressedVar :: {-# UNPACK #-} !(TVar Bool)
}
newScrollBar :: Vec2 Metric -> ScrollBox -> STM ScrollBar
newScrollBar direction scrollBox = do
sizeVar <- newTVar $ Vec2 0 0
lastMousePositionVar <- newTVar Nothing
pressedVar <- newTVar False
return ScrollBar
{ scrollBarScrollBox = scrollBox
, scrollBarDirection = direction
, scrollBarSizeVar = sizeVar
, scrollBarLastMousePositionVar = lastMousePositionVar
, scrollBarPressedVar = pressedVar
}
newVerticalScrollBar :: ScrollBox -> STM ScrollBar
newVerticalScrollBar = newScrollBar $ Vec2 0 1
newHorizontalScrollBar :: ScrollBox -> STM ScrollBar
newHorizontalScrollBar = newScrollBar $ Vec2 1 0
instance Element ScrollBar where
layoutElement ScrollBar
{ scrollBarSizeVar = sizeVar
} = writeTVar sizeVar
dabElement ScrollBar
{ scrollBarSizeVar = sizeVar
} (Vec2 x y) = if x < 0 || y < 0 then return False else do
size <- readTVar sizeVar
let Vec2 sx sy = size
return $ x < sx && y < sy
renderElement scrollBar@ScrollBar
{ scrollBarSizeVar = barSizeVar
, scrollBarLastMousePositionVar = lastMousePositionVar
, scrollBarPressedVar = pressedVar
} Drawer
{ drawerCanvas = canvas
, drawerStyles = DrawerStyles
{ drawerFlatStyleVariant = StyleVariant
{ styleVariantNormalStyle = flatNormalStyle
}
, drawerRaisedStyleVariant = StyleVariant
{ styleVariantNormalStyle = raisedNormalStyle
, styleVariantMousedStyle = raisedMousedStyle
, styleVariantPressedStyle = raisedPressedStyle
}
}
} (Vec2 px py) = do
barSize <- readTVar barSizeVar
let Vec2 sx sy = barSize
piece <- scrollBarPiece scrollBar
moused <- isJust <$> readTVar lastMousePositionVar
pressed <- readTVar pressedVar
let
pieceStyle
| pressed = raisedPressedStyle
| moused = raisedMousedStyle
| otherwise = raisedNormalStyle
return $ do
-- render border
drawBorderedRectangle canvas
(Vec4 px (px + 1) (px + sx - 1) (px + sx))
(Vec4 py (py + 1) (py + sy - 1) (py + sy))
(styleFillColor flatNormalStyle) (styleBorderColor flatNormalStyle)
case piece of
Just ScrollBarPiece
{ scrollBarPieceRect = pieceRect
} -> let Vec4 ppx ppy pqx pqy = pieceRect + Vec4 px py px py in
-- render piece
drawBorderedRectangle canvas
(Vec4 ppx (ppx + 1) (pqx - 1) pqx)
(Vec4 ppy (ppy + 1) (pqy - 1) pqy)
(styleFillColor pieceStyle) (styleBorderColor pieceStyle)
Nothing -> return ()
processInputEvent scrollBar@ScrollBar
{ scrollBarScrollBox = ScrollBox
{ scrollBoxScrollVar = scrollVar
}
, scrollBarLastMousePositionVar = lastMousePositionVar
, scrollBarPressedVar = pressedVar
} inputEvent _inputState = case inputEvent of
MouseInputEvent mouseEvent -> case mouseEvent of
MouseDownEvent LeftMouseButton -> do
writeTVar pressedVar True
return True
MouseUpEvent LeftMouseButton -> do
writeTVar pressedVar False
return True
RawMouseMoveEvent _x _y z -> do
piece <- scrollBarPiece scrollBar
case piece of
Just ScrollBarPiece
{ scrollBarPieceOffsetMultiplier = offsetMultiplier
} -> do
modifyTVar' scrollVar (+ signum offsetMultiplier * vecFromScalar (floor (z * (-15))))
return True
Nothing -> return False
CursorMoveEvent x y -> do
pressed <- readTVar pressedVar
when pressed $ do
maybeLastMousePosition <- readTVar lastMousePositionVar
case maybeLastMousePosition of
Just lastMousePosition -> do
piece <- scrollBarPiece scrollBar
case piece of
Just ScrollBarPiece
{ scrollBarPieceOffsetMultiplier = offsetMultiplier
} -> modifyTVar' scrollVar (+ (Vec2 x y - lastMousePosition) * offsetMultiplier)
Nothing -> return ()
Nothing -> return ()
writeTVar lastMousePositionVar $ Just $ Vec2 x y
return True
_ -> return False
MouseLeaveEvent -> do
writeTVar lastMousePositionVar Nothing
writeTVar pressedVar False
return True
_ -> return False
-- | Internal information about piece.
data ScrollBarPiece = ScrollBarPiece
{ scrollBarPieceRect :: {-# UNPACK #-} !Rect
, scrollBarPieceOffsetMultiplier :: {-# UNPACK #-} !(Vec2 Metric)
}
-- | Get scroll bar piece rect and piece offset multiplier.
scrollBarPiece :: ScrollBar -> STM (Maybe ScrollBarPiece)
scrollBarPiece ScrollBar
{ scrollBarScrollBox = ScrollBox
{ scrollBoxElement = SomeScrollable element
, scrollBoxScrollVar = scrollVar
, scrollBoxSizeVar = boxSizeVar
}
, scrollBarDirection = direction
, scrollBarSizeVar = barSizeVar
} = do
barSize <- readTVar barSizeVar
let Vec2 sx sy = barSize
boxSize <- readTVar boxSizeVar
scrollableSize <- scrollableElementSize element
scroll <- readTVar scrollVar
let
padding = 2
contentOffset = dot scroll direction
boxLength = dot boxSize direction
contentLength = dot scrollableSize direction
barLength = dot barSize direction - padding * 2
minPieceLength = min sx sy - padding * 2
pieceLength = max minPieceLength $ (barLength * boxLength) `quot` max 1 contentLength
pieceOffset = (negate contentOffset * (barLength - pieceLength)) `quot` max 1 (contentLength - boxLength)
Vec2 ppx ppy = vecFromScalar padding + direction * vecFromScalar pieceOffset
Vec2 psx psy = vecfmap (max minPieceLength) $ direction * vecFromScalar pieceLength
piece = if contentLength > boxLength then
Just ScrollBarPiece
{ scrollBarPieceRect = Vec4 ppx ppy (ppx + psx) (ppy + psy)
, scrollBarPieceOffsetMultiplier = direction * vecFromScalar (negate $ (contentLength - boxLength) `quot` max 1 (barLength - pieceLength))
}
else Nothing
return piece
-- | Process possibly scroll bar event.
-- Could be used for passing scrolling events from other elements.
processScrollBarEvent :: ScrollBar -> InputEvent -> InputState -> STM Bool
processScrollBarEvent scrollBar inputEvent inputState = case inputEvent of
MouseInputEvent RawMouseMoveEvent {} -> processInputEvent scrollBar inputEvent inputState
_ -> return False
-- | Adjust scrolling so the specified area (in content coords) is visible.
ensureVisibleScrollBoxArea :: ScrollBox -> Rect -> STM ()
ensureVisibleScrollBoxArea ScrollBox
{ scrollBoxScrollVar = scrollVar
, scrollBoxSizeVar = sizeVar
} (Vec4 left top right bottom) = do
scroll <- readTVar scrollVar
let Vec2 ox oy = scroll
size <- readTVar sizeVar
let Vec2 sx sy = size
-- dimensions are to be adjusted independently
-- function to adjust one dimension
let
adjust o s a b =
if a + o >= 0 then
if b + o <= s then o
else s - b
else -a
newScroll = Vec2 (adjust ox sx left right) (adjust oy sy top bottom)
unless (scroll == newScroll) $ writeTVar scrollVar newScroll
| quyse/flaw | flaw-ui/Flaw/UI/ScrollBox.hs | mit | 10,754 | 0 | 30 | 2,656 | 2,938 | 1,464 | 1,474 | 260 | 3 |
module Diamond (diamond) where
diamond :: Char -> Maybe [String]
diamond = error "You need to implement this function"
| exercism/xhaskell | exercises/practice/diamond/src/Diamond.hs | mit | 120 | 0 | 7 | 20 | 32 | 18 | 14 | 3 | 1 |
import Control.Monad
main = print . msum $ do
x <- [ 1 .. 1000 ]
y <- [x + 1 .. div (1000 - x) 2 ]
let z = 1000 - x - y
return $ if x^2 + y^2 == z^2 && x + y + z == 1000
then Just $ x * y * z
else Nothing
| nickspinale/euler | complete/009.hs | mit | 253 | 0 | 18 | 110 | 141 | 72 | 69 | 8 | 2 |
module BFLib.BrainfuchFollow where
import Control.Monad.State
import Control.Monad.Writer
import System.IO
import BFLib.Brainfuch (Code
, Stack
, bfTail
, emptyStack
, incPtr
, decPtr
, incCell
, decCell
, bfGetLoop
, bfDropLoop)
{-
- Syntax
> Increment pointer
< Decrement pointer
+ Increment contents
- Decrement contents
. Put cell content
, Read cell content
[ ] Loop ([ - Skip following part if content == 0; ] go to last [ if content != 0)
-}
type StackCode = (Stack,Char)
-- As function: Stack -> IO ((a,[StackCode]),Stack)
type BFFState = WriterT [StackCode] (StateT Stack IO)
-- monadic ops
bffTell :: StackCode -> BFFState ()
bffTell sc = tell [sc]
mIncPtr :: BFFState ()
mIncPtr = WriterT . StateT $ \s -> let s' = incPtr s
in return (((),[(s','>')]),s')
mDecPtr :: BFFState ()
mDecPtr = WriterT . StateT $ \s -> let s' = decPtr s
in return (((),[(s','<')]),s')
mIncCell :: BFFState ()
mIncCell = WriterT . StateT $ \s -> let s' = incCell s
in return (((),[(s','+')]),s')
mDecCell :: BFFState ()
mDecCell = WriterT . StateT $ \s -> let s' = decCell s
in return (((),[(s','-')]),s')
mPrintContent :: BFFState ()
mPrintContent = WriterT . StateT $ \s@(_,e,_) -> (putStrLn . show) e >> hFlush stdout >> return (((),[(s,'.')]),s)
mReadContent :: BFFState ()
mReadContent = WriterT . StateT $ \(xs,_,ys) -> readLn >>= \e -> let s' = (xs,e,ys)
in return (((),[(s',',')]),s')
mIsZero :: BFFState Bool
mIsZero = WriterT . StateT $ \s@(_,e,_) -> return ((e == 0,[]),s)
-- Interpreter
bfInt :: Code -> BFFState ()
bfInt [] = return ()
bfInt allc@(c:cs) = case c of
'>' -> mIncPtr >> bfInt cs
'<' -> mDecPtr >> bfInt cs
'+' -> mIncCell >> bfInt cs
'-' -> mDecCell >> bfInt cs
'.' -> mPrintContent >> bfInt cs
',' -> mReadContent >> bfInt cs
'[' -> do
p <- mIsZero
if p
then bfInt . bfDropLoop $ allc
else let loopcode = bfGetLoop allc in do
bfInt loopcode
bfInt (c:cs)
_ -> bfInt cs
| dermesser/Brainfuch | BFLib/BrainfuchFollow.hs | mit | 2,592 | 0 | 17 | 1,043 | 839 | 457 | 382 | 54 | 9 |
module PartialRecordSel where
-- Partial record selectors use 'error' in the output (which is undefined)
-- Would be better to use 'panic' (or be able to skip them entirely).
data R = R1 { a :: Bool } | R2 { b :: Bool }
| antalsz/hs-to-coq | examples/base-tests/PartialRecordSel.hs | mit | 222 | 0 | 8 | 47 | 32 | 21 | 11 | 2 | 0 |
module Examples.EX3 where
import Control.Lens
import Control.Lens.Setter
import Control.Monad (void)
import Control.Monad.Trans.Class (lift)
import Data.List (intersperse, isPrefixOf)
import Data.Time.LocalTime
import Data.Maybe (catMaybes)
import Twilio.Key
import Twilio.IVR
data User = User {
lastname :: String,
firstname :: String,
extension :: Maybe String
}
deriving (Show)
users = [
User "Smith" "Joe" $ Just "7734",
User "Doe" "Jane" $ Just "1556",
User "Doe" "Linda" Nothing,
User "Samson" "Tina" $ Just "3443",
User "O'Donald" "Jack" $ Just "5432",
User "Sam-son" "Tony" $ Nothing
]
-- | match last name by removing non-keypad characters
matchingUsers :: [User] -> [Key] -> [User]
matchingUsers ux kx = filter (\u -> let lnky = catMaybes $ map letterToKey (lastname u) in
isPrefixOf kx lnky) ux
describeUser :: User -> TwilioIVRCoroutine ()
describeUser u = do
say (firstname u)
say (lastname u)
case extension u of
(Just x) -> say $ "Phone extension " ++ (intersperse ' ' x)
Nothing -> return ()
search :: Call -> TwilioIVRCoroutine ()
search _ = do
say "Welcome."
name <- gather "Please enter the last name of the person you wish to find. You do not have to enter the entire name. Finish with the pound key."
((finishOnKey .~ Just KPound).(timeout .~ 30))
case matchingUsers users name of
[] -> say "Sorry, no matching results found."
[x] -> describeUser x
xs -> do
say $ "We found "++(show $ length xs)++" matching users."
mapM_ describeUser xs
say "Have a nice day."
| steven777400/TwilioIVR | src/Examples/EX3.hs | mit | 1,669 | 1 | 16 | 427 | 518 | 264 | 254 | 44 | 3 |
{-# OPTIONS_GHC -Wall #-}
module LogAnalysis where
import Log
import Data.Char (isDigit)
parseMessage :: String -> LogMessage
parseMessage (x:' ':xs)
| x == 'I' = LogMessage Info first body
| x == 'W' = LogMessage Warning first body
| x == 'E' = LogMessage (Error first) second (trim body)
where body = tail . dropWhile isDigit $ xs
first = read . takeWhile isDigit $ xs
second = read . takeWhile isDigit . dropWhileHeader $ xs
where dropWhileHeader = tail . snd . span isDigit
trim = tail . dropWhile isDigit
parseMessage x = Unknown x
parse :: String -> [LogMessage]
parse = map parseMessage . lines
insert :: LogMessage -> MessageTree -> MessageTree
insert (Unknown _) tree = tree
insert _ tree@(Node _ (Unknown _) _) = tree
insert m (Leaf) = Node Leaf m Leaf
insert m@(LogMessage _ ts _) (Node l c@(LogMessage _ other _) r)
| other > ts = Node (insert m l) c r
| otherwise = Node l c (insert m r)
build :: [LogMessage] -> MessageTree
build [] = Leaf
build (xs) = foldl buildTree Leaf xs
where buildTree acc x = insert x acc
inOrder :: MessageTree -> [LogMessage]
inOrder (Leaf) = []
inOrder (Node l m r) = (inOrder l) ++ [m] ++ (inOrder r)
whatWentWrong :: [LogMessage] -> [String]
whatWentWrong [] = []
whatWentWrong (ms) = map printMsg $ filter bigs $ filter errors logs
where logs = inOrder $ build ms
bigs (LogMessage (Error n) _ _)
| n >= 50 = True
| otherwise = False
bigs _ = False
printMsg (LogMessage _ _ s) = s
printMsg (Unknown s) = s
errors (LogMessage (Error _) _ _) = True
errors _ = False
| tylerjl/cis194 | old/hw02/LogAnalysis.hs | mit | 1,674 | 0 | 11 | 453 | 716 | 360 | 356 | 43 | 4 |
{-|
Module : Export.TimetableImageCreator
Description : Primarily defines a function used to render SVGs with times.
-}
module Export.TimetableImageCreator
(renderTable, renderTableHelper, times) where
import Data.List (intersperse)
import qualified Data.Text as T
import Diagrams.Backend.SVG
import Diagrams.Prelude
days :: [T.Text]
days = ["Mon", "Tue", "Wed", "Thu", "Fri"]
-- |A list of lists of Texts, which has the "times" from 8:00 to 12:00, and
-- 1:00 to 8:00.times
times :: [[T.Text]]
times = map (\x -> [T.pack (show x ++ ":00")]) ([8..12] ++ [1..8] :: [Int])
blue3 :: Colour Double
blue3 = sRGB24read "#437699"
pink1 :: Colour Double
pink1 = sRGB24read "#DB94B8"
pomegranate :: Colour Double
pomegranate = sRGB24read "#F20C00"
cellWidth :: Double
cellWidth = 2
timeCellWidth :: Double
timeCellWidth = 1.2
cellHeight :: Double
cellHeight = 0.4
cellPaddingHeight :: Double
cellPaddingHeight = 0.1
fs :: Double
fs = 14
cell :: Diagram B
cell = rect cellWidth cellHeight
cellPadding :: Diagram B
cellPadding = rect cellWidth cellPaddingHeight
timeCell :: Diagram B
timeCell = rect timeCellWidth cellHeight # lw none
timeCellPadding :: Diagram B
timeCellPadding = rect timeCellWidth cellPaddingHeight # lw none
cellText :: T.Text -> Diagram B
cellText s = font "Trebuchet MS" $ text (T.unpack s) # fontSizeO (1024/900 * fs)
-- | Creates and accumulates cells according to the number of course.
makeCell :: Int -> [T.Text] -> Diagram B
makeCell maxCourse sList =
let actualCourse = length sList
emptyCellNum = if maxCourse == 0 then 1 else maxCourse - actualCourse
extraCell = replicate emptyCellNum [cellPadding # fc white # lc white, cellText "" # fc white <> cell # fc white # lc white]
in vsep 0.030 $
concat $ map (\x -> [cellPadding # fc background # lc background, cellText x # fc white <> cell # fc background # lc background]) sList ++ extraCell
where
background = getBackground sList
getBackground :: [T.Text] -> Colour Double
getBackground s
| null s = white
| length s == 1 = blue3
| otherwise = pomegranate
header :: T.Text -> Diagram B
header session = hcat (makeSessionCell session : map makeHeaderCell days) # centerX === headerBorder
makeSessionCell :: T.Text -> Diagram B
makeSessionCell s =
timeCellPadding === (cellText s <> timeCell)
makeHeaderCell :: T.Text -> Diagram B
makeHeaderCell s =
(cellPadding # lw none # fc white # lc white) === (cellText s <> cell # lw none)
makeTimeCell :: T.Text -> Diagram B
makeTimeCell s =
timeCellPadding === (cellText s <> timeCell)
makeRow :: [[T.Text]] -> Diagram B
makeRow ([x]:xs) =
let maxCourse = maximum (map length xs)
in (# centerX) . hcat $
makeTimeCell x : map (makeCell maxCourse) xs
makeRow _ = error "invalid timetable format"
headerBorder :: Diagram B
headerBorder = hrule 11.2 # lw medium # lc pink1
rowBorder :: Diagram B
rowBorder = hrule 11.2 # lw thin # lc pink1
makeTable :: [[[T.Text]]] -> T.Text -> Diagram B
makeTable s session = vsep 0.04 $ header session: intersperse rowBorder (map makeRow s)
-- |Creates a timetable by zipping the time and course tables.
renderTable :: String -> T.Text -> T.Text -> IO ()
renderTable filename courses session = do
let courseTable = partition5 $ map (\x -> [x | not (T.null x)]) $ T.splitOn "_" courses
renderTableHelper filename (zipWith (:) times courseTable) session
where
partition5 [] = []
partition5 lst = take 5 lst : partition5 (drop 5 lst)
-- |Renders an SVG with a width of 1024, though the documentation doesn't
-- specify the units, it is assumed that these are pixels.
renderTableHelper :: String -> [[[T.Text]]] -> T.Text -> IO ()
renderTableHelper filename schedule session = do
let g = makeTable schedule session
renderSVG filename (mkWidth 1024) g
| Courseography/courseography | app/Export/TimetableImageCreator.hs | gpl-3.0 | 3,855 | 44 | 18 | 772 | 1,286 | 666 | 620 | 82 | 2 |
{-# LANGUAGE QuasiQuotes,DataKinds,GADTs,RankNTypes,ScopedTypeVariables,KindSignatures,TemplateHaskell, FlexibleInstances,TypeFamilies #-}
module Z3Tutorial where
import Language.SMTLib2
import Language.SMTLib2.Pipe (createPipe)
import Language.SMTLib2.Debug (debugBackend)
import qualified Language.SMTLib2.Internals.Type.List as List
import qualified Language.SMTLib2.Internals.Expression as SMT
import qualified Language.SMTLib2.Internals.Type as Type
import Data.Proxy
import Data.GADT.Compare
import Data.GADT.Show
import Data.Typeable
runExample :: (forall b. Backend b => SMT b r) -> IO r
runExample ex = withBackend (fmap debugBackend $ createPipe "z3" ["-in","-smt2"]) ex
query :: (Backend b)
=> List Repr tps
-> (List (Expr b) tps -> SMT b ())
-> SMT b (Maybe (List Value tps))
query tps f = do
args <- List.mapM declareVar tps
f args
res <- checkSat
case res of
Sat -> do
vals <- List.mapM getValue args
return $ Just vals
_ -> return Nothing
-- | Basic commands
example1 :: Backend b => SMT b (Maybe Integer)
example1 = do
a <- declareVar int
f <- declareFun (int ::: bool ::: Nil) int
assert $ a .>. cint 10
assert $ fun f (a .:. true .:. nil) .<. cint 100
res <- checkSat
case res of
Sat -> do
IntValue v <- getValue a
return $ Just v
_ -> return Nothing
-- | Using scopes
example2 :: Backend b => SMT b (Maybe (Integer,Integer,Integer),Maybe (Integer,Integer,Integer))
example2 = do
x <- declareVar int
y <- declareVar int
z <- declareVar int
q1 <- stack $ do
x .+. y .==. cint 10 >>= assert
x .+. (cint 2 .*. y) .==. cint 20 >>= assert
r1 <- checkSat
case r1 of
Sat -> do
IntValue vx <- getValue x
IntValue vy <- getValue y
IntValue vz <- getValue z
return (Just (vx,vy,vz))
_ -> return Nothing
q2 <- stack $ do
(cint 3 .*. x) .+. y .==. cint 10 >>= assert
(cint 2 .*. x) .+. (cint 2 .*. y) .==. cint 21 >>= assert
r2 <- checkSat
case r2 of
Sat -> do
IntValue vx <- getValue x
IntValue vy <- getValue y
IntValue vz <- getValue z
return (Just (vx,vy,vz))
_ -> return Nothing
return (q1,q2)
-- | Propositional Logic
example3 :: Backend b => SMT b CheckSatResult
example3 = do
p <- declareVar bool
q <- declareVar bool
r <- declareVar bool
conjecture <- ((p .=>. q) .&. (q .=>. r)) .=>. (p .=>. r) >>= defineVar
not' conjecture >>= assert
checkSat
-- | Satisfiability and Validity
example4 :: Backend b => SMT b CheckSatResult
example4 = do
a <- declareVarNamed bool "a"
b <- declareVarNamed bool "b"
demorgan <- (a .&. b) .==. (not' $ (not' a) .|. (not' b)) >>= defineVarNamed "demorgan"
not' demorgan >>= assert
checkSat
-- | Uninterpreted functions and constants
example5 :: Backend b => SMT b (Maybe (Integer,Integer))
example5 = do
f <- declareFun (int ::: Nil) int
a <- declareVar int
b <- declareVar int
a .>. cint 20 >>= assert
b .>. a >>= assert
assert $ (fun f (cint 10 .:. nil)) .==. cint 1
r <- checkSat
case r of
Sat -> do
IntValue ra <- getValue a
IntValue rb <- getValue b
return $ Just (ra,rb)
_ -> return Nothing
example6 :: Backend b => SMT b (Maybe (List Value '[IntType,IntType,IntType,RealType,RealType]))
example6 = query (int ::: int ::: int ::: real ::: real ::: Nil)
(\(a ::: b ::: c ::: d ::: e ::: Nil) -> do
a .>. b .+. cint 2 >>= assert
a .==. (cint 2 .*. c) .+. cint 10 >>= assert
c .+. b .<=. cint 1000 >>= assert
d .>=. e >>= assert)
example7 :: Backend b => SMT b (Maybe (List Value [IntType,IntType,IntType,RealType,RealType]))
example7 = query (int ::: int ::: int ::: real ::: real ::: Nil)
(\(a ::: b ::: c ::: d ::: e ::: Nil) -> do
e .>. toReal (a .+. b) .+. creal 2 >>= assert
d .==. toReal c .+. creal 0.5 >>= assert
a .>. b >>= assert)
example8 :: Backend b => SMT b (Maybe (List Value [RealType,RealType]))
example8 = query (real ::: real ::: Nil)
(\(b ::: c ::: Nil) -> do
mult [b,b,b] .+. (b .*. c) .==. creal 3.0 >>= assert)
example9 :: Backend b => SMT b (Maybe (List Value [RealType,RealType,RealType]))
example9 = query (real ::: real ::: real ::: Nil)
(\(x ::: y ::: z ::: Nil) -> do
x .*. x .==. x .*. creal 2 >>= assert
x .*. y .==. x >>= assert
(y .-. creal 1) .*. z .==. creal 1 >>= assert)
example10 :: Backend b => SMT b (Maybe (List Value [IntType,IntType,IntType,IntType,IntType,IntType,IntType,RealType,RealType]))
example10 = query (int ::: int ::: int ::: int ::: int ::: int ::: int ::: real ::: real ::: Nil)
(\(a ::: r1 ::: r2 ::: r3 ::: r4 ::: r5 ::: r6 ::: b ::: c ::: Nil) -> do
a .==. cint 10 >>= assert
r1 .==. a `div'` cint 4 >>= assert
r2 .==. a `mod'` cint 4 >>= assert
r3 .==. a `rem'` cint 4 >>= assert
r4 .==. a `div'` cint (-4) >>= assert
r5 .==. a `mod'` cint (-4) >>= assert
r6 .==. a `rem'` cint (-4) >>= assert
b .>=. c ./. creal 3 >>= assert
c .>=. creal 20 >>= assert)
example11 :: Backend b => SMT b (Maybe (List Value '[BitVecType 64,BitVecType 64]))
example11 = query (bitvec (bw Proxy) ::: bitvec (bw Proxy) ::: Nil)
(\(x ::: y ::: Nil) -> do
not' (bvand (bvnot x) (bvnot y) .==. bvnot (bvor x y)) >>= assert)
example13 :: Backend b => SMT b CheckSatResult
example13 = do
let w = bw (Proxy::Proxy 4)
isPowerOfTwo <- defineFunNamed "isPowerOfTwo" (bitvec w ::: Nil) $
\(x ::: Nil) -> cbv 0 w .==. bvand x (bvsub x (cbv 1 w))
a <- declareVarNamed (bitvec w) "a"
args <- sequence [ a .==. cbv n w | n <- [0,1,2,4,8]]
assert $ not' (fun isPowerOfTwo (a .:. nil) .==. or' args)
checkSat
example14 :: Backend b => SMT b (Maybe (List Value [BitVecType 8,BitVecType 8]))
example14 = query (bitvec (bw Proxy) ::: bitvec (bw Proxy) ::: Nil)
$ \(a ::: b ::: Nil) -> do
not' (bvule a b .==. bvsle a b) >>= assert
example15 :: Backend b => SMT b (Integer,Integer)
example15 = do
x <- declareVar int
y <- declareVar int
a1 <- declareVar (array (int ::: Nil) int)
select1 a1 x .==. x >>= assert
store1 a1 x y .==. a1 >>= assert
--not' (x .==. y) >>= assert
checkSat
IntValue vx <- getValue x
IntValue vy <- getValue y
return (vx,vy)
example16 :: Backend b => SMT b (Integer,Integer,CheckSatResult)
example16 = do
all1 <- declareVar (array (int ::: Nil) int)
a <- declareVar int
i <- declareVar int
all1 .==. constArray (int ::: Nil) (cint 1) >>= assert
a .==. select1 all1 i >>= assert
checkSat
IntValue va <- getValue a
IntValue vi <- getValue i
assert $ not' (a .==. cint 1)
r <- checkSat
return (va,vi,r)
-- | Mapping Functions on Arrays
example17 :: Backend b => SMT b (CheckSatResult,CheckSatResult,String,CheckSatResult)
example17 = do
a <- declareVar (array (int ::: Nil) bool)
b <- declareVar (array (int ::: Nil) bool)
c <- declareVar (array (int ::: Nil) bool)
x <- declareVar int
r1 <- stack $ do
not' (map' (SMT.Logic SMT.And $(nat 2)) (a .:. b .:. nil) .==.
(map' SMT.Not ((map' (SMT.Logic SMT.Or $(nat 2))
((map' SMT.Not (b .:. nil)) .:.
(map' SMT.Not (a .:. nil)) .:. nil)) .:. nil))) >>= assert
map' SMT.Not (a .:. nil) .==. b >>= assert
checkSat
r2 <- stack $ do
select (map' (SMT.Logic SMT.And $(nat 2)) (a .:. b .:. nil)) (x .:. nil) .&.
not' (select a (x .:. nil)) >>= assert
checkSat
(r3,r4) <- stack $ do
select (map' (SMT.Logic SMT.Or $(nat 2)) (a .:. b .:. nil)) (x .:. nil) .&.
not' (select a (x .:. nil)) >>= assert
p <- checkSat
mdl <- getModel
not' (select b (x .:. nil)) >>= assert
q <- checkSat
return (mdl,q)
return (r1,r2,show r3,r4)
-- | Bags as Arrays
example18 :: Backend b => SMT b String
example18 = do
let a = array (int ::: int ::: Nil) int
bagUnion <- defineFunNamed "bag-union" (a ::: a ::: Nil) $
\(x ::: y ::: Nil) -> map' (SMT.Arith Type.NumInt SMT.Plus $(nat 2)) (x .:. y .:. nil)
s1 <- declareVarNamed a "s1"
s2 <- declareVarNamed a "s2"
s3 <- declareVarNamed a "s3"
s3 .==. fun bagUnion (s1 .:. s2 .:. nil) >>= assert
select s1 (cint 0 .:. cint 0 .:. nil) .==. cint 5 >>= assert
select s2 (cint 0 .:. cint 0 .:. nil) .==. cint 3 >>= assert
select s2 (cint 1 .:. cint 2 .:. nil) .==. cint 4 >>= assert
checkSat
fmap show getModel
-- Datatypes
data Pair par (e :: Type -> *) where
MkPair :: e t1 -> e t2 -> Pair '[t1,t2] e
instance Type.IsDatatype Pair where
type Parameters Pair = 'S ('S 'Z)
type Signature Pair = '[ '[ ParameterType Z, ParameterType (S Z) ] ]
data Datatype Pair = Pair deriving (Eq,Ord)
data Constr Pair sig where
ConMkPair :: Type.Constr Pair '[ ParameterType Z, ParameterType (S Z) ]
data Field Pair sig where
First :: Type.Field Pair (ParameterType Z)
Second :: Type.Field Pair (ParameterType (S Z))
datatypeGet (MkPair x y) = (Pair,getType x ::: getType y ::: Nil)
parameters _ = Succ (Succ Zero)
datatypeName _ = "Pair"
constructors Pair = ConMkPair ::: Nil
constrName ConMkPair = "MkPair"
test _ _ = True
fields ConMkPair = First ::: Second ::: Nil
construct (_ ::: _ ::: Nil) ConMkPair (x ::: y ::: Nil) = MkPair x y
deconstruct (MkPair x y)
= Type.ConApp
(getType x ::: getType y ::: Nil)
ConMkPair
(x ::: y ::: Nil)
fieldType First = ParameterRepr Zero
fieldType Second = ParameterRepr (Succ Zero)
fieldName First = "first"
fieldName Second = "second"
fieldGet (MkPair x _) First = x
fieldGet (MkPair _ y) Second = y
instance GEq (Type.Constr Pair) where
geq ConMkPair ConMkPair = Just Refl
instance GCompare (Type.Constr Pair) where
gcompare ConMkPair ConMkPair = GEQ
instance GEq (Type.Field Pair) where
geq First First = Just Refl
geq Second Second = Just Refl
geq _ _ = Nothing
instance GCompare (Type.Field Pair) where
gcompare First First = GEQ
gcompare First _ = GLT
gcompare _ First = GGT
gcompare Second Second = GEQ
-- | Records
example19 :: Backend b => SMT b (Pair '[IntType,IntType] Value,Pair '[IntType,IntType] Value,CheckSatResult)
example19 = do
let dt = Pair
registerDatatype dt
p1 <- declareVar (DataRepr dt (int ::: int ::: Nil))
p2 <- declareVar (DataRepr dt (int ::: int ::: Nil))
assert $ p1 .==. p2
assert $ (p1 .#. Second) .>. cint 20
checkSat
DataValue v1 <- getValue p1
DataValue v2 <- getValue p2
assert $ not' $ (p1 .#. First) .==. (p2 .#. First)
r <- checkSat
return (v1,v2,r)
data S' (par :: [Type]) (e :: Type -> *) where
A :: S' '[] e
B :: S' '[] e
C :: S' '[] e
instance Type.IsDatatype S' where
type Parameters S' = 'Z
type Signature S' = '[ '[], '[], '[] ]
data Datatype S' = S' deriving (Eq,Ord)
data Constr S' sig where
MkA :: Type.Constr S' '[]
MkB :: Type.Constr S' '[]
MkC :: Type.Constr S' '[]
data Field S' sig
datatypeGet A = (S',Nil)
datatypeGet B = (S',Nil)
datatypeGet C = (S',Nil)
parameters _ = Zero
datatypeName _ = "S"
constructors S' = MkA ::: MkB ::: MkC ::: Nil
constrName MkA = "A"
constrName MkB = "B"
constrName MkC = "C"
test A MkA = True
test B MkB = True
test C MkC = True
test _ _ = False
fields MkA = Nil
fields MkB = Nil
fields MkC = Nil
construct Nil MkA Nil = A
construct Nil MkB Nil = B
construct Nil MkC Nil = C
deconstruct A = Type.ConApp Nil MkA Nil
deconstruct B = Type.ConApp Nil MkB Nil
deconstruct C = Type.ConApp Nil MkC Nil
fieldName = undefined
fieldType = undefined
fieldGet = undefined
instance GEq (Type.Constr S') where
geq MkA MkA = Just Refl
geq MkB MkB = Just Refl
geq MkC MkC = Just Refl
geq _ _ = Nothing
instance GCompare (Type.Constr S') where
gcompare MkA MkA = GEQ
gcompare MkA _ = GLT
gcompare _ MkA = GGT
gcompare MkB MkB = GEQ
gcompare MkB _ = GLT
gcompare _ MkB = GGT
gcompare MkC MkC = GEQ
instance GEq (Type.Field S') where
geq = undefined
instance GCompare (Type.Field S') where
gcompare = undefined
-- | Scalars
example20 :: Backend b => SMT b (CheckSatResult,CheckSatResult)
example20 = do
registerDatatype S'
x <- declareVarNamed (dt S') "x"
y <- declareVarNamed (dt S') "y"
z <- declareVarNamed (dt S') "z"
u <- declareVarNamed (dt S') "u"
assert $ distinct [x,y,z]
r1 <- checkSat
assert $ distinct [x,y,z,u]
r2 <- checkSat
return (r1,r2)
data Lst (par :: [Type]) e where
Nil' :: Repr t -> Lst '[t] e
Cons' :: e t -> e (DataType Lst '[t]) -> Lst '[t] e
instance Type.IsDatatype Lst where
type Parameters Lst = 'S 'Z
type Signature Lst = '[ '[], '[ParameterType 'Z,DataType Lst '[ParameterType 'Z] ] ]
data Datatype Lst = Lst deriving (Eq,Ord)
data Constr Lst sig where
MkNil :: Type.Constr Lst '[]
MkCons :: Type.Constr Lst '[ParameterType 'Z,DataType Lst '[ParameterType 'Z] ]
data Field Lst tp where
Hd :: Type.Field Lst (ParameterType 'Z)
Tl :: Type.Field Lst (DataType Lst '[ParameterType 'Z])
datatypeGet (Nil' tp) = (Lst,tp ::: Nil)
datatypeGet (Cons' e _) = (Lst,getType e ::: Nil)
parameters _ = Succ Zero
datatypeName _ = "Lst"
constructors _ = MkNil ::: MkCons ::: Nil
constrName MkNil = "nil"
constrName MkCons = "cons"
test (Nil' _) MkNil = True
test (Cons' _ _) MkCons = True
test _ _ = False
fields MkNil = Nil
fields MkCons = Hd ::: Tl ::: Nil
construct (tp ::: Nil) MkNil Nil = Nil' tp
construct (tp ::: Nil) MkCons (hd ::: tl ::: Nil) = Cons' hd tl
deconstruct (Nil' tp) = Type.ConApp (tp ::: Nil) MkNil Nil
deconstruct (Cons' x xs) = Type.ConApp (getType x ::: Nil) MkCons
(x ::: xs ::: Nil)
fieldName Hd = "hd"
fieldName Tl = "tl"
fieldType Hd = ParameterRepr Zero
fieldType Tl = DataRepr Lst (ParameterRepr Zero ::: Nil)
fieldGet (Cons' hd _) Hd = hd
fieldGet (Cons' _ tl) Tl = tl
instance GEq (Type.Constr Lst) where
geq MkNil MkNil = Just Refl
geq MkCons MkCons = Just Refl
geq _ _ = Nothing
instance GCompare (Type.Constr Lst) where
gcompare MkNil MkNil = GEQ
gcompare MkNil _ = GLT
gcompare _ MkNil = GGT
gcompare MkCons MkCons = GEQ
instance GEq (Type.Field Lst) where
geq Hd Hd = Just Refl
geq Tl Tl = Just Refl
geq _ _ = Nothing
instance GCompare (Type.Field Lst) where
gcompare Hd Hd = GEQ
gcompare Hd _ = GLT
gcompare _ Hd = GGT
gcompare Tl Tl = GEQ
-- | Recursive datatypes
example21 :: Backend b => SMT b (CheckSatResult,CheckSatResult)
example21 = do
registerDatatype Lst
l1 <- declareVarNamed (dt' Lst (int ::: Nil)) "l1"
l2 <- declareVarNamed (dt' Lst (int ::: Nil)) "l2"
l3 <- declareVarNamed (dt' Lst (int ::: Nil)) "l3"
x <- declareVarNamed int "x"
assert $ not' $ l1 .==. cdt (Nil' int)
assert $ not' $ l2 .==. cdt (Nil' int)
assert $ (l1 .#. Hd) .==. (l2 .#. Hd)
assert $ not' $ l1 .==. l2
assert $ l3 .==. (mk Lst (int ::: Nil) MkCons (x ::: l2 ::: Nil))
assert $ x .>. cint 100
r1 <- checkSat
getModel
assert $ (l1 .#. Tl) .==. (l2 .#. Tl)
r2 <- checkSat
return (r1,r2)
data Tree par e where
Leaf :: Repr t -> Tree '[t] e
Node :: e t -> e (DataType TreeList '[t]) -> Tree '[t] e
data TreeList par e where
TLNil :: Repr t -> TreeList '[t] e
TLCons :: e (DataType Tree '[t]) -> e (DataType TreeList '[t])
-> TreeList '[t] e
instance Type.IsDatatype Tree where
type Parameters Tree = 'S 'Z
type Signature Tree = '[ '[], '[ParameterType 'Z,DataType TreeList '[ParameterType 'Z]] ]
data Datatype Tree = Tree deriving (Eq,Ord)
data Constr Tree sig where
MkLeaf :: Type.Constr Tree '[]
MkNode :: Type.Constr Tree '[ParameterType 'Z,DataType TreeList '[ParameterType 'Z]]
data Field Tree tp where
TValue :: Type.Field Tree (ParameterType 'Z)
TChildren :: Type.Field Tree (DataType TreeList '[ParameterType 'Z])
datatypeGet (Leaf tp) = (Tree,tp ::: Nil)
datatypeGet (Node v _) = (Tree,getType v:::Nil)
parameters _ = Succ Zero
datatypeName _ = "Tree"
constructors _ = MkLeaf ::: MkNode ::: Nil
constrName MkLeaf = "leaf"
constrName MkNode = "node"
test (Leaf _) MkLeaf = True
test (Node _ _) MkNode = True
test _ _ = False
fields MkLeaf = Nil
fields MkNode = TValue ::: TChildren ::: Nil
construct (tp ::: Nil) MkLeaf Nil = Leaf tp
construct (tp ::: Nil) MkNode (v ::: ch ::: Nil) = Node v ch
deconstruct (Leaf tp) = Type.ConApp (tp ::: Nil) MkLeaf Nil
deconstruct (Node x xs) = Type.ConApp (getType x ::: Nil) MkNode (x:::xs:::Nil)
fieldName TValue = "value"
fieldName TChildren = "children"
fieldType TValue = ParameterRepr Zero
fieldType TChildren = DataRepr TreeList (ParameterRepr Zero ::: Nil)
fieldGet (Node x _) TValue = x
fieldGet (Node _ xs) TChildren = xs
instance Type.IsDatatype TreeList where
type Parameters TreeList = 'S 'Z
type Signature TreeList = '[ '[], '[ DataType Tree '[ParameterType 'Z]
, DataType TreeList '[ParameterType 'Z]] ]
data Datatype TreeList = TreeList deriving (Eq,Ord)
data Constr TreeList sig where
MkTLNil :: Type.Constr TreeList '[]
MkTLCons :: Type.Constr TreeList '[ DataType Tree '[ParameterType 'Z]
, DataType TreeList '[ParameterType 'Z]]
data Field TreeList sig where
Car :: Type.Field TreeList (DataType Tree '[ParameterType 'Z])
Cdr :: Type.Field TreeList (DataType TreeList '[ParameterType 'Z])
datatypeGet (TLNil tp) = (TreeList,tp:::Nil)
datatypeGet (TLCons x _) = case getType x of
DataRepr _ (tp:::Nil) -> (TreeList,tp:::Nil)
parameters _ = Succ Zero
datatypeName _ = "TreeList"
constructors _ = MkTLNil ::: MkTLCons ::: Nil
constrName MkTLNil = "nil"
constrName MkTLCons = "cons"
test (TLNil _) MkTLNil = True
test (TLCons _ _) MkTLCons = True
test _ _ = False
fields MkTLNil = Nil
fields MkTLCons = Car ::: Cdr ::: Nil
construct (tp ::: Nil) MkTLNil Nil = TLNil tp
construct (tp ::: Nil) MkTLCons (x:::xs:::Nil) = TLCons x xs
deconstruct (TLNil tp) = Type.ConApp (tp:::Nil) MkTLNil Nil
deconstruct (TLCons x xs) = case getType x of
DataRepr _ (tp:::Nil) -> Type.ConApp (tp:::Nil) MkTLCons (x:::xs:::Nil)
fieldName Car = "car"
fieldName Cdr = "cdr"
fieldType Car = DataRepr Tree (ParameterRepr Zero:::Nil)
fieldType Cdr = DataRepr TreeList (ParameterRepr Zero:::Nil)
fieldGet (TLCons x _) Car = x
fieldGet (TLCons _ xs) Cdr = xs
instance GEq (Type.Constr Tree) where
geq MkLeaf MkLeaf = Just Refl
geq MkNode MkNode = Just Refl
geq _ _ = Nothing
instance GEq (Type.Constr TreeList) where
geq MkTLNil MkTLNil = Just Refl
geq MkTLCons MkTLCons = Just Refl
geq _ _ = Nothing
instance GCompare (Type.Constr Tree) where
gcompare MkLeaf MkLeaf = GEQ
gcompare MkLeaf _ = GLT
gcompare _ MkLeaf = GGT
gcompare MkNode MkNode = GEQ
instance GCompare (Type.Constr TreeList) where
gcompare MkTLNil MkTLNil = GEQ
gcompare MkTLNil _ = GLT
gcompare _ MkTLNil = GGT
gcompare MkTLCons MkTLCons = GEQ
instance GEq (Type.Field Tree) where
geq TValue TValue = Just Refl
geq TChildren TChildren = Just Refl
geq _ _ = Nothing
instance GEq (Type.Field TreeList) where
geq Car Car = Just Refl
geq Cdr Cdr = Just Refl
geq _ _ = Nothing
instance GCompare (Type.Field Tree) where
gcompare TValue TValue = GEQ
gcompare TValue _ = GLT
gcompare _ TValue = GGT
gcompare TChildren TChildren = GEQ
instance GCompare (Type.Field TreeList) where
gcompare Car Car = GEQ
gcompare Car _ = GLT
gcompare _ Car = GGT
gcompare Cdr Cdr = GEQ
-- | Mutually recursive datatypes
example22 :: Backend b => SMT b (CheckSatResult)
example22 = do
registerDatatype Tree
t1 <- declareVarNamed (dt' Tree (int:::Nil)) "t1"
t2 <- declareVarNamed (dt' Tree (bool:::Nil)) "t2"
assert $ not' $ t1 .==. cdt (Leaf int)
assert $ (t1 .#. TValue) .>. cint 20
assert $ not' $ is t2 MkLeaf
assert $ not' $ t2 .#. TValue
r <- checkSat
getModel
return r
| hguenther/smtlib2 | examples/Z3Tutorial.hs | gpl-3.0 | 20,220 | 0 | 27 | 5,062 | 9,026 | 4,465 | 4,561 | 532 | 3 |
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE LambdaCase #-}
module Wiretap.Analysis.Lock
( locksetSimulation
, lockset
, lockMap
, nonreentrant
, lockOf
, LockMap
, sharedLocks
)
where
import Wiretap.Data.Event
import Wiretap.Data.History
-- import Wiretap.Utils
-- import Wiretap.Graph
-- import Debug.Trace
import qualified Data.List as L
import qualified Data.Map.Strict as M
import Data.Maybe
import Data.Unique
-- import qualified Data.Set as S
-- import Debug.Trace
-- import Control.Lens (over, _1)
-- import Control.Monad
import Control.Monad.State.Strict
-- import Control.Monad.Trans.Either
-- import Debug.Trace
type LockMap = UniqueMap (M.Map Ref UE)
-- | Lockset simulation, walks over a history and calculates the lockset
-- | of each event. The function produces a tuple of an assignment a lockset
-- | to every event, and the hold lockset of every thread.
-- | Notice this function only works if locks are local, and if there no re-entrant
-- | lock.
locksetSimulation :: PartialHistory h
=> M.Map Thread [(Ref, UE)]
-> h
-> (LockMap, M.Map Thread [(Ref, UE)])
locksetSimulation !s history =
(fromUniques $ map (fmap toLockMap) lockstacks, state')
where
(lockstacks, !state') = runState (simulateM step history) s
filterFirst p = L.deleteBy (const p) undefined
step u@(Unique _ e) =
case operation e of
Acquire l ->
updateAndGet t ((l,u):)
Release l ->
updateAndGet t . filterFirst $ (l ==) . fst
_ ->
gets $ fromMaybe [] . M.lookup t
where t = thread e
updateAndGet
:: Thread
-> ([(Ref, UE)] -> [(Ref, UE)])
-> State (M.Map Thread [(Ref, UE)]) [(Ref,UE)]
updateAndGet t f = do
m <- get
let l = fromMaybe [] $ M.lookup t m
let rs = f l
put $! M.insert t rs m
return l
-- | toLockMap converges the lock stack to a map where all locks reference
-- | points to the first event to grab it.
toLockMap :: [(Ref, UE)] -> M.Map Ref UE
toLockMap =
M.fromList
sharedLocks :: LockMap -> UE -> UE -> M.Map Ref (UE, UE)
sharedLocks u a b =
M.intersectionWith (,) (u ! a) (u ! b)
lockMap
:: PartialHistory h
=> h
-> LockMap
lockMap =
fst . locksetSimulation M.empty
lockset :: PartialHistory h
=> h
-> [(Event, (M.Map Ref UE))]
lockset h =
map (\e -> (normal e, locks ! e)) $ enumerate h
where locks = lockMap h
-- A non reentrant lock has does not have it's own lock in
-- the its own lockset.
nonreentrant :: LockMap -> UE -> Ref -> Bool
nonreentrant lm e l =
M.notMember l (lm ! e)
lockOf :: UE -> Maybe Ref
lockOf (Unique _ e) =
case operation e of
Acquire l -> Just l
Request l -> Just l
Release l -> Just l
_ -> Nothing
| ucla-pls/wiretap-tools | src/Wiretap/Analysis/Lock.hs | gpl-3.0 | 2,958 | 0 | 14 | 856 | 848 | 456 | 392 | 74 | 4 |
{-# LANGUAGE UnicodeSyntax #-}
-- $ ghc -o 示例 Haskell示例.hs
-- $ ./示例
-- $ ghci --version
-- The Glorious Glasgow Haskell Compilation System, version 8.2.1
-- | 折叠
-- 同理可以有左折叠和从 1 开始的折叠
-- 只是没写,道理都一样
右折叠 :: Foldable 可折叠 => (甲 -> 乙 -> 乙) -> 乙 -> 可折叠 甲 -> 乙
右折叠 = foldr
-- | 乘法
乘 :: Num 数值 => 数值 -> 数值 -> 数值
乘 = (*)
-- | 阶乘
阶乘 :: Int -> Int
阶乘 数 = 右折叠 乘 1 [ 1 .. 数 ]
main :: IO ()
main = do
let 输出 = print
in 输出 $ 阶乘 5
--
-- 可以开个编译器扩展
-- 符号就可以用全角的完整符号
-- 比如
-- a -> a
-- 扩展后就可以是
-- a → a
-- 不知道对中文有没有帮助
-- 我觉得应该可以
| program-in-chinese/overview | 示例代码/Haskell示例.hs | gpl-3.0 | 794 | 34 | 7 | 148 | 124 | 84 | 40 | -1 | -1 |
{-# LANGUAGE ForeignFunctionInterface #-}
module ChibiOSWrap where
import Foreign.Ptr
import Foreign.C.String
import Data.Word
newtype {-# CTYPE "ioportid_t" #-} IoportidT = IoportidT Word32
type SystimeT = Word32
foreign import primitive "const.GPIOD" c_GPIOD :: IoportidT
foreign import primitive "const.GPIOD_LED3" c_GPIOD_LED3 :: Int
foreign import capi "c_extern.h palSetPad" c_palSetPad :: IoportidT -> Int -> IO ()
foreign import capi "c_extern.h palClearPad" c_palClearPad :: IoportidT -> Int -> IO ()
foreign import capi "c_extern.h chThdSleepMilliseconds" c_chThdSleepMilliseconds :: SystimeT -> IO ()
foreign import capi "c_extern.h chRegSetThreadName" c_chRegSetThreadName :: CString -> IO ()
| metasepi/chibios-arafura | demos/ARMCM4-STM32F407-DISCOVERY_hs/hs_src/ChibiOSWrap.hs | gpl-3.0 | 708 | 2 | 9 | 91 | 144 | 82 | 62 | -1 | -1 |
{-----------------------------------------------------------------
(c) 2008-2009 Markus Dittrich
This program is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public
License Version 3 as published by the Free Software Foundation.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License Version 3 for more details.
You should have received a copy of the GNU General Public
License along with this program; if not, write to the Free
Software Foundation, Inc., 59 Temple Place - Suite 330,
Boston, MA 02111-1307, USA.
--------------------------------------------------------------------}
-- | routines called from the toplevel readline instance without
-- before any parsing is done, aka info routines of any sort and
-- shape
module InfoRoutines ( confirm_and_exit
, list_functions
, list_variables
, show_time
) where
-- imports
import Data.List
import Data.Map
import Data.Time
import Prelude
import System.IO
import System.Locale
-- local imports
import CalculatorState
-- | list all currently defined variables
list_variables :: CalcState -> IO ()
list_variables (CalcState {varMap = theMap}) =
mapM_ print_variable (assocs theMap)
where
print_variable (x,y) = putStrLn (x ++ " == " ++ (show y))
-- | list all currently defined functions
list_functions :: CalcState -> IO ()
list_functions (CalcState {funcMap = theMap} ) =
mapM_ print_function (assocs theMap)
where
print_function ( x
, (Function { f_vars = vars
, f_expression = expr }
)
) =
putStrLn (x ++ "(" ++ intercalate [','] vars ++ ") = " ++ expr)
-- | display the current localtime
show_time :: IO ()
show_time = getCurrentTime
>>= \utcTime -> getTimeZone utcTime
>>= \zone ->
let
localTime = utcToLocalTime zone utcTime
timeString = formatTime defaultTimeLocale
"%a %b %d %Y <> %T %Z " localTime
in
putStrLn timeString
-- | ask user for confirmation before exiting
confirm_and_exit :: IO Bool
confirm_and_exit = putStr "Really quit (y/n)? "
>> hFlush stdout
>> getLine
>>= \answer -> case answer of
"y" -> return True
"n" -> return False
_ -> confirm_and_exit
| markusle/husky | src/InfoRoutines.hs | gpl-3.0 | 2,823 | 0 | 13 | 938 | 380 | 205 | 175 | 40 | 3 |
{-
Author: Ka Wai Cheng
Maintainer: Ka Wai Cheng
Email: <mail.kawai.cheng@gmail.com>
License: GPL 3.0
File: ProofChecker.hs
Description: checks given proof tree is correct and shows unsatisfiability
-}
module ProofChecker where
import Proof
import Signature
import ProofUtils
import Data.List
{-
Called by other modules to check a proof tree
Checks initial set of concepts and gamma before checking the proof
-}
checkProof :: ProofTree -> [Concept] -> (String, Bool)
checkProof prooftree gamma
| length (nub cs) /= length cs =
("Initial concepts must not contain duplicate concepts", False)
| length (nub gamma) /= glength =
("Gamma must not contain duplicate concepts", False)
| not $ all isNNF cs =
("Initial concepts are not in negation normal form", False)
| not $ all isNNF gamma =
("Concepts in gamma are not in negation normal form", False)
| length (gamma `intersect` cs) /= glength =
("Concepts in gamma are not in the initial set of concepts", False)
| otherwise =
checkTree prooftree gamma
where cs = getConcepts prooftree
glength = length gamma
{-
Checks a proof tree shows unsatisfiability and returns true if so
Else returns messages of incorrect steps at point in proof tree & false
Pre: Gamma and initial set of concepts do not contain duplicates
-}
checkTree :: ProofTree -> [Concept] -> (String, Bool)
checkTree (NodeZero step) gamma
| not success =
(msg, False)
| cs /= [] =
("Proof tree is not complete, applying the " ++ rule ++ " rule to {" ++
showConceptList initialconcepts ++ "} produces {" ++ showResults cs ++
"}", False)
| otherwise =
("", True)
where (msg, success, cs) = checkProofStep step gamma
(initialconcepts, rule, _) = step
checkTree (NodeOne step tree) gamma
| not $ rule `elem` ["and", "exists"] =
("Applying the " ++ rule ++ " rule to {" ++ showConceptList initialconcepts
++ "} should not give 1 resulting set of concepts", False)
| not success =
(msg, False)
| length cs /= 1 =
("There should be 1 resulting set of concepts for applying the " ++ rule
++ " rule to {" ++ showConceptList initialconcepts ++ "}", False)
| conceptEquals (head cs) (getConcepts tree) =
checkTree tree gamma
| otherwise =
("Next step's concepts {" ++ showConceptList (getConcepts tree) ++
"} do not match the result of applying " ++ rule ++ " rule to {" ++
showConceptList initialconcepts ++ "}", False)
where (msg, success, cs) = checkProofStep step gamma
(initialconcepts, rule, _) = step
checkTree (NodeTwo step t1 t2) gamma
| rule /= "or" =
("Applying the " ++ rule ++ " rule to {" ++ showConceptList initialconcepts ++
"} should not give 2 resulting sets of concepts", False)
| not success =
(msg, False)
| length cs /= 2 =
("There should be 2 resulting sets of concepts for applying the or rule to {"
++ showConceptList initialconcepts ++ "}",
False)
| conceptEquals (head cs) (getConcepts t1) &&
conceptEquals (cs !! 1) (getConcepts t2) ||
conceptEquals (cs !! 1) (getConcepts t1) &&
conceptEquals (head cs) (getConcepts t2) =
(msg1 ++ msg2, tsuccess1 && tsuccess2)
| otherwise =
("Next step's set of concepts {" ++ showConceptList (getConcepts t1)
++ "} and {" ++ showConceptList (getConcepts t2) ++
"} do not match the results of applying the or rule to {" ++
showConceptList initialconcepts ++ "}", False)
where (msg, success, cs) = checkProofStep step gamma
(msg1, tsuccess1) = checkTree t1 gamma
(msg2, tsuccess2) = checkTree t2 gamma
(initialconcepts, rule, _) = step
{-
Returns a string of sets of concepts
WARNING: only accepts a maximum of 2 results
-}
showResults :: [[Concept]] -> String
showResults [] = "Empty"
showResults [cs] = showConceptList cs
showResults [c1,c2] = showConceptList c1 ++ "} and {" ++ showConceptList c2
showResults _ = "There should not be more than 2 results"
{-
Checks a single proof step, returns true and resulting concepts if correct
Else returns error message, false and given list of concepts of the step
Pre: set of concept in proofstep and gamma contain no duplicates
Post: lists of concepts returned contain no duplicates
-}
checkProofStep :: ProofStep -> [Concept] -> (String, Bool, [[Concept]])
checkProofStep (cs, "bottom", Atom a) _
| Atom a `elem` cs && Neg (Atom a) `elem` cs =
("", True, [])
| otherwise =
(showConcept (Atom a) ++ " and " ++ showConcept (Neg (Atom a)) ++
" do not both exist in the set of concepts {" ++ showConceptList cs ++
"}", False, [cs])
checkProofStep (cs, rule, c) gamma
| c `elem` cs =
checkRule (cs, rule, c) gamma
| otherwise =
(showConcept c ++ " does not exist in the set of concepts {" ++
showConceptList cs ++ "}", False, [cs])
{-
Checks the proof rule can be applied, returns true and resulting concepts if correct
Else returns error message, false and given list of concepts of the step
Pre: ProofStep concept exists
-}
checkRule :: ProofStep -> [Concept] -> (String, Bool, [[Concept]])
checkRule (cs, "", Neg T) _ = ("", True, [])
checkRule (cs, "", _) _ =
("This proof tree does not show unsatisfiability", False, [cs])
checkRule (cs, "and", And l r) _ = ("", True, [nub $ delete (And l r) (l:r:cs)])
checkRule (cs, "or", Or l r) _ = ("", True, [nub (l:result), nub (r:result)])
where result = delete (Or l r) cs
checkRule (cs, "exists", Exists r c) gamma = ("", True, [nub $ c:fsuccs ++ gamma])
where fsuccs = [successor | Forall relation successor <- cs, relation == r]
checkRule (cs, rule, c) _ =
(rule ++ " rule cannot be applied to " ++ showConcept c ++ "", False, [cs])
| j5b/ps-pc | ProofChecker.hs | gpl-3.0 | 5,960 | 0 | 15 | 1,501 | 1,652 | 873 | 779 | 104 | 1 |
module EnvTests (runTests) where
import Data.Maybe
import Data.Set (Set)
import qualified Data.Set as Set
import Data.Map (Map)
import qualified Data.Map as Map
import Syntax
import Env
import Test.HUnit
-- printing tests
testEnv1 = initEnv [Static "a", Static "b", Static "c"]
envTest1 = TestCase $ assertEqual "envEqualize1"
"Just Env{a=b,b=b,c=c}" (show (equalizeNames (Static "a") (Static "b") testEnv1))
envTest2 = TestCase $ assertEqual "envEqualize2"
"Just Env{a=a,b=b,c=c}" (show (equalizeNames (Static "a") (Static "a") testEnv1))
envTest3 = TestCase $ assertEqual "envDistinguish1"
"Just Env{a=a,b=b,c=c,a<>b}" (show (distinguishNames (Static "a") (Static "b") testEnv1))
testEnv2 = fromJust $ equalizeNames (Static "a") (Static "b") testEnv1
envTest4 = TestCase $ assertEqual "envDistinguish2"
"Nothing" (show (distinguishNames (Static "a") (Static "b") testEnv2))
envTests = TestList [TestLabel "envTest1" envTest1
, TestLabel "envTest2" envTest2
, TestLabel "envTest3" envTest3
, TestLabel "envTest4" envTest4
]
runTests = runTestTT envTests
| fredokun/piexplorer | src/EnvTests.hs | gpl-3.0 | 1,197 | 0 | 12 | 274 | 340 | 180 | 160 | 24 | 1 |
module OSRIC.DM where
import EasyIRCBot
import OSRIC.State
setDM :: String -> IRC OSRICState Message
setDM n = do
s <- get
let cs = concrete $ customState s
put $ s { customState = cs { dm = n } }
return $ privmsg $ "Set DM to " ++ n ++"."
tellDM :: IRC OSRICState Message
tellDM = gets (dm.customState) >>= \d -> return $ privmsg $ "The DM is: "++d++"."
| kaashif/hs-irc-osric | lib/OSRIC/DM.hs | agpl-3.0 | 365 | 0 | 11 | 82 | 149 | 77 | 72 | 11 | 1 |
-- brittany { lconfig_columnAlignMode: { tag: ColumnAlignModeDisabled }, lconfig_indentPolicy: IndentPolicyLeft }
func :: (((((((((())))))))))
-- current output is.. funny. wonder if that can/needs to be improved..
| lspitzner/brittany | data/Test364.hs | agpl-3.0 | 215 | 0 | 14 | 26 | 37 | 24 | 13 | 1 | 0 |
module Codewars.Kata.Unique where
import Data.List
findUniqueNumber :: [Int] -> Int
findUniqueNumber [a] = a
findUniqueNumber (a : (b : c))
| a /= b = a
| otherwise = findUniqueNumber c
--
-- | All numbers in the unsorted list are present twice,
-- except the one you have to find.
findUnique :: [Int] -> Int
findUnique = findUniqueNumber . sort
--
| ice1000/OI-codes | codewars/101-200/find-the-unique-number.hs | agpl-3.0 | 361 | 0 | 9 | 74 | 104 | 58 | 46 | 9 | 1 |
--Data type way of creating a Person
{-data Person = Person String String Int Float String String deriving (Show)
firstName :: Person -> String
firstName (Person firstname _ _ _ _ _) = firstname
lastName :: Person -> String
lastName (Person _ lastname _ _ _ _) = lastname
age :: Person -> Int
age (Person _ _ age _ _ _) = age
height :: Person -> Float
height (Person _ _ _ height _ _) = height
phoneNumber :: Person -> String
phoneNumber (Person _ _ _ _ number _) = number
flavor :: Person -> String
flavor (Person _ _ _ _ _ flavor) = flavor -}
--Record way
{-data Person = Person { firstName :: String
, lastName :: String
, age :: Int
, height :: Float
, phoneNumber :: String
, flavor :: String } deriving (Show) -}
data Person = Person
{
firstName :: String
, lastName :: String
, age :: Int
} deriving (Eq, Show, Read)
mikeD = Person "Michael" "Diamond" 43
adRock = Person "Adam" "horovitz" 41
mca = Person "Adam" "Yauch" 44
mysteryDude = "Person { firstName =\"Michael\"" ++
", lastName =\"Diamond\"" ++
", age = 43}"
| alexliew/learn_you_a_haskell | code/person.hs | unlicense | 1,157 | 0 | 8 | 331 | 96 | 54 | 42 | 11 | 1 |
{-# LANGUAGE QuasiQuotes #-}
module JavaLight.UseJll where
import JavaLight.JavaletteLight
import Prelude hiding (exp)
{- This Javalette Light program is parsed at compile time,
and replaced by it's abstract syntax representation.
The 'holes' in square brackets are anti-quoted Haskell
expression.
The QuasiQuoter prog is generated from the grammar in JavaletteLight.hs
(it corresponds to the category Prog).
-}
printing' :: Expr -> Prog
printing' e = [prog|
int main ( ) {
print ( $e ) ;
}
|]
printing :: Expr -> Prog
printing e = Fun TInt (Ident "main") [SFunApp (Ident "print") [e]]
print10 :: Prog
print10 = printing' [expr| 5 + 5 |]
main :: IO ()
main = print print10
| haroldcarr/learn-haskell-coq-ml-etc | haskell/topic/parsing/bnfc-meta-examples/src/JavaLight/UseJll.hs | unlicense | 733 | 0 | 9 | 172 | 125 | 72 | 53 | 12 | 1 |
{-# OPTIONS -fglasgow-exts #-}
-----------------------------------------------------------------------------
{-| Module : QNetworkInterface.hs
Copyright : (c) David Harley 2010
Project : qtHaskell
Version : 1.1.4
Modified : 2010-09-02 17:02:36
Warning : this file is machine generated - do not modify.
--}
-----------------------------------------------------------------------------
module Qtc.Enums.Network.QNetworkInterface (
InterfaceFlag, InterfaceFlags, eIsUp, fIsUp, eIsRunning, fIsRunning, eCanBroadcast, fCanBroadcast, eIsLoopBack, fIsLoopBack, eIsPointToPoint, fIsPointToPoint, eCanMulticast, fCanMulticast
)
where
import Foreign.C.Types
import Qtc.Classes.Base
import Qtc.ClassTypes.Core (QObject, TQObject, qObjectFromPtr)
import Qtc.Core.Base (Qcs, connectSlot, qtc_connectSlot_int, wrapSlotHandler_int)
import Qtc.Enums.Base
import Qtc.Enums.Classes.Core
data CInterfaceFlag a = CInterfaceFlag a
type InterfaceFlag = QEnum(CInterfaceFlag Int)
ieInterfaceFlag :: Int -> InterfaceFlag
ieInterfaceFlag x = QEnum (CInterfaceFlag x)
instance QEnumC (CInterfaceFlag Int) where
qEnum_toInt (QEnum (CInterfaceFlag x)) = x
qEnum_fromInt x = QEnum (CInterfaceFlag x)
withQEnumResult x
= do
ti <- x
return $ qEnum_fromInt $ fromIntegral ti
withQEnumListResult x
= do
til <- x
return $ map qEnum_fromInt til
instance Qcs (QObject c -> InterfaceFlag -> IO ()) where
connectSlot _qsig_obj _qsig_nam _qslt_obj _qslt_nam _handler
= do
funptr <- wrapSlotHandler_int slotHandlerWrapper_int
stptr <- newStablePtr (Wrap _handler)
withObjectPtr _qsig_obj $ \cobj_sig ->
withCWString _qsig_nam $ \cstr_sig ->
withObjectPtr _qslt_obj $ \cobj_slt ->
withCWString _qslt_nam $ \cstr_slt ->
qtc_connectSlot_int cobj_sig cstr_sig cobj_slt cstr_slt (toCFunPtr funptr) (castStablePtrToPtr stptr)
return ()
where
slotHandlerWrapper_int :: Ptr fun -> Ptr () -> Ptr (TQObject c) -> CInt -> IO ()
slotHandlerWrapper_int funptr stptr qobjptr cint
= do qobj <- qObjectFromPtr qobjptr
let hint = fromCInt cint
if (objectIsNull qobj)
then do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
else _handler qobj (qEnum_fromInt hint)
return ()
data CInterfaceFlags a = CInterfaceFlags a
type InterfaceFlags = QFlags(CInterfaceFlags Int)
ifInterfaceFlags :: Int -> InterfaceFlags
ifInterfaceFlags x = QFlags (CInterfaceFlags x)
instance QFlagsC (CInterfaceFlags Int) where
qFlags_toInt (QFlags (CInterfaceFlags x)) = x
qFlags_fromInt x = QFlags (CInterfaceFlags x)
withQFlagsResult x
= do
ti <- x
return $ qFlags_fromInt $ fromIntegral ti
withQFlagsListResult x
= do
til <- x
return $ map qFlags_fromInt til
instance Qcs (QObject c -> InterfaceFlags -> IO ()) where
connectSlot _qsig_obj _qsig_nam _qslt_obj _qslt_nam _handler
= do
funptr <- wrapSlotHandler_int slotHandlerWrapper_int
stptr <- newStablePtr (Wrap _handler)
withObjectPtr _qsig_obj $ \cobj_sig ->
withCWString _qsig_nam $ \cstr_sig ->
withObjectPtr _qslt_obj $ \cobj_slt ->
withCWString _qslt_nam $ \cstr_slt ->
qtc_connectSlot_int cobj_sig cstr_sig cobj_slt cstr_slt (toCFunPtr funptr) (castStablePtrToPtr stptr)
return ()
where
slotHandlerWrapper_int :: Ptr fun -> Ptr () -> Ptr (TQObject c) -> CInt -> IO ()
slotHandlerWrapper_int funptr stptr qobjptr cint
= do qobj <- qObjectFromPtr qobjptr
let hint = fromCInt cint
if (objectIsNull qobj)
then do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
else _handler qobj (qFlags_fromInt hint)
return ()
eIsUp :: InterfaceFlag
eIsUp
= ieInterfaceFlag $ 1
eIsRunning :: InterfaceFlag
eIsRunning
= ieInterfaceFlag $ 2
eCanBroadcast :: InterfaceFlag
eCanBroadcast
= ieInterfaceFlag $ 4
eIsLoopBack :: InterfaceFlag
eIsLoopBack
= ieInterfaceFlag $ 8
eIsPointToPoint :: InterfaceFlag
eIsPointToPoint
= ieInterfaceFlag $ 16
eCanMulticast :: InterfaceFlag
eCanMulticast
= ieInterfaceFlag $ 32
fIsUp :: InterfaceFlags
fIsUp
= ifInterfaceFlags $ 1
fIsRunning :: InterfaceFlags
fIsRunning
= ifInterfaceFlags $ 2
fCanBroadcast :: InterfaceFlags
fCanBroadcast
= ifInterfaceFlags $ 4
fIsLoopBack :: InterfaceFlags
fIsLoopBack
= ifInterfaceFlags $ 8
fIsPointToPoint :: InterfaceFlags
fIsPointToPoint
= ifInterfaceFlags $ 16
fCanMulticast :: InterfaceFlags
fCanMulticast
= ifInterfaceFlags $ 32
| keera-studios/hsQt | Qtc/Enums/Network/QNetworkInterface.hs | bsd-2-clause | 4,834 | 0 | 18 | 1,027 | 1,250 | 634 | 616 | 119 | 1 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeFamilies #-}
module Acid (loadSet, addExperiment) where
import Control.Monad.Reader
import Control.Monad.State
import Data.Acid
import Data.SafeCopy
import Data.Time.LocalTime (ZonedTime(..))
import Data.Typeable
import qualified Data.Map as Map
import Network.ImageTrove.Main
import Network.MyTardis.RestTypes
import qualified Data.Set as Set
import Data.Set (Set)
data ExperimentSet = ExperimentSet !(Set RestExperiment) deriving (Typeable)
$(deriveSafeCopy 0 'base ''RestParameter)
$(deriveSafeCopy 0 'base ''RestSchema)
$(deriveSafeCopy 0 'base ''RestExperimentParameterSet)
$(deriveSafeCopy 0 'base ''RestPermission)
$(deriveSafeCopy 0 'base ''RestGroup)
$(deriveSafeCopy 0 'base ''RestObjectACL)
$(deriveSafeCopy 0 'base ''RestExperiment)
$(deriveSafeCopy 0 'base ''ExperimentSet)
insertExperiment :: RestExperiment -> Update ExperimentSet ()
insertExperiment e = do
ExperimentSet s <- get
put $ ExperimentSet $ Set.insert e s
{-
isMember :: RestExperiment -> Query ExperimentSet Bool
isMember e = do
ExperimentSet s <- get
return True -- $ Set.member e s
Doesn't compile:
Acid.hs:41:24:
No instance for (MonadState ExperimentSet (Query ExperimentSet))
arising from a use of `get'
Possible fix:
add an instance declaration for
(MonadState ExperimentSet (Query ExperimentSet))
In a stmt of a 'do' block: ExperimentSet s <- get
In the expression:
do { ExperimentSet s <- get;
return True }
In an equation for `isMember':
isMember e
= do { ExperimentSet s <- get;
return True }
-}
getSetInternal :: Query ExperimentSet (Set RestExperiment)
getSetInternal = do
ExperimentSet s <- ask
return s
$(makeAcidic ''ExperimentSet ['insertExperiment, 'getSetInternal])
loadSet :: FilePath -> IO (Set RestExperiment)
loadSet fp = do
acid <- openLocalStateFrom fp (ExperimentSet Set.empty)
m <- query acid GetSetInternal
closeAcidState acid
return m
addExperiment :: FilePath -> RestExperiment -> IO ()
addExperiment fp e = do
acid <- openLocalStateFrom fp (ExperimentSet Set.empty)
_ <- update acid (InsertExperiment e)
closeAcidState acid
| carlohamalainen/imagetrove-cai-projects-db | Acid.hs | bsd-2-clause | 2,332 | 0 | 11 | 486 | 508 | 258 | 250 | 46 | 1 |
{-# LANGUAGE CPP, FlexibleContexts, GeneralizedNewtypeDeriving, InstanceSigs,
RankNTypes, ScopedTypeVariables, TypeFamilies, UndecidableInstances #-}
module Text.Grampa.ContextFree.Memoizing
{-# DEPRECATED "Use Text.Grampa.ContextFree.SortedMemoizing instead" #-}
(ResultList(..), Parser(..), BinTree(..),
reparseTails, longest, peg, terminalPEG)
where
import Control.Applicative
import Control.Monad (Monad(..), MonadPlus(..))
#if MIN_VERSION_base(4,13,0)
import Control.Monad (MonadFail(fail))
#endif
import Data.Function (on)
import Data.Foldable (toList)
import Data.Functor.Classes (Show1(..))
import Data.Functor.Compose (Compose(..))
import Data.List (maximumBy)
import Data.Monoid (Monoid(mappend, mempty))
import Data.Monoid.Null (MonoidNull(null))
import Data.Monoid.Factorial (FactorialMonoid, length, splitPrimePrefix)
import Data.Monoid.Textual (TextualMonoid)
import qualified Data.Monoid.Factorial as Factorial
import qualified Data.Monoid.Textual as Textual
import Data.Ord (Down(Down))
import Data.Semigroup (Semigroup((<>)))
import Data.Semigroup.Cancellative (LeftReductive(isPrefixOf))
import Data.String (fromString)
import Debug.Trace (trace)
import Witherable (Filterable(mapMaybe))
import qualified Text.Parser.Char
import Text.Parser.Char (CharParsing)
import Text.Parser.Combinators (Parsing(..))
import Text.Parser.LookAhead (LookAheadParsing(..))
import qualified Rank2
import Text.Grampa.Class (GrammarParsing(..), MultiParsing(..),
DeterministicParsing(..), InputParsing(..), InputCharParsing(..),
TailsParsing(parseTails), ParseResults, ParseFailure(..), FailureDescription(..), Pos)
import Text.Grampa.Internal (BinTree(..), TraceableParsing(..), expected, erroneous)
import qualified Text.Grampa.PEG.Backtrack.Measured as Backtrack
import Prelude hiding (iterate, length, null, showList, span, takeWhile)
-- | Parser for a context-free grammar with packrat-like sharing of parse results. It does not support left-recursive
-- grammars.
newtype Parser g s r = Parser{applyParser :: [(s, g (ResultList g s))] -> ResultList g s r}
data ResultList g s r = ResultList !(BinTree (ResultInfo g s r)) {-# UNPACK #-} !(ParseFailure Pos s)
data ResultInfo g s r = ResultInfo !Int ![(s, g (ResultList g s))] !r
instance (Show s, Show r) => Show (ResultList g s r) where
show (ResultList l f) = "ResultList (" ++ shows l (") (" ++ shows f ")")
instance Show s => Show1 (ResultList g s) where
liftShowsPrec _sp showList _prec (ResultList l f) rest = "ResultList " ++ showList (simplify <$> toList l) (shows f rest)
where simplify (ResultInfo _ _ r) = r
instance (Show s, Show r) => Show (ResultInfo g s r) where
show (ResultInfo l _ r) = "(ResultInfo @" ++ show l ++ " " ++ shows r ")"
instance Functor (ResultInfo g s) where
fmap f (ResultInfo l t r) = ResultInfo l t (f r)
instance Foldable (ResultInfo g s) where
foldMap f (ResultInfo _ _ r) = f r
instance Traversable (ResultInfo g s) where
traverse f (ResultInfo l t r) = ResultInfo l t <$> f r
instance Functor (ResultList g s) where
fmap f (ResultList l failure) = ResultList ((f <$>) <$> l) failure
instance Filterable (ResultList g s) where
mapMaybe f (ResultList l failure) = ResultList (mapMaybe (traverse f) l) failure
instance Ord s => Semigroup (ResultList g s r) where
ResultList rl1 f1 <> ResultList rl2 f2 = ResultList (rl1 <> rl2) (f1 <> f2)
instance Ord s => Monoid (ResultList g s r) where
mempty = ResultList mempty mempty
mappend = (<>)
instance Functor (Parser g i) where
fmap f (Parser p) = Parser (fmap f . p)
{-# INLINABLE fmap #-}
instance Ord s => Applicative (Parser g s) where
pure a = Parser (\rest-> ResultList (Leaf $ ResultInfo 0 rest a) mempty)
Parser p <*> Parser q = Parser r where
r rest = case p rest
of ResultList results failure -> ResultList mempty failure <> foldMap continue results
continue (ResultInfo l rest' f) = continue' l f (q rest')
continue' l f (ResultList rs failure) = ResultList (adjust l f <$> rs) failure
adjust l f (ResultInfo l' rest' a) = ResultInfo (l+l') rest' (f a)
{-# INLINABLE pure #-}
{-# INLINABLE (<*>) #-}
instance Ord s => Alternative (Parser g s) where
empty = Parser (\rest-> ResultList mempty $ ParseFailure (Down $ length rest) [] [])
Parser p <|> Parser q = Parser r where
r rest = p rest <> q rest
{-# INLINABLE (<|>) #-}
instance Filterable (Parser g i) where
mapMaybe f (Parser p) = Parser (mapMaybe f . p)
{-# INLINABLE mapMaybe #-}
instance Ord s => Monad (Parser g s) where
return = pure
Parser p >>= f = Parser q where
q rest = case p rest
of ResultList results failure -> ResultList mempty failure <> foldMap continue results
continue (ResultInfo l rest' a) = continue' l (applyParser (f a) rest')
continue' l (ResultList rs failure) = ResultList (adjust l <$> rs) failure
adjust l (ResultInfo l' rest' a) = ResultInfo (l+l') rest' a
#if MIN_VERSION_base(4,13,0)
instance Ord s => MonadFail (Parser g s) where
#endif
fail msg = Parser p
where p rest = ResultList mempty (erroneous (Down $ length rest) msg)
instance Ord s => MonadPlus (Parser g s) where
mzero = empty
mplus = (<|>)
instance (Semigroup x, Ord s) => Semigroup (Parser g s x) where
(<>) = liftA2 (<>)
instance (Monoid x, Ord s) => Monoid (Parser g s x) where
mempty = pure mempty
mappend = liftA2 mappend
instance (Ord s, LeftReductive s, FactorialMonoid s) => GrammarParsing (Parser g s) where
type ParserGrammar (Parser g s) = g
type GrammarFunctor (Parser g s) = ResultList g s
parsingResult _ = Compose . fromResultList
nonTerminal f = Parser p where
p ((_, d) : _) = f d
p _ = ResultList mempty (expected 0 "NonTerminal at endOfInput")
{-# INLINE nonTerminal #-}
instance (Ord s, LeftReductive s, FactorialMonoid s) => TailsParsing (Parser g s) where
parseTails = applyParser
-- | Memoizing parser guarantees O(n²) performance for grammars with unambiguous productions, but provides no left
-- recursion support.
--
-- @
-- 'parseComplete' :: ("Rank2".'Rank2.Functor' g, 'FactorialMonoid' s) =>
-- g (Memoizing.'Parser' g s) -> s -> g ('Compose' ('ParseResults' s) [])
-- @
instance (LeftReductive s, FactorialMonoid s, Ord s) => MultiParsing (Parser g s) where
type GrammarConstraint (Parser g s) g' = (g ~ g', Rank2.Functor g)
type ResultFunctor (Parser g s) = Compose (ParseResults s) []
-- | Returns the list of all possible input prefix parses paired with the remaining input suffix.
parsePrefix g input = Rank2.fmap (Compose . Compose . fromResultList) (snd $ head $ parseGrammarTails g input)
-- parseComplete :: (Rank2.Functor g, Eq s, FactorialMonoid s) =>
-- g (Parser g s) -> s -> g (Compose (ParseResults s) [])
parseComplete g input = Rank2.fmap ((snd <$>) . Compose . fromResultList)
(snd $ head $ reparseTails close $ parseGrammarTails g input)
where close = Rank2.fmap (<* eof) g
parseGrammarTails :: (Rank2.Functor g, FactorialMonoid s) => g (Parser g s) -> s -> [(s, g (ResultList g s))]
parseGrammarTails g input = foldr parseTail [] (Factorial.tails input)
where parseTail s parsedTail = parsed
where parsed = (s,d):parsedTail
d = Rank2.fmap (($ parsed) . applyParser) g
reparseTails :: Rank2.Functor g => g (Parser g s) -> [(s, g (ResultList g s))] -> [(s, g (ResultList g s))]
reparseTails _ [] = []
reparseTails final parsed@((s, _):_) = (s, gd):parsed
where gd = Rank2.fmap (`applyParser` parsed) final
instance (LeftReductive s, FactorialMonoid s, Ord s) => InputParsing (Parser g s) where
type ParserInput (Parser g s) = s
getInput = Parser p
where p rest@((s, _):_) = ResultList (Leaf $ ResultInfo 0 rest s) mempty
p [] = ResultList (Leaf $ ResultInfo 0 [] mempty) mempty
anyToken = Parser p
where p rest@((s, _):t) = case splitPrimePrefix s
of Just (first, _) -> ResultList (Leaf $ ResultInfo 1 t first) mempty
_ -> ResultList mempty (expected (Down $ length rest) "anyToken")
p [] = ResultList mempty (expected 0 "anyToken")
satisfy predicate = Parser p
where p rest@((s, _):t) =
case splitPrimePrefix s
of Just (first, _) | predicate first -> ResultList (Leaf $ ResultInfo 1 t first) mempty
_ -> ResultList mempty (expected (Down $ length rest) "satisfy")
p [] = ResultList mempty (expected 0 "satisfy")
scan s0 f = Parser (p s0)
where p s rest@((i, _) : _) = ResultList (Leaf $ ResultInfo l (drop l rest) prefix) mempty
where (prefix, _, _) = Factorial.spanMaybe' s f i
l = Factorial.length prefix
p _ [] = ResultList (Leaf $ ResultInfo 0 [] mempty) mempty
take 0 = mempty
take n = Parser p
where p rest@((s, _) : _)
| x <- Factorial.take n s, l <- Factorial.length x, l == n =
ResultList (Leaf $ ResultInfo l (drop l rest) x) mempty
p rest = ResultList mempty (expected (Down $ length rest) $ "take " ++ show n)
takeWhile predicate = Parser p
where p rest@((s, _) : _)
| x <- Factorial.takeWhile predicate s, l <- Factorial.length x =
ResultList (Leaf $ ResultInfo l (drop l rest) x) mempty
p [] = ResultList (Leaf $ ResultInfo 0 [] mempty) mempty
takeWhile1 predicate = Parser p
where p rest@((s, _) : _)
| x <- Factorial.takeWhile predicate s, l <- Factorial.length x, l > 0 =
ResultList (Leaf $ ResultInfo l (drop l rest) x) mempty
p rest = ResultList mempty (expected (Down $ length rest) "takeWhile1")
string s = Parser p where
p rest@((s', _) : _)
| s `isPrefixOf` s' = ResultList (Leaf $ ResultInfo l (Factorial.drop l rest) s) mempty
p rest = ResultList mempty (ParseFailure (Down $ length rest) [LiteralDescription s] [])
l = Factorial.length s
notSatisfy predicate = Parser p
where p rest@((s, _):_)
| Just (first, _) <- splitPrimePrefix s,
predicate first = ResultList mempty (expected (Down $ length rest) "notSatisfy")
p rest = ResultList (Leaf $ ResultInfo 0 rest ()) mempty
{-# INLINABLE string #-}
instance InputParsing (Parser g s) => TraceableParsing (Parser g s) where
traceInput description (Parser p) = Parser q
where q rest@((s, _):_) = case traceWith "Parsing " (p rest)
of rl@(ResultList EmptyTree _) -> traceWith "Failed " rl
rl -> traceWith "Parsed " rl
where traceWith prefix = trace (prefix <> description s)
q [] = p []
instance (Ord s, Show s, TextualMonoid s) => InputCharParsing (Parser g s) where
satisfyCharInput predicate = Parser p
where p rest@((s, _):t) =
case Textual.characterPrefix s
of Just first | predicate first -> ResultList (Leaf $ ResultInfo 1 t $ Factorial.primePrefix s) mempty
_ -> ResultList mempty (expected (Down $ length rest) "satisfyCharInput")
p [] = ResultList mempty (expected 0 "satisfyCharInput")
scanChars s0 f = Parser (p s0)
where p s rest@((i, _) : _) = ResultList (Leaf $ ResultInfo l (drop l rest) prefix) mempty
where (prefix, _, _) = Textual.spanMaybe_' s f i
l = Factorial.length prefix
p _ [] = ResultList (Leaf $ ResultInfo 0 [] mempty) mempty
takeCharsWhile predicate = Parser p
where p rest@((s, _) : _)
| x <- Textual.takeWhile_ False predicate s, l <- Factorial.length x =
ResultList (Leaf $ ResultInfo l (drop l rest) x) mempty
p [] = ResultList (Leaf $ ResultInfo 0 [] mempty) mempty
takeCharsWhile1 predicate = Parser p
where p rest@((s, _) : _)
| x <- Textual.takeWhile_ False predicate s, l <- Factorial.length x, l > 0 =
ResultList (Leaf $ ResultInfo l (drop l rest) x) mempty
p rest = ResultList mempty (expected (Down $ length rest) "takeCharsWhile1")
notSatisfyChar predicate = Parser p
where p rest@((s, _):_)
| Just first <- Textual.characterPrefix s,
predicate first = ResultList mempty (expected (Down $ length rest) "notSatisfyChar")
p rest = ResultList (Leaf $ ResultInfo 0 rest ()) mempty
instance (MonoidNull s, Ord s) => Parsing (Parser g s) where
try (Parser p) = Parser q
where q rest = rewindFailure (p rest)
where rewindFailure (ResultList rl _) = ResultList rl (ParseFailure (Down $ length rest) [] [])
Parser p <?> msg = Parser q
where q rest = replaceFailure (p rest)
where replaceFailure (ResultList EmptyTree (ParseFailure pos msgs erroneous')) =
ResultList EmptyTree (ParseFailure pos
(if pos == Down (length rest) then [StaticDescription msg]
else msgs)
erroneous')
replaceFailure rl = rl
notFollowedBy (Parser p) = Parser (\input-> rewind input (p input))
where rewind t (ResultList EmptyTree _) = ResultList (Leaf $ ResultInfo 0 t ()) mempty
rewind t ResultList{} = ResultList mempty (expected (Down $ length t) "notFollowedBy")
skipMany p = go
where go = pure () <|> p *> go
unexpected msg = Parser (\t-> ResultList mempty $ expected (Down $ length t) msg)
eof = Parser f
where f rest@((s, _):_)
| null s = ResultList (Leaf $ ResultInfo 0 rest ()) mempty
| otherwise = ResultList mempty (expected (Down $ length rest) "endOfInput")
f [] = ResultList (Leaf $ ResultInfo 0 [] ()) mempty
instance (MonoidNull s, Ord s) => DeterministicParsing (Parser g s) where
Parser p <<|> Parser q = Parser r where
r rest = case p rest
of rl@(ResultList EmptyTree _failure) -> rl <> q rest
rl -> rl
takeSome p = (:) <$> p <*> takeMany p
takeMany (Parser p) = Parser (q 0 id) where
q len acc rest = case p rest
of ResultList EmptyTree _failure -> ResultList (Leaf $ ResultInfo len rest (acc [])) mempty
ResultList rl _ -> foldMap continue rl
where continue (ResultInfo len' rest' result) = q (len + len') (acc . (result:)) rest'
skipAll (Parser p) = Parser (q 0) where
q len rest = case p rest
of ResultList EmptyTree _failure -> ResultList (Leaf $ ResultInfo len rest ()) mempty
ResultList rl _failure -> foldMap continue rl
where continue (ResultInfo len' rest' _) = q (len + len') rest'
instance (MonoidNull s, Ord s) => LookAheadParsing (Parser g s) where
lookAhead (Parser p) = Parser (\input-> rewind input (p input))
where rewind t (ResultList rl failure) = ResultList (rewindInput t <$> rl) failure
rewindInput t (ResultInfo _ _ r) = ResultInfo 0 t r
instance (Ord s, Show s, TextualMonoid s) => CharParsing (Parser g s) where
satisfy predicate = Parser p
where p rest@((s, _):t) =
case Textual.characterPrefix s
of Just first | predicate first -> ResultList (Leaf $ ResultInfo 1 t first) mempty
_ -> ResultList mempty (expected (Down $ length rest) "Char.satisfy")
p [] = ResultList mempty (expected 0 "Char.satisfy")
string s = Textual.toString (error "unexpected non-character") <$> string (fromString s)
text t = (fromString . Textual.toString (error "unexpected non-character")) <$> string (Textual.fromText t)
fromResultList :: FactorialMonoid s => ResultList g s r -> ParseResults s [(s, r)]
fromResultList (ResultList EmptyTree (ParseFailure pos positive negative)) =
Left (ParseFailure (pos - 1) positive negative)
fromResultList (ResultList rl _failure) = Right (f <$> toList rl)
where f (ResultInfo _ ((s, _):_) r) = (s, r)
f (ResultInfo _ [] r) = (mempty, r)
-- | Turns a context-free parser into a backtracking PEG parser that consumes the longest possible prefix of the list
-- of input tails, opposite of 'peg'
longest :: Parser g s a -> Backtrack.Parser g [(s, g (ResultList g s))] a
longest p = Backtrack.Parser q where
q rest = case applyParser p rest
of ResultList EmptyTree (ParseFailure pos positive negative)
-> Backtrack.NoParse (ParseFailure pos (map message positive) (map message negative))
ResultList rs _ -> parsed (maximumBy (compare `on` resultLength) rs)
resultLength (ResultInfo l _ _) = l
parsed (ResultInfo l s r) = Backtrack.Parsed l r s
message (StaticDescription msg) = StaticDescription msg
message (LiteralDescription s) = LiteralDescription [(s, error "longest")]
-- | Turns a backtracking PEG parser of the list of input tails into a context-free parser, opposite of 'longest'
peg :: Ord s => Backtrack.Parser g [(s, g (ResultList g s))] a -> Parser g s a
peg p = Parser q where
q rest = case Backtrack.applyParser p rest
of Backtrack.Parsed l result suffix -> ResultList (Leaf $ ResultInfo l suffix result) mempty
Backtrack.NoParse (ParseFailure pos positive negative)
-> ResultList mempty (ParseFailure pos (original <$> positive) (original <$> negative))
where original = (fst . head <$>)
-- | Turns a backtracking PEG parser into a context-free parser
terminalPEG :: (Monoid s, Ord s) => Backtrack.Parser g s a -> Parser g s a
terminalPEG p = Parser q where
q [] = case Backtrack.applyParser p mempty
of Backtrack.Parsed l result _ -> ResultList (Leaf $ ResultInfo l [] result) mempty
Backtrack.NoParse failure -> ResultList mempty failure
q rest@((s, _):_) = case Backtrack.applyParser p s
of Backtrack.Parsed l result _ -> ResultList (Leaf $ ResultInfo l (drop l rest) result) mempty
Backtrack.NoParse failure -> ResultList mempty failure
| blamario/grampa | grammatical-parsers/src/Text/Grampa/ContextFree/Memoizing.hs | bsd-2-clause | 18,417 | 0 | 18 | 4,800 | 6,920 | 3,539 | 3,381 | 293 | 4 |
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
module ApiTypes where
import Control.Applicative (Applicative)
import Control.Concurrent.STM (TVar)
import Control.Monad.Reader (MonadReader, ReaderT (..))
import Control.Monad.Trans (MonadIO)
import Data.HashMap.Strict (HashMap)
import Data.Set (Set)
import Type.Comment (Comment)
import Type.Invoice (Invoice)
import Type.Customer (Customer)
import qualified Type.Invoice as Invoice
data ServerData = ServerData
{ customers :: TVar (Set Customer)
, invoices :: TVar (Set Invoice)
, comments :: TVar (HashMap Invoice.Id (Set Comment))
}
newtype BlogApi a = BlogApi { unBlogApi :: ReaderT ServerData IO a }
deriving ( Applicative
, Functor
, Monad
, MonadIO
, MonadReader ServerData
)
runBlogApi :: ServerData -> BlogApi a -> IO a
runBlogApi serverdata = flip runReaderT serverdata . unBlogApi
| tinkerthaler/basic-invoice-rest | example-api/ApiTypes.hs | bsd-3-clause | 914 | 0 | 13 | 185 | 260 | 150 | 110 | 24 | 1 |
{-|
Module : MixedTypesNumPrelude
Description : Bottom-up typed numeric expressions
Copyright : (c) Michal Konecny, Pieter Collins
License : BSD3
Maintainer : mikkonecny@gmail.com
Stability : experimental
Portability : portable
@MixedTypesNumPrelude@ provides a version of @Prelude@ where
unary and binary operations such as @not@, @+@, @==@
have their result type derived from the parameter type(s).
This module facilitates a single-line import for the package
mixed-types-num. See the re-exported modules for further details.
-}
module MixedTypesNumPrelude
(
-- * Re-exporting Prelude, hiding the operators we are changing
module Numeric.MixedTypes.PreludeHiding,
-- * Error-collecting wrapper type
CN, cn, unCN, clearPotentialErrors,
-- * A part of package ``convertible''
module Data.Convertible.Base,
-- * Modules with Prelude alternatives
module Numeric.MixedTypes.Literals,
module Numeric.MixedTypes.Bool,
module Numeric.MixedTypes.Eq,
module Numeric.MixedTypes.Ord,
module Numeric.MixedTypes.MinMaxAbs,
module Numeric.MixedTypes.AddSub,
module Numeric.MixedTypes.Round,
module Numeric.MixedTypes.Reduce,
module Numeric.MixedTypes.Mul,
module Numeric.MixedTypes.Ring,
module Numeric.MixedTypes.Div,
module Numeric.MixedTypes.Power,
module Numeric.MixedTypes.Field,
module Numeric.MixedTypes.Elementary,
module Numeric.MixedTypes.Complex,
-- module Numeric.CollectErrors,
module Utils.TH.DeclForTypes,
module Utils.Test.EnforceRange,
-- * Re-export for convenient Rational literals
(%)
)
where
import Data.Ratio ((%))
import Numeric.CollectErrors (CN, cn, unCN, clearPotentialErrors)
import Data.Convertible.Instances.Num()
import Data.Convertible.Base
import Utils.TH.DeclForTypes
import Utils.Test.EnforceRange
import Numeric.MixedTypes.PreludeHiding
import Numeric.MixedTypes.Literals
import Numeric.MixedTypes.Bool
import Numeric.MixedTypes.Eq
import Numeric.MixedTypes.Ord
import Numeric.MixedTypes.MinMaxAbs
import Numeric.MixedTypes.AddSub
import Numeric.MixedTypes.Round
import Numeric.MixedTypes.Reduce
import Numeric.MixedTypes.Mul
import Numeric.MixedTypes.Ring
import Numeric.MixedTypes.Div
import Numeric.MixedTypes.Power
import Numeric.MixedTypes.Field
import Numeric.MixedTypes.Elementary
import Numeric.MixedTypes.Complex
| michalkonecny/mixed-types-num | src/MixedTypesNumPrelude.hs | bsd-3-clause | 2,375 | 0 | 5 | 338 | 318 | 221 | 97 | 45 | 0 |
module Signal.Wavelet.Eval2Bench where
import Signal.Wavelet.Eval2
{-# INLINE benchDwt #-}
benchDwt :: ([Double], [Double]) -> [Double]
benchDwt (ls, sig) = dwt ls sig
{-# INLINE benchIdwt #-}
benchIdwt :: ([Double], [Double]) -> [Double]
benchIdwt (ls, sig) = idwt ls sig
| jstolarek/lattice-structure-hs | bench/Signal/Wavelet/Eval2Bench.hs | bsd-3-clause | 278 | 0 | 7 | 44 | 101 | 61 | 40 | 8 | 1 |
{-# LANGUAGE MultiParamTypeClasses, NoImplicitPrelude, RebindableSyntax #-}
{-# LANGUAGE ScopedTypeVariables, ViewPatterns #-}
module Numeric.Field.Fraction
( Fraction
, numerator
, denominator
, Ratio
, (%)
, lcm
) where
import Data.Proxy
import Numeric.Additive.Class
import Numeric.Additive.Group
import Numeric.Algebra.Class
import Numeric.Algebra.Commutative
import Numeric.Algebra.Division
import Numeric.Algebra.Unital
import Numeric.Decidable.Units
import Numeric.Decidable.Zero
import Numeric.Domain.Euclidean
import Numeric.Natural
import Numeric.Rig.Characteristic
import Numeric.Rig.Class
import Numeric.Ring.Class
import Numeric.Semiring.Integral
import Prelude hiding (Integral (..), Num (..), gcd, lcm)
-- | Fraction field @k(D)@ of 'Euclidean' domain @D@.
data Fraction d = Fraction !d !d
-- Invariants: r == Fraction p q
-- ==> leadingUnit q == one && q /= 0
-- && isUnit (gcd p q)
-- | Convenient synonym for 'Fraction'.
type Ratio = Fraction
lcm :: Euclidean r => r -> r -> r
lcm p q = p * q `quot` gcd p q
instance (Eq d, Show d, Unital d) => Show (Fraction d) where
showsPrec d (Fraction p q)
| q == one = showsPrec d p
| otherwise = showParen (d > 5) $ showsPrec 6 p . showString " / " . showsPrec 6 q
infixl 7 %
(%) :: Euclidean d => d -> d -> Fraction d
a % b = let (ua, a') = splitUnit a
(ub, b') = splitUnit b
Just ub' = recipUnit ub
r = gcd a' b'
in Fraction (ua * ub' * a' `quot` r) (b' `quot` r)
numerator :: Fraction t -> t
numerator (Fraction q _) = q
{-# INLINE numerator #-}
denominator :: Fraction t -> t
denominator (Fraction _ p) = p
{-# INLINE denominator #-}
instance Euclidean d => IntegralSemiring (Fraction d)
instance (Eq d, Multiplicative d) => Eq (Fraction d) where
Fraction p q == Fraction s t = p*t == q*s
{-# INLINE (==) #-}
instance (Ord d, Multiplicative d) => Ord (Fraction d) where
compare (Fraction p q) (Fraction p' q') = compare (p*q') (p'*q)
{-# INLINE compare #-}
instance Euclidean d => Division (Fraction d) where
recip (Fraction p q) | isZero p = error "Ratio has zero denominator!"
| otherwise = let (recipUnit -> Just u, p') = splitUnit p
in Fraction (q * u) p'
Fraction p q / Fraction s t = (p*t) % (q*s)
{-# INLINE recip #-}
{-# INLINE (/) #-}
instance (Commutative d, Euclidean d) => Commutative (Fraction d)
instance Euclidean d => DecidableZero (Fraction d) where
isZero (Fraction p _) = isZero p
{-# INLINE isZero #-}
instance Euclidean d => DecidableUnits (Fraction d) where
isUnit (Fraction p _) = not $ isZero p
{-# INLINE isUnit #-}
recipUnit (Fraction p q) | isZero p = Nothing
| otherwise = Just (Fraction q p)
{-# INLINE recipUnit #-}
instance Euclidean d => Ring (Fraction d)
instance Euclidean d => Abelian (Fraction d)
instance Euclidean d => Semiring (Fraction d)
instance Euclidean d => Group (Fraction d) where
negate (Fraction p q) = Fraction (negate p) q
Fraction p q - Fraction p' q' = (p*q'-p'*q) % (q*q')
instance Euclidean d => Monoidal (Fraction d) where
zero = Fraction zero one
{-# INLINE zero #-}
instance Euclidean d => LeftModule Integer (Fraction d) where
n .* Fraction p r = (n .* p) % r
{-# INLINE (.*) #-}
instance Euclidean d => RightModule Integer (Fraction d) where
Fraction p r *. n = (p *. n) % r
{-# INLINE (*.) #-}
instance Euclidean d => LeftModule Natural (Fraction d) where
n .* Fraction p r = (n .* p) % r
{-# INLINE (.*) #-}
instance Euclidean d => RightModule Natural (Fraction d) where
Fraction p r *. n = (p *. n) % r
{-# INLINE (*.) #-}
instance Euclidean d => Additive (Fraction d) where
Fraction p q + Fraction s t =
let u = gcd q t
in Fraction (p * t `quot` u + s*q`quot`u) (q*t`quot`u)
{-# INLINE (+) #-}
instance Euclidean d => Unital (Fraction d) where
one = Fraction one one
{-# INLINE one #-}
instance Euclidean d => Multiplicative (Fraction d) where
Fraction p q * Fraction s t = (p*s) % (q*t)
instance Euclidean d => Rig (Fraction d)
instance (Characteristic d, Euclidean d) => Characteristic (Fraction d) where
char _ = char (Proxy :: Proxy d)
| athanclark/algebra | src/Numeric/Field/Fraction.hs | bsd-3-clause | 4,275 | 0 | 14 | 1,015 | 1,628 | 830 | 798 | 108 | 1 |
{-# LANGUAGE FlexibleContexts #-}
module Language.Typo.Token
( typoDef -- :: LanguageDef s
, typo -- :: GenTokenParser String u Identity
, lexeme -- :: Parsec String u a -> Parsec String u a
, parens -- :: Parsec String u a -> Parsec String u a
, identifier -- :: Parsec String u String
, operator -- :: Parsec String u String
, natural -- :: Parsec String u Integer
, whiteSpace -- :: Parsec String u ()
) where
import Control.Monad.Identity
import Text.Parsec ( oneOf )
import Text.Parsec.Prim
import Text.Parsec.Language ( emptyDef )
import Text.Parsec.Token ( GenTokenParser, LanguageDef, makeTokenParser )
import qualified Text.Parsec.Token as P
typoDef :: LanguageDef s
typoDef = emptyDef {
P.commentLine = ";",
P.opStart = P.opLetter typoDef,
P.opLetter = oneOf ":!$%&*+./<=>?@\\^|-~",
P.reservedNames = [
"define", "let", "if" -- language keywords
, "and", "or", "imp", "cond" -- (prelude) boolean operators
, "add", "sub", "mul", "div", "rem" -- (prelude) arithmetic operators
, "eq", "lt" -- (prelude) comparison operators
, "result", "res", "undefined" -- program keywords
]
}
typo :: GenTokenParser String u Identity
typo = makeTokenParser typoDef
lexeme, parens :: Parsec String u a -> Parsec String u a
lexeme = P.lexeme typo
parens = P.parens typo
identifier, operator :: Parsec String u String
identifier = P.identifier typo
operator = P.operator typo
natural :: Parsec String u Integer
natural = P.natural typo
whiteSpace :: Parsec String u ()
whiteSpace = P.whiteSpace typo
| seliopou/typo | Language/Typo/Token.hs | bsd-3-clause | 1,630 | 0 | 8 | 372 | 357 | 214 | 143 | 39 | 1 |
{-# LANGUAGE GADTs #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
--
-- Copyright (c) 2009-2011, ERICSSON AB
-- 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 the ERICSSON AB nor the names of its 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 HOLDER 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 Feldspar.Core.Constructs.MutableToPure
( MutableToPure (..)
) where
import qualified Control.Exception as C
import Data.Array.IArray
import Data.Array.MArray (freeze)
import Data.Array.Unsafe (unsafeFreeze)
import System.IO.Unsafe
import Language.Syntactic
import Language.Syntactic.Constructs.Binding
import Language.Syntactic.Constructs.Binding.HigherOrder (CLambda)
import Feldspar.Lattice
import Feldspar.Core.Types
import Feldspar.Core.Interpretation
import Feldspar.Core.Constructs.Binding
data MutableToPure a where
RunMutableArray :: Type a => MutableToPure (Mut (MArr a) :-> Full [a])
WithArray :: Type b => MutableToPure (MArr a :-> ([a] -> Mut b) :-> Full (Mut b))
instance Semantic MutableToPure
where
semantics RunMutableArray = Sem "runMutableArray" runMutableArrayEval
semantics WithArray = Sem "withArray" withArrayEval
runMutableArrayEval :: forall a . Mut (MArr a) -> [a]
runMutableArrayEval m = unsafePerformIO $
do marr <- m
iarr <- unsafeFreeze marr
return (elems (iarr :: Array Integer a))
withArrayEval :: forall a b. MArr a -> ([a] -> Mut b) -> Mut b
withArrayEval ma f
= do a <- f (elems (unsafePerformIO $ freeze ma :: Array Integer a))
C.evaluate a
instance Typed MutableToPure
where
typeDictSym RunMutableArray = Just Dict
typeDictSym _ = Nothing
semanticInstances ''MutableToPure
instance EvalBind MutableToPure where evalBindSym = evalBindSymDefault
instance AlphaEq dom dom dom env => AlphaEq MutableToPure MutableToPure dom env
where
alphaEqSym = alphaEqSymDefault
instance Sharable MutableToPure
instance Cumulative MutableToPure
instance SizeProp MutableToPure
where
sizeProp RunMutableArray (WrapFull arr :* Nil) = infoSize arr
sizeProp WithArray (_ :* WrapFull fun :* Nil) = snd $ infoSize fun
instance ( MutableToPure :<: dom
, Let :<: dom
, (Variable :|| Type) :<: dom
, CLambda Type :<: dom
, OptimizeSuper dom
) =>
Optimize MutableToPure dom
where
optimizeFeat opts sym@WithArray (arr :* fun@(lam :$ body) :* Nil)
| Dict <- exprDict fun
, Dict <- exprDict body
, Just (SubConstr2 (Lambda _)) <- prjLambda lam
= do
arr' <- optimizeM opts arr
let (szl :> sze) = infoSize (getInfo arr')
fun' <- optimizeFunction opts (optimizeM opts) (mkInfo (szl :> sze)) fun
constructFeat opts sym (arr' :* fun' :* Nil)
optimizeFeat opts sym args = optimizeFeatDefault opts sym args
constructFeatUnOpt opts RunMutableArray args = constructFeatUnOptDefaultTyp opts typeRep RunMutableArray args
constructFeatUnOpt opts WithArray args = constructFeatUnOptDefaultTyp opts (MutType typeRep) WithArray args
| emwap/feldspar-language | src/Feldspar/Core/Constructs/MutableToPure.hs | bsd-3-clause | 4,777 | 0 | 14 | 996 | 904 | 479 | 425 | 69 | 1 |
{-
Kubernetes
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
OpenAPI spec version: 2.0
Kubernetes API version: v1.9.12
Generated by Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git)
-}
{-|
Module : Kubernetes.OpenAPI.API.Certificates
-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MonoLocalBinds #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings #-}
{-# OPTIONS_GHC -fno-warn-name-shadowing -fno-warn-unused-binds -fno-warn-unused-imports #-}
module Kubernetes.OpenAPI.API.Certificates where
import Kubernetes.OpenAPI.Core
import Kubernetes.OpenAPI.MimeTypes
import Kubernetes.OpenAPI.Model as M
import qualified Data.Aeson as A
import qualified Data.ByteString as B
import qualified Data.ByteString.Lazy as BL
import qualified Data.Data as P (Typeable, TypeRep, typeOf, typeRep)
import qualified Data.Foldable as P
import qualified Data.Map as Map
import qualified Data.Maybe as P
import qualified Data.Proxy as P (Proxy(..))
import qualified Data.Set as Set
import qualified Data.String as P
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
import qualified Data.Text.Lazy as TL
import qualified Data.Text.Lazy.Encoding as TL
import qualified Data.Time as TI
import qualified Network.HTTP.Client.MultipartFormData as NH
import qualified Network.HTTP.Media as ME
import qualified Network.HTTP.Types as NH
import qualified Web.FormUrlEncoded as WH
import qualified Web.HttpApiData as WH
import Data.Text (Text)
import GHC.Base ((<|>))
import Prelude ((==),(/=),($), (.),(<$>),(<*>),(>>=),Maybe(..),Bool(..),Char,Double,FilePath,Float,Int,Integer,String,fmap,undefined,mempty,maybe,pure,Monad,Applicative,Functor)
import qualified Prelude as P
-- * Operations
-- ** Certificates
-- *** getAPIGroup
-- | @GET \/apis\/certificates.k8s.io\/@
--
-- get information of a group
--
-- AuthMethod: 'AuthApiKeyBearerToken'
--
getAPIGroup
:: Accept accept -- ^ request accept ('MimeType')
-> KubernetesRequest GetAPIGroup MimeNoContent V1APIGroup accept
getAPIGroup _ =
_mkRequest "GET" ["/apis/certificates.k8s.io/"]
`_hasAuthType` (P.Proxy :: P.Proxy AuthApiKeyBearerToken)
data GetAPIGroup
-- | @application/json@
instance Consumes GetAPIGroup MimeJSON
-- | @application/yaml@
instance Consumes GetAPIGroup MimeYaml
-- | @application/vnd.kubernetes.protobuf@
instance Consumes GetAPIGroup MimeVndKubernetesProtobuf
-- | @application/json@
instance Produces GetAPIGroup MimeJSON
-- | @application/yaml@
instance Produces GetAPIGroup MimeYaml
-- | @application/vnd.kubernetes.protobuf@
instance Produces GetAPIGroup MimeVndKubernetesProtobuf
| denibertovic/haskell | kubernetes/lib/Kubernetes/OpenAPI/API/Certificates.hs | bsd-3-clause | 2,742 | 0 | 8 | 331 | 484 | 333 | 151 | -1 | -1 |
module Network.PushbulletSpec (main, spec) where
import Test.Hspec
main :: IO ()
main = hspec spec
spec :: Spec
spec = do
describe "someFunction" $ do
it "should work fine" $ do
True `shouldBe` False
| KevinCotrone/pushbullet | test/Network/PushbulletSpec.hs | bsd-3-clause | 215 | 0 | 13 | 49 | 76 | 40 | 36 | 9 | 1 |
import System.Environment (getArgs)
import Data.List.Split (splitOn)
maxran :: Int -> Int -> [Int] -> [Int] -> Int
maxran x _ _ [] = x
maxran x c (y:ys) (z:zs) = maxran (max x d) d (ys ++ [z]) zs
where d = c - y + z
maxrange :: [String] -> Int
maxrange [ns, xs] = maxran (max 0 z) z zs (drop n ys)
where n = read ns
ys = map read (words xs)
zs = take n ys
z = sum zs
main :: IO ()
main = do
[inpFile] <- getArgs
input <- readFile inpFile
putStr . unlines . map (show . maxrange . splitOn ";") $ lines input
| nikai3d/ce-challenges | easy/max_range_sum.hs | bsd-3-clause | 673 | 0 | 12 | 279 | 300 | 155 | 145 | 17 | 1 |
import System.Environment (getArgs)
r1 :: [Int]
r1 = [1, 0, 0, 0, 1, 1]
r2 :: [Int]
r2 = [1, 0, 1, 0, 1, 1]
bnot :: Int -> Int
bnot 0 = 1
bnot _ = 0
pmod6 :: Int -> Int
pmod6 x | mod x 6 == 0 = 6
| otherwise = mod x 6
locks :: [Int] -> Int
locks [0, _] = 0
locks [x, 0] = x
locks [x, 1] = x-1
locks [x, y] | x > 6 && mod y 2 == 0 = div x 6 * 3 + locks [pmod6 x, y]
| x > 6 = div x 6 * 4 + locks [pmod6 x, y]
| mod y 2 == 0 = sum (init xs) + bnot (last xs)
| otherwise = sum (init ys) + bnot (last ys)
where xs = take x r1
ys = take x r2
main :: IO ()
main = do
[inpFile] <- getArgs
input <- readFile inpFile
putStr . unlines . map (show . locks . map read . words) $ lines input
| nikai3d/ce-challenges | moderate/locks.hs | bsd-3-clause | 816 | 0 | 13 | 320 | 469 | 239 | 230 | 26 | 1 |
module Main where
import Graphics.Gnuplot.Simple
-- import qualified Graphics.Gnuplot.Terminal.WXT as WXT
-- import qualified Graphics.Gnuplot.Terminal.PostScript as PS
ops :: [Attribute]
-- ops = [(Custom "term" ["postscript", "eps", "enhanced", "color", "solid"])
-- ,(Custom "output" ["temp.eps"])
-- ]
-- ops = [(terminal $ WXT.persist WXT.cons)]
-- ops = [(EPS "temp.eps")]
ops = [(PNG "temp.png")]
main :: IO ()
main = do
let xs = (linearScale 1000 (0,2*pi)) :: [Double]
ys = fmap sin xs
points = zip xs ys
plotPath ops points
| chupaaaaaaan/nn-with-haskell | app/Main_ex.hs | bsd-3-clause | 569 | 0 | 13 | 116 | 115 | 66 | 49 | 10 | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.