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 Main where
myContains a b
| a == [] = False
| head a == b = True
| otherwise = myContains (tail a) b
myFilter a b
| b == [] = []
| a (head b) == False = myFilter a (tail b)
| otherwise = head b : myFilter a (tail b)
myAppend a b
| a == [] && b == [] = []
| a == [] = b
| b == [] = a
| length b == 1 = a : b
| otherwise = a : head b : myAppend a (tail b)
| pavlosmcg/haskell-musings | listfunctions.hs | mit | 380 | 6 | 11 | 121 | 267 | 123 | 144 | 15 | 1 |
module BusinessProcess.TypeChecker (typeChecker) where
import BusinessProcess.Types
import Data.List
-- import BusinessProcessModel
-- Checks wether a BusinessProcess is consistent,
-- according to the following rules
--
-- a) there must be just one trasition starting from the start state (why?)
-- b) there must be one or more transitions going to the end state
-- c) all other transitions, apart from start and end, must have at least one incoming transition.
-- d) all other transitions, apart from start and end, must have at least one outgoing transition.
--
typeChecker :: BusinessProcess -> Bool
typeChecker bp = (startRule bp) && (endRule bp) && (sequencingRule bp)
startRule bp = ((numberOfIncomingTransitions bp Start) == 1)
endRule bp = ((numberOfOutgoingTransitions bp End) > 0)
sequencingRule bp = seqRuleIn && seqRuleOut
where
seqRuleIn = and [hasIncomingTransitions bp fo | fo <- objects bp, fo /= Start, fo /= End]
seqRuleOut = and [hasOutcomingTransitions bp fo | fo <- objects bp, fo /= Start, fo /= End]
data Position = Incoming | Outgoing
deriving(Eq)
hasIncomingTransitions bp fo = not (findTransitions bp fo Incoming == [])
hasOutcomingTransitions bp fo = not (findTransitions bp fo Outgoing == [])
numberOfIncomingTransitions bp fo = length $ findTransitions bp fo Incoming
numberOfOutgoingTransitions bp fo = length $ findTransitions bp fo Outgoing
--
-- Retrieves the set of transitions, either starting from or
-- going to a specific flow object. It is an
-- an auxiliarly funcition, which helps
-- the type checker definition.
--
-- Nevertheless, I think it should be exposed by the
-- BusinessProcess.Types module.
--
findTransitions :: BusinessProcess -> FlowObject -> Position -> [(FlowObject, FlowObject, Condition)]
findTransitions bp fo pos =
case pos of
Incoming -> [(i,j,k) | (i,j,k) <- ((<*>) bp), i == fo]
Outgoing -> [(i,j,k) | (i,j,k) <- ((<*>) bp), j == fo]
| hephaestus-pl/hephaestus | willian/hephaestus-integrated/asset-base/bpmn/src/BusinessProcess/TypeChecker.hs | mit | 2,006 | 0 | 12 | 405 | 492 | 269 | 223 | 21 | 2 |
module Latte.FrontEnd.FunctionNameDuplicationSpec (main, spec) where
import qualified Data.Set as Set
import Test.Hspec
import Latte.Lang
import Latte.FrontEnd
mockFunction :: String -> TopDef
mockFunction name = FnDef Int (Ident name) [] (Block [])
main :: IO ()
main = hspec spec
spec :: Spec
spec = do
describe "Passing" $ do
it "No function" $ do
(runFeFnd (Program [])) >>= (`shouldBe` (Right (Set.empty, Set.empty)))
it "One function" $ do
(runFeFnd (Program [mockFunction "main"])) >>= (`shouldBe` (Right (Set.empty, Set.fromList ["main"])))
it "Many functions" $ do
(runFeFnd (Program [mockFunction "main", mockFunction "a", mockFunction "b"])) >>= (`shouldBe` (Right (Set.empty, Set.fromList ["main", "a", "b"])))
describe "Failing" $ do
it "One Function" $ do
(runFeFnd (Program [mockFunction "main", mockFunction "main"])) >>= (`shouldBe` (Right (Set.fromList ["main"], Set.fromList ["main"])))
it "Many functions, only colisions" $ do
(runFeFnd (Program [mockFunction "main", mockFunction "b", mockFunction "main", mockFunction "b", mockFunction "b"])) >>= (`shouldBe` (Right (Set.fromList ["main", "b"], Set.fromList ["main", "b"])))
it "One function colision, one no colision" $ do
(runFeFnd (Program [mockFunction "main", mockFunction "b", mockFunction "main"])) >>= (`shouldBe` (Right (Set.fromList ["main"], Set.fromList ["main", "b"])))
| mpsk2/LatteCompiler | testsuite/tests/Latte/FrontEnd/FunctionNameDuplicationSpec.hs | mit | 1,395 | 2 | 19 | 213 | 585 | 309 | 276 | 25 | 1 |
module Handler.Home
where
import Import
getHomeR :: Handler Html
getHomeR =
defaultLayout $
$(widgetFile "home")
| collaborare/antikythera | src/Handler/Home.hs | mit | 121 | 0 | 8 | 23 | 33 | 18 | 15 | -1 | -1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE StrictData #-}
{-# LANGUAGE TupleSections #-}
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpn-connection.html
module Stratosphere.Resources.EC2VPNConnection where
import Stratosphere.ResourceImports
import Stratosphere.ResourceProperties.Tag
import Stratosphere.ResourceProperties.EC2VPNConnectionVpnTunnelOptionsSpecification
-- | Full data type definition for EC2VPNConnection. See 'ec2VPNConnection'
-- for a more convenient constructor.
data EC2VPNConnection =
EC2VPNConnection
{ _eC2VPNConnectionCustomerGatewayId :: Val Text
, _eC2VPNConnectionStaticRoutesOnly :: Maybe (Val Bool)
, _eC2VPNConnectionTags :: Maybe [Tag]
, _eC2VPNConnectionType :: Val Text
, _eC2VPNConnectionVpnGatewayId :: Val Text
, _eC2VPNConnectionVpnTunnelOptionsSpecifications :: Maybe [EC2VPNConnectionVpnTunnelOptionsSpecification]
} deriving (Show, Eq)
instance ToResourceProperties EC2VPNConnection where
toResourceProperties EC2VPNConnection{..} =
ResourceProperties
{ resourcePropertiesType = "AWS::EC2::VPNConnection"
, resourcePropertiesProperties =
hashMapFromList $ catMaybes
[ (Just . ("CustomerGatewayId",) . toJSON) _eC2VPNConnectionCustomerGatewayId
, fmap (("StaticRoutesOnly",) . toJSON) _eC2VPNConnectionStaticRoutesOnly
, fmap (("Tags",) . toJSON) _eC2VPNConnectionTags
, (Just . ("Type",) . toJSON) _eC2VPNConnectionType
, (Just . ("VpnGatewayId",) . toJSON) _eC2VPNConnectionVpnGatewayId
, fmap (("VpnTunnelOptionsSpecifications",) . toJSON) _eC2VPNConnectionVpnTunnelOptionsSpecifications
]
}
-- | Constructor for 'EC2VPNConnection' containing required fields as
-- arguments.
ec2VPNConnection
:: Val Text -- ^ 'ecvpncCustomerGatewayId'
-> Val Text -- ^ 'ecvpncType'
-> Val Text -- ^ 'ecvpncVpnGatewayId'
-> EC2VPNConnection
ec2VPNConnection customerGatewayIdarg typearg vpnGatewayIdarg =
EC2VPNConnection
{ _eC2VPNConnectionCustomerGatewayId = customerGatewayIdarg
, _eC2VPNConnectionStaticRoutesOnly = Nothing
, _eC2VPNConnectionTags = Nothing
, _eC2VPNConnectionType = typearg
, _eC2VPNConnectionVpnGatewayId = vpnGatewayIdarg
, _eC2VPNConnectionVpnTunnelOptionsSpecifications = Nothing
}
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpn-connection.html#cfn-ec2-vpnconnection-customergatewayid
ecvpncCustomerGatewayId :: Lens' EC2VPNConnection (Val Text)
ecvpncCustomerGatewayId = lens _eC2VPNConnectionCustomerGatewayId (\s a -> s { _eC2VPNConnectionCustomerGatewayId = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpn-connection.html#cfn-ec2-vpnconnection-StaticRoutesOnly
ecvpncStaticRoutesOnly :: Lens' EC2VPNConnection (Maybe (Val Bool))
ecvpncStaticRoutesOnly = lens _eC2VPNConnectionStaticRoutesOnly (\s a -> s { _eC2VPNConnectionStaticRoutesOnly = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpn-connection.html#cfn-ec2-vpnconnection-tags
ecvpncTags :: Lens' EC2VPNConnection (Maybe [Tag])
ecvpncTags = lens _eC2VPNConnectionTags (\s a -> s { _eC2VPNConnectionTags = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpn-connection.html#cfn-ec2-vpnconnection-type
ecvpncType :: Lens' EC2VPNConnection (Val Text)
ecvpncType = lens _eC2VPNConnectionType (\s a -> s { _eC2VPNConnectionType = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpn-connection.html#cfn-ec2-vpnconnection-vpngatewayid
ecvpncVpnGatewayId :: Lens' EC2VPNConnection (Val Text)
ecvpncVpnGatewayId = lens _eC2VPNConnectionVpnGatewayId (\s a -> s { _eC2VPNConnectionVpnGatewayId = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpn-connection.html#cfn-ec2-vpnconnection-vpntunneloptionsspecifications
ecvpncVpnTunnelOptionsSpecifications :: Lens' EC2VPNConnection (Maybe [EC2VPNConnectionVpnTunnelOptionsSpecification])
ecvpncVpnTunnelOptionsSpecifications = lens _eC2VPNConnectionVpnTunnelOptionsSpecifications (\s a -> s { _eC2VPNConnectionVpnTunnelOptionsSpecifications = a })
| frontrowed/stratosphere | library-gen/Stratosphere/Resources/EC2VPNConnection.hs | mit | 4,264 | 0 | 15 | 472 | 643 | 368 | 275 | 54 | 1 |
{-|
A small module for performing some analysis of hydra models.
In the ipc compiler we use this to provide some sanity checking
of the compiled model.
-}
module Language.Hydra.Analysis
( sanityChecks
)
where
{- Imported Standard Libraries -}
{- Imported Local Libraries -}
import Language.Pepa.QualifiedName
( hprintQualifiedName )
import Language.Hydra.Syntax
( DNAMmodelFile ( .. )
, DNAMmodel ( .. )
, DNAMtransition ( .. )
)
{- End of Imports -}
{-|
Just for now we return a list of error messages but I think
in the future we will return something more sane.
-}
sanityChecks :: DNAMmodelFile a b -> [ String ]
sanityChecks (DNAMmodelFile model _sCont _pMeas) =
selfLoopErrors model
selfLoopErrors :: DNAMmodel a b -> [ String ]
selfLoopErrors model =
concatMap emptyAction $ modelTransitions model
where
emptyAction :: DNAMtransition a b -> [ String ]
emptyAction t
| null $ transActions t =
[ unwords [ "The transition"
, hprintQualifiedName $ transName t
, "contains no actions and is hence a self loop"
]
]
| otherwise =
[]
| allanderek/ipclib | Language/Hydra/Analysis.hs | gpl-2.0 | 1,194 | 0 | 12 | 335 | 203 | 112 | 91 | 22 | 1 |
-- Automatically execute source code in multiple languages, with docker.
-- Copyright (C) 2014 Pedro Tacla Yamada
--
-- 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 3 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, see <http://www.gnu.org/licenses/>.
module Main where
import System.Environment (getArgs)
import AutoRun
main :: IO ()
main = getArgs >>= mapM_ autorun
| yamadapc/autorun | src/Main.hs | gpl-2.0 | 881 | 0 | 6 | 151 | 54 | 37 | 17 | 5 | 1 |
-- If we allow a kTest as an initialiser, we can easily get a
-- paradox.
module T where
import Prelude hiding ( id )
import Tests.KBPBasis
import ADHOC.Knowledge.Clock
-- Agent "1" knows a bit iff the bit is false.
c = proc () ->
do rec x <- (| nondetLatchAC
(\x -> agent "1" (kTest $ "1" `knows` neg (probe "x")) <<< probeA "x" <<< idB -< x) |)
returnA -< x
-- Synthesis using the clock semantics
Just (_kautos_clk, mclk, _) = clockSynth MinNone c
ctlM_clk = mkCTLModel mclk
-- What is the value of the bit?
test_clock_bit1 = isOK (mc ctlM_clk (probe "x"))
test_clock_bit0 = isOK (mc ctlM_clk (neg (probe "x")))
| peteg/ADHOC | Tests/10_Knowledge/050_kbpTest_init.hs | gpl-2.0 | 646 | 3 | 23 | 146 | 201 | 107 | 94 | -1 | -1 |
module GGen.Slice ( planeSlice
) where
import Data.VectorSpace
import Data.AffineSpace
import Data.List (deleteFirstsBy, partition)
import GGen.Types
import GGen.Geometry.Types
import GGen.Geometry.Polygon (lineSegPaths, lineSegsToPolygons, polygonToLineSegPath, fixPolygon2Chirality)
import GGen.Geometry.Intersect (planeFaceIntersect, lineSegLineSeg2Intersect)
import GGen.Geometry.LineSeg (mergeLineSegList)
import GGen.Geometry.BoundingBox (facesBoundingBox)
orientPolygon :: Polygon R2 -> Bool -> OrientedPolygon R2
orientPolygon poly fill
| fill = (poly', RightHanded)
| otherwise = (poly', LeftHanded)
where poly' = fixPolygon2Chirality poly
unitZ = r3 (0,0,1)
-- | Try to find the boundaries sitting in a plane
-- Assumes slice is in XY plane
planeSlice :: [Face] -> Double -> Double -> Slice
planeSlice faces height z =
let plane = Plane { planeNormal=unitZ, planePoint=bbMin .+^ unitZ ^* z }
proj p = let (x,y,_) = unp3 p
in p2 (x,y) -- | Project point onto XY plane
projPolygon = map proj
projLineSeg (LineSeg a b) = LineSeg (proj a) (proj b) -- | Project line segment to XY plane
projLineSegPath = map projLineSeg
(_,_,planeZ) = unp3 $ planePoint plane
inPlane face = (abs (z - planeZ) < height) && (faceNormal face `parallel` unitZ)
where (_,_,z) = unp3 p
(p,_,_) = faceVertices face
(inPlaneFaces, outPlaneFaces) = partition inPlane faces
lines :: [LineSeg R3]
lines = mergeLineSegList
$ mapIntersection (planeFaceIntersect plane)
$ outPlaneFaces
paths = map projLineSegPath $ lineSegPaths lines
(polys, unmatchedPaths) = lineSegsToPolygons $ map projLineSeg lines
-- To figure out filled-ness, we project a segment from outside of the bounding box to each
-- of the line segment paths, counting intersections as we go
(bbMin, bbMax) = facesBoundingBox faces
origin = proj $ bbMax .+^ (bbMax.-.bbMin) ^* 0.1
-- | Figure out whether polygon should be filled
fillPoly :: Polygon R2 -> Bool
fillPoly poly = let path = polygonToLineSegPath poly
LineSeg a b = head path
ll = LineSeg origin $ alerp a b 0.5
inters = mapIntersection (lineSegLineSeg2Intersect ll)
$ concat (deleteFirstsBy approx paths [path])
in length inters `mod` 2 == 1
-- | Figure out whether a polygon is exposed. We see whether any of
-- the polygon vertices are coincident with a vertex of an exposed
-- face
exposedVerts = map proj
$ concat
$ map (\(Face _ (a,b,c)) -> [a,b,c])
$ inPlaneFaces
polyExposed :: Polygon R2 -> Exposure
polyExposed (Polygon vs) =
let checkVert v = or $ map (`coincident` v) exposedVerts
in case or $ map checkVert vs of
True -> External
False -> Internal
in (z, map (\poly -> (orientPolygon poly (fillPoly poly), polyExposed poly)) polys)
| bgamari/GGen | GGen/Slice.hs | gpl-3.0 | 3,481 | 0 | 17 | 1,236 | 865 | 465 | 400 | 55 | 2 |
module Vdv.XML where
import ClassyPrelude hiding (Element)
import Text.XML
elementToBareDocument :: Element -> Document
elementToBareDocument e =
Document {
documentPrologue = Prologue { prologueBefore = [], prologueDoctype = Nothing, prologueAfter = []}
, documentRoot = e
, documentEpilogue = []
}
| pmiddend/vdvanalyze | src/Vdv/XML.hs | gpl-3.0 | 320 | 0 | 9 | 61 | 83 | 51 | 32 | 9 | 1 |
--project euler problem 390
{--
Consider the triangle with sides sqrt(5), sqrt(65) and sqrt(68). It can be shown that this triangle has area 9.
S(n) is the sum of the areas of all triangles with sides sqrt(1+b2), sqrt(1+c2) and sqrt(b2+c2) (for positive integers b and c ) that have an integral area not exceeding n.
The example triangle has b=2 and c=8.
S(10^6)=18018206.
Find S(10^10).
--}
area_triangle_sq a b c = s * (s - a) * (s - b) * (s-c)
where s = (a+b+c)/2
main = do
txt <- readFile "base_exp.txt"
let pairs = zip [1..] $ map (split ',') $ lines txt
print $ fst $ maximumBy cmp pairs
| goalieca/haskelling | 390.hs | gpl-3.0 | 617 | 0 | 14 | 135 | 136 | 68 | 68 | 6 | 1 |
{-# LANGUAGE OverloadedStrings, QuasiQuotes, StandaloneDeriving #-}
module Main (main) where
import Prolog (Program, consult, parseQuery ,resolve, VariableName(..), Term(..),var,withTrace)
import Quote (ts)
import System.Environment (getArgs)
import Control.DeepSeq (deepseq, NFData(rnf))
instance NFData Term where
rnf (Struct a ts) = rnf a `seq` rnf ts
rnf (Var v) = rnf v
rnf (Cut n) = rnf n
rnf Wildcard = ()
instance NFData VariableName where
rnf (VariableName i s) = rnf i `seq` rnf s
run program_file goal = do
Right p <- consult program_file
case parseQuery goal of
Left err -> putStrLn (show err)
Right gs -> do
qs <- resolve p gs
putStrLn $ show qs
putStrLn $ "Number of solutions: " ++ show (length qs)
main = do
args <- getArgs
let n = case args of { [] -> 6; (x:_) -> read x }
putStrLn "Starting benchmark..."
-- qs <- resolve p [ts|queens($n,Qs)|]
-- run "../bench/queens.pl" "queens(5,Qs)"
run "../bench/fig02_12.pl" "[a,b,c] = .(a,.(b,.(c,[])))"
| nishiuramakoto/logiku | prolog/bench/Main.hs | gpl-3.0 | 1,053 | 0 | 15 | 245 | 368 | 189 | 179 | 26 | 2 |
{-# LANGUAGE OverloadedStrings #-}
module Reffit.Handlers.HandleIndex(
handleIndex
)
where
import Reffit.Types
import Reffit.Document
import Reffit.OverviewComment
import Reffit.Sort
import Reffit.PaperRoll
import Reffit.User
import Reffit.Scores
import Reffit.AcidTypes
import Reffit.FieldTag
import Reffit.Handlers.HandleNewPaper -- to get fieldTag button splices. TODO restructure
import Control.Applicative
import Snap.Core (getParams, writeText)
import Snap.Snaplet(Handler)
import Snap.Snaplet.AcidState (query)
import Snap.Snaplet.Auth
import Snap.Snaplet.Heist
import Application
import Heist
import qualified Heist.Interpreted as I
import qualified Data.Text as T
import qualified Data.Map as Map
import qualified Data.Set as Set
import qualified Data.ByteString.Char8 as BS
import Control.Monad
import Control.Monad.Trans
import Data.Map.Syntax
import Data.Time
import Data.Monoid ((<>))
handleIndex :: Handler App (AuthManager App) ()
--handleIndex = handlePaperRoll
handleIndex = do
docs <- query QueryAllDocs
us <- query QueryAllUsers
tags <- query QueryAllFieldTags
aUser <- currentUser
indexParams <- getParams
tNow <- liftIO $ getCurrentTime
let user' = join $ Map.lookup <$> (userLogin <$> aUser) <*> pure us :: Maybe User
renderWithSplices "_index" (allIndexSplices tNow docs user' us indexParams tags)
allIndexSplices :: UTCTime -> Map.Map DocumentId Document
-> Maybe User -> Map.Map UserName User
-> Map.Map BS.ByteString [BS.ByteString]
-> FieldTags
-> Splices (SnapletISplice App)
allIndexSplices tNow docs user' us indexParams tags = do
let docsToShow = presentationSort tNow docs (paramsToStrategy tags indexParams)
allPaperRollSplices docsToShow
allStatsSplices docs us
case user' of
Nothing -> do
"tagsButton" ## tagButtonSplice tagHierarchy
Just user -> do
allFilterTagSplices (Set.toList . userTags $ user) <>
("userRep" ## I.textSplice . T.pack . show $ userReputation docs user)
allStatsSplices :: Map.Map DocumentId Document -> Map.Map UserName User -> Splices (SnapletISplice App)
allStatsSplices docs us = do
"nUsers" ## I.textSplice $ T.pack . show . Map.size $ us
"nDocs" ## I.textSplice $ T.pack . show . Map.size $ docs
"nComments" ## I.textSplice $ T.pack . show $
sum (map (\d -> (Map.size . docOComments $ d)) (Map.elems docs) )
"nVotes" ## I.textSplice $ T.pack . show $
sum $ map docNVotes (Map.elems docs)
where
docNVotes doc = sum . map (length . ocResponse) .
Map.elems $ docOComments doc
allFilterTagSplices :: [TagPath] -> Splices (SnapletISplice App)
allFilterTagSplices tps = do
"fieldTags" ## renderFieldTags tps
"tagsButton" ## tagButtonSplice tagHierarchy
renderFieldTags :: [TagPath] -> SnapletISplice App
renderFieldTags = I.mapSplices $ I.runChildrenWith . splicesFromFieldTag
splicesFromFieldTag :: Monad n => TagPath -> Splices (I.Splice n)
splicesFromFieldTag tp = do
"fieldTagText" ## I.textSplice . last $ tp
"fieldTagFullText" ## I.textSplice . toFullName $ tp
| imalsogreg/reffit | src/Reffit/Handlers/HandleIndex.hs | gpl-3.0 | 3,169 | 0 | 18 | 627 | 943 | 486 | 457 | -1 | -1 |
module HipSpec.Lint where
import Text.PrettyPrint
import HipSpec.Lang.LintRich as R
import HipSpec.Lang.Simple as S
import HipSpec.GHC.Utils
import CoreSyn
import CoreLint
import SrcLoc
import HipSpec.Id
coreExprLint :: CoreExpr -> Maybe String
coreExprLint = fmap portableShowSDoc . lintUnfolding noSrcLoc []
lintRich :: Ord v => (v -> String) -> [(v,Type v)] -> LintM v a -> Maybe String
lintRich p sc m = case lintWithScope sc (text . p) m of
[] -> Nothing
errs -> Just (render . vcat $ errs)
lintSimple :: [S.Function Id] -> Maybe String
lintSimple = lintRich ppId [] . lintFns . map injectFn
lintSimpleExpr :: [(Id,Type Id)] -> S.Expr Id -> Maybe String
lintSimpleExpr sc = lintRich ppId sc . R.lintExpr . injectExpr
| danr/hipspec | src/HipSpec/Lint.hs | gpl-3.0 | 742 | 0 | 11 | 136 | 286 | 151 | 135 | 19 | 2 |
{-# LANGUAGE ScopedTypeVariables #-}
module Ampersand.Basics.Exit
( exitWith
, AmpersandExit(..)
) where
import Ampersand.Basics.Prelude
import Ampersand.Basics.UTF8
import Data.List
import qualified System.Exit as SE
import System.IO.Unsafe(unsafePerformIO)
{-# NOINLINE exitWith #-}
exitWith :: AmpersandExit -> a
exitWith x = unsafePerformIO $ do
mapM_ putStrLn message
SE.exitWith exitcode
where (exitcode,message) = info x
data AmpersandExit
= --Succes [String]
-- |
Fatal [String]
| NoValidFSpec [String]
| ViolationsInDatabase [(String,[String])]
| InvalidSQLExpression [String]
| NoPrototypeBecauseOfRuleViolations
| FailedToInstallComposer [String]
| PHPExecutionFailed [String]
| WrongArgumentsGiven [String]
| FailedToInstallPrototypeFramework [String]
info :: AmpersandExit -> (SE.ExitCode, [String])
info x =
case x of
-- Succes msg -> (SE.ExitSuccess , msg)
Fatal msg -> (SE.ExitFailure 2 , msg) -- These specific errors are due to some bug in the Ampersand code. Please report such bugs!
NoValidFSpec msg
-> (SE.ExitFailure 10 , case msg of
[] -> ["ERROR Something is wrong with your script. See https://github.com/AmpersandTarski/Ampersand/issues/751"]
_ -> msg
)
ViolationsInDatabase viols
-> (SE.ExitFailure 20 , "ERROR: The population would violate invariants. Could not generate your database." : concatMap showViolatedRule viols)
InvalidSQLExpression msg
-> (SE.ExitFailure 30 , "ERROR: Invalid SQL Expression" : map (" "++) msg)
NoPrototypeBecauseOfRuleViolations
-> (SE.ExitFailure 40 , ["ERROR: No prototype generated because of rule violations."])
FailedToInstallComposer msg
-> (SE.ExitFailure 50 , msg)
PHPExecutionFailed msg
-> (SE.ExitFailure 60 , msg)
WrongArgumentsGiven msg
-> (SE.ExitFailure 70 , msg)
FailedToInstallPrototypeFramework msg
-> (SE.ExitFailure 80 , msg)
where
showViolatedRule :: (String,[String]) -> [String]
showViolatedRule (rule,pairs) =
[ "Rule: "++rule
, " violations: "++intercalate ", " pairs
]
| AmpersandTarski/ampersand | src/Ampersand/Basics/Exit.hs | gpl-3.0 | 2,363 | 0 | 12 | 658 | 506 | 282 | 224 | 51 | 10 |
--------------------------------------------------------------------------------
-- This file is part of diplomarbeit ("Diplomarbeit Johannes Weiß"). --
-- --
-- diplomarbeit 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 3 of the License, or --
-- (at your option) any later version. --
-- --
-- diplomarbeit 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 diplomarbeit. If not, see <http://www.gnu.org/licenses/>. --
-- --
-- Copyright 2012, Johannes Weiß --
--------------------------------------------------------------------------------
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE FlexibleContexts #-}
module Data.Helpers ( integralBytes, takeOneConduit
, isOptionArg
, runTCPClientNoWait
) where
import Blaze.ByteString.Builder (Builder, toByteString)
import Blaze.ByteString.Builder.Char8 (fromChar)
import Control.Exception (bracket)
import Control.Monad.Trans.Resource (MonadResource)
import Data.Bits (Bits, shiftR)
import Data.ByteString (ByteString)
import Data.Char (chr)
import Data.Streaming.Network (safeRecv, getSocketFamilyTCP)
import Data.Streaming.Network.Internal
import Network.Socket.ByteString (sendAll)
import Data.Maybe (fromJust)
import Data.Monoid (mempty, mappend)
import qualified Data.Conduit as C
import qualified Data.Conduit.List as CL
import qualified Data.Conduit.Network as CN
import qualified Network.Socket as NS
-- | Encode a value of an 'Integral' type as 'ByteString'.
integralBytes :: (Integral a, Bits a, Show a)
=> a -- ^ Value to encode
-> ByteString -- ^ Returned 'ByteString'
integralBytes n0
| n0 < 0 = error ("integralBytes: applied to negative number " ++ show n0)
| otherwise =
let !bs = toByteString $ marshallIntByte n0 mempty
in bs
where marshallIntByte :: (Show a, Bits a, Integral a)
=> a -> Builder -> Builder
marshallIntByte !n !acc =
let !newChar = chr . fromIntegral $ n `mod` 256
!newBuilder = fromChar newChar
in case n of
0 -> acc
_ -> marshallIntByte (n `shiftR` 8) (acc `mappend` newBuilder)
-- | A 'C.Conduit' drops every element but the first.
takeOneConduit :: MonadResource m => C.Conduit i m i
takeOneConduit =
do mX <- CL.head
C.yield $ fromJust mX
-- | Run an "application" by connecting to the specified server.
-- Does TCP_NOWAIT
--
-- (stolen from streaming-commons-0.1.9.1)
runTCPClientNoWait :: CN.ClientSettings -> (AppData -> IO a) -> IO a
runTCPClientNoWait (ClientSettings port host addrFamily) app = bracket
(getSocketFamilyTCP host port addrFamily)
(NS.sClose . fst)
(\(s, address) ->
do NS.setSocketOption s NS.NoDelay 1
app AppData
{ appRead' = safeRecv s 4096
, appWrite' = sendAll s
, appSockAddr' = address
, appLocalAddr' = Nothing
, appCloseConnection' = NS.sClose s
})
-- | Predicate to decide whether a command line argument is an optional argument
-- (starts with a dash).
isOptionArg :: String -> Bool
isOptionArg s =
case s of
[] -> False
('-':_) -> True
_ -> False
| weissi/diplomarbeit | lib/Data/Helpers.hs | gpl-3.0 | 4,165 | 0 | 14 | 1,362 | 684 | 388 | 296 | 59 | 3 |
{-# 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.BigQueryDataTransfer.Projects.Locations.DataSources.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 supported data sources and returns their settings, which can be
-- used for UI rendering.
--
-- /See:/ <https://cloud.google.com/bigquery-transfer/ BigQuery Data Transfer API Reference> for @bigquerydatatransfer.projects.locations.dataSources.list@.
module Network.Google.Resource.BigQueryDataTransfer.Projects.Locations.DataSources.List
(
-- * REST Resource
ProjectsLocationsDataSourcesListResource
-- * Creating a Request
, projectsLocationsDataSourcesList
, ProjectsLocationsDataSourcesList
-- * Request Lenses
, pldslParent
, pldslXgafv
, pldslUploadProtocol
, pldslAccessToken
, pldslUploadType
, pldslPageToken
, pldslPageSize
, pldslCallback
) where
import Network.Google.BigQueryDataTransfer.Types
import Network.Google.Prelude
-- | A resource alias for @bigquerydatatransfer.projects.locations.dataSources.list@ method which the
-- 'ProjectsLocationsDataSourcesList' request conforms to.
type ProjectsLocationsDataSourcesListResource =
"v1" :>
Capture "parent" Text :>
"dataSources" :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "pageToken" Text :>
QueryParam "pageSize" (Textual Int32) :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
Get '[JSON] ListDataSourcesResponse
-- | Lists supported data sources and returns their settings, which can be
-- used for UI rendering.
--
-- /See:/ 'projectsLocationsDataSourcesList' smart constructor.
data ProjectsLocationsDataSourcesList =
ProjectsLocationsDataSourcesList'
{ _pldslParent :: !Text
, _pldslXgafv :: !(Maybe Xgafv)
, _pldslUploadProtocol :: !(Maybe Text)
, _pldslAccessToken :: !(Maybe Text)
, _pldslUploadType :: !(Maybe Text)
, _pldslPageToken :: !(Maybe Text)
, _pldslPageSize :: !(Maybe (Textual Int32))
, _pldslCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ProjectsLocationsDataSourcesList' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'pldslParent'
--
-- * 'pldslXgafv'
--
-- * 'pldslUploadProtocol'
--
-- * 'pldslAccessToken'
--
-- * 'pldslUploadType'
--
-- * 'pldslPageToken'
--
-- * 'pldslPageSize'
--
-- * 'pldslCallback'
projectsLocationsDataSourcesList
:: Text -- ^ 'pldslParent'
-> ProjectsLocationsDataSourcesList
projectsLocationsDataSourcesList pPldslParent_ =
ProjectsLocationsDataSourcesList'
{ _pldslParent = pPldslParent_
, _pldslXgafv = Nothing
, _pldslUploadProtocol = Nothing
, _pldslAccessToken = Nothing
, _pldslUploadType = Nothing
, _pldslPageToken = Nothing
, _pldslPageSize = Nothing
, _pldslCallback = Nothing
}
-- | Required. The BigQuery project id for which data sources should be
-- returned. Must be in the form: \`projects\/{project_id}\` or
-- \`projects\/{project_id}\/locations\/{location_id}
pldslParent :: Lens' ProjectsLocationsDataSourcesList Text
pldslParent
= lens _pldslParent (\ s a -> s{_pldslParent = a})
-- | V1 error format.
pldslXgafv :: Lens' ProjectsLocationsDataSourcesList (Maybe Xgafv)
pldslXgafv
= lens _pldslXgafv (\ s a -> s{_pldslXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
pldslUploadProtocol :: Lens' ProjectsLocationsDataSourcesList (Maybe Text)
pldslUploadProtocol
= lens _pldslUploadProtocol
(\ s a -> s{_pldslUploadProtocol = a})
-- | OAuth access token.
pldslAccessToken :: Lens' ProjectsLocationsDataSourcesList (Maybe Text)
pldslAccessToken
= lens _pldslAccessToken
(\ s a -> s{_pldslAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
pldslUploadType :: Lens' ProjectsLocationsDataSourcesList (Maybe Text)
pldslUploadType
= lens _pldslUploadType
(\ s a -> s{_pldslUploadType = a})
-- | Pagination token, which can be used to request a specific page of
-- \`ListDataSourcesRequest\` list results. For multiple-page results,
-- \`ListDataSourcesResponse\` outputs a \`next_page\` token, which can be
-- used as the \`page_token\` value to request the next page of list
-- results.
pldslPageToken :: Lens' ProjectsLocationsDataSourcesList (Maybe Text)
pldslPageToken
= lens _pldslPageToken
(\ s a -> s{_pldslPageToken = a})
-- | Page size. The default page size is the maximum value of 1000 results.
pldslPageSize :: Lens' ProjectsLocationsDataSourcesList (Maybe Int32)
pldslPageSize
= lens _pldslPageSize
(\ s a -> s{_pldslPageSize = a})
. mapping _Coerce
-- | JSONP
pldslCallback :: Lens' ProjectsLocationsDataSourcesList (Maybe Text)
pldslCallback
= lens _pldslCallback
(\ s a -> s{_pldslCallback = a})
instance GoogleRequest
ProjectsLocationsDataSourcesList
where
type Rs ProjectsLocationsDataSourcesList =
ListDataSourcesResponse
type Scopes ProjectsLocationsDataSourcesList =
'["https://www.googleapis.com/auth/bigquery",
"https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/cloud-platform.read-only"]
requestClient ProjectsLocationsDataSourcesList'{..}
= go _pldslParent _pldslXgafv _pldslUploadProtocol
_pldslAccessToken
_pldslUploadType
_pldslPageToken
_pldslPageSize
_pldslCallback
(Just AltJSON)
bigQueryDataTransferService
where go
= buildClient
(Proxy ::
Proxy ProjectsLocationsDataSourcesListResource)
mempty
| brendanhay/gogol | gogol-bigquerydatatransfer/gen/Network/Google/Resource/BigQueryDataTransfer/Projects/Locations/DataSources/List.hs | mpl-2.0 | 6,740 | 0 | 18 | 1,474 | 893 | 520 | 373 | 133 | 1 |
module Transpiler where
import Data.Char
import Data.List
import Control.Monad
import Control.Applicative
alpha :: String
alpha = ['a'..'z'] ++ ['A'..'Z']
nums :: String
nums = ['0' .. '9']
-----------------------------------------------------
--------------- my parser combinator ----------------
-----------------------------------------------------
newtype Parser val = Parser { parse :: String -> [(val, String)] }
parseCode :: Parser a -> String -> Either a String
parseCode m s = case parse m s of
[(res, [])] -> Left res
_ -> Right "Hugh?"
--
instance Functor Parser where
fmap f (Parser ps) = Parser $ \p -> [ (f a, b) | (a, b) <- ps p ]
--
instance Applicative Parser where
pure = return
(Parser p1) <*> (Parser p2) = Parser $ \p ->
[ (f a, s2) | (f, s1) <- p1 p, (a, s2) <- p2 s1 ]
--
instance Monad Parser where
return a = Parser $ \s -> [(a, s)]
p >>= f = Parser $ concatMap (\(a, s1) -> f a `parse` s1) . parse p
--
instance MonadPlus Parser where
mzero = Parser $ const []
mplus p q = Parser $ \s -> parse p s ++ parse q s
--
instance Alternative Parser where
empty = mzero
p <|> q = Parser $ \s -> case parse p s of
[] -> parse q s
rs -> rs
--
(<~>) :: Alternative a => a b -> a b -> a b
(<~>) = flip (<|>)
item :: Parser Char
item = Parser $ \s -> case s of
[ ] -> [ ]
(h : t) -> [(h, t)]
--
satisfy :: (Char -> Bool) -> Parser Char
satisfy p = item >>= \c -> if p c then return c else empty
option0 :: b -> Parser b -> Parser b
option0 d p = p <|> return d
oneOf :: String -> Parser Char
oneOf = satisfy . flip elem
charP :: Char -> Parser Char
charP = satisfy . (==)
digitP :: Parser Char
digitP = satisfy isDigit
reservedP :: String -> Parser String
reservedP = tokenP . stringP
spacesP :: Parser String
spacesP = some $ oneOf " \n\r\t"
spaces0P :: Parser String
spaces0P = option0 "" spacesP
stringP :: String -> Parser String
stringP [ ] = return []
stringP (c : cs) = do
charP c
stringP cs
return $ c : cs
--
tokenP :: Parser a -> Parser a
tokenP p = do
a <- p
spaces0P
return a
--
nameP :: Parser String
nameP = do
h <- oneOf s
n <- many $ oneOf $ s ++ "<>" ++ nums
spaces0P
return $ h : n
where s = '_' : alpha
--
seperateP ns s = do
n <- ns
return [n] <~> do
reservedP s
r <- seperateP ns s
spaces0P
return $ n : s : r
--
numberP :: Parser String
numberP = do
s <- stringP "-" <|> return []
cs <- some digitP
spaces0P
return $ s ++ cs
--
allNameP :: Parser String
allNameP = nameP <|> numberP
kotlinCallExpr :: Parser String
kotlinCallExpr = do
n <- kotlinExpr
e <- return "#" <~> do
reservedP "("
e <- option0 [] $ seperateP kotlinExpr ","
reservedP ")"
return $ join e
l <- option0 "" kotlinLambda
return $ g n ++ f e l
where f "#" [ ] = []
f "#" b = "(" ++ b ++ ")"
f a@(_ : _) b@(_ : _) = "(" ++ a ++ "," ++ b ++ ")"
f a b = "(" ++ a ++ b ++ ")"
g s@(h : _) |elem h l = "new " ++ s
|otherwise = s
where l = ['A' .. 'Z']
--
kotlinExpr :: Parser String
kotlinExpr = allNameP <|> kotlinLambda
kotlinLambda :: Parser String
kotlinLambda = do
reservedP "{"
pm <- option0 [] $ do
p <- seperateP nameP ","
reservedP "->"
return p
stmt <- many $ do
e <- kotlinExpr
return $ e ++ ";"
reservedP "}"
return $ "(" ++ join pm ++ "){" ++ join stmt ++ "}"
--
transpile :: String -> Either String String
transpile = parseCode kotlinCallExpr
| ice1000/OI-codes | codewars/authoring/haskell/Transpiler.hs | agpl-3.0 | 3,570 | 0 | 14 | 1,008 | 1,578 | 795 | 783 | 119 | 4 |
{-
Copyright (C) 2004-2007 John Goerzen <jgoerzen@complete.org>
Please see the COPYRIGHT file
-}
module Main where
import Test.HUnit
import Tests
import TestUtils
import System.IO
import Text.Printf
-- main = do runTestTT tests
main = do hSetBuffering stdout LineBuffering
hSetBuffering stderr LineBuffering
(c, _) <- performTest reportStart reportError reportFailure () tests
printf "\n TESTS COMPLETE\n"
printf "Cases: %d, Tried: %d, Errors: %d, Failures: %d\n"
(cases c) (tried c) (errors c) (failures c)
reportStart :: ReportStart ()
reportStart st () =
do printf "[%-4d/%-4d] START %s\n" (tried . counts $ st)
(cases . counts $ st)
(showPath . path $ st)
hFlush stdout
return ()
reportError :: ReportProblem ()
reportError = problem "ERROR "
reportFailure :: ReportProblem ()
reportFailure = problem "FAILURE"
problem :: String -> ReportProblem ()
problem ptype ptext st () =
do printf "[%-4d/%-4d] %s\n %s\n" (tried . counts $ st)
(cases . counts $ st)
(showPath . path $ st) ptext
hFlush stdout
return ()
| jgoerzen/hsh | testsrc/runtests.hs | lgpl-2.1 | 1,176 | 0 | 10 | 321 | 326 | 161 | 165 | 30 | 1 |
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE RecordWildCards #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Application
( getApplicationDev
, appMain
, develMain
, makeFoundation
, makeLogWare
-- * for DevelMain
, getApplicationRepl
, shutdownApp
-- * for GHCI
, handler
, db
) where
import Control.Monad.Logger (liftLoc, runLoggingT)
import Database.Persist.Postgresql (createPostgresqlPool, pgConnStr,
pgPoolSize, runSqlPool)
import Import
import Language.Haskell.TH.Syntax (qLocation)
import Network.Wai (Middleware)
import Network.Wai.Handler.Warp (Settings, defaultSettings,
defaultShouldDisplayException,
runSettings, setHost,
setOnException, setPort, getPort)
import Network.Wai.Middleware.RequestLogger (Destination (Logger),
IPAddrSource (..),
OutputFormat (..), destination,
mkRequestLogger, outputFormat)
import System.Log.FastLogger (defaultBufSize, newStdoutLoggerSet,
toLogStr)
-- Import all relevant handler modules here.
-- Don't forget to add new modules to your cabal file!
import Handler.Home
import Handler.Book
import Handler.Common
-- This line actually creates our YesodDispatch instance. It is the second half
-- of the call to mkYesodData which occurs in Foundation.hs. Please see the
-- comments there for more details.
mkYesodDispatch "App" resourcesApp
-- | This function allocates resources (such as a database connection pool),
-- performs initialization and returns a foundation datatype value. This is also
-- the place to put your migrate statements to have automatic database
-- migrations handled by Yesod.
makeFoundation :: AppSettings -> IO App
makeFoundation appSettings = do
-- Some basic initializations: HTTP connection manager, logger, and static
-- subsite.
appHttpManager <- newManager
appLogger <- newStdoutLoggerSet defaultBufSize >>= makeYesodLogger
appStatic <-
(if appMutableStatic appSettings then staticDevel else static)
(appStaticDir appSettings)
-- We need a log function to create a connection pool. We need a connection
-- pool to create our foundation. And we need our foundation to get a
-- logging function. To get out of this loop, we initially create a
-- temporary foundation without a real connection pool, get a log function
-- from there, and then create the real foundation.
let mkFoundation appConnPool = App {..}
-- The App {..} syntax is an example of record wild cards. For more
-- information, see:
-- https://ocharles.org.uk/blog/posts/2014-12-04-record-wildcards.html
tempFoundation = mkFoundation $ error "connPool forced in tempFoundation"
logFunc = messageLoggerSource tempFoundation appLogger
-- Create the database connection pool
pool <- flip runLoggingT logFunc $ createPostgresqlPool
(pgConnStr $ appDatabaseConf appSettings)
(pgPoolSize $ appDatabaseConf appSettings)
-- Perform database migration using our application's logging settings.
runLoggingT (runSqlPool (runMigration migrateAll) pool) logFunc
-- Return the foundation
return $ mkFoundation pool
-- | Convert our foundation to a WAI Application by calling @toWaiAppPlain@ and
-- applying some additional middlewares.
makeApplication :: App -> IO Application
makeApplication foundation = do
logWare <- makeLogWare foundation
-- Create the WAI application and apply middlewares
appPlain <- toWaiAppPlain foundation
return $ logWare $ defaultMiddlewaresNoLogging appPlain
makeLogWare :: App -> IO Middleware
makeLogWare foundation =
mkRequestLogger def
{ outputFormat =
if appDetailedRequestLogging $ appSettings foundation
then Detailed True
else Apache
(if appIpFromHeader $ appSettings foundation
then FromFallback
else FromSocket)
, destination = Logger $ loggerSet $ appLogger foundation
}
-- | Warp settings for the given foundation value.
warpSettings :: App -> Settings
warpSettings foundation =
setPort (appPort $ appSettings foundation)
$ setHost (appHost $ appSettings foundation)
$ setOnException (\_req e ->
when (defaultShouldDisplayException e) $ messageLoggerSource
foundation
(appLogger foundation)
$(qLocation >>= liftLoc)
"yesod"
LevelError
(toLogStr $ "Exception from Warp: " ++ show e))
defaultSettings
-- | For yesod devel, return the Warp settings and WAI Application.
getApplicationDev :: IO (Settings, Application)
getApplicationDev = do
settings <- getAppSettings
foundation <- makeFoundation settings
wsettings <- getDevSettings $ warpSettings foundation
app <- makeApplication foundation
return (wsettings, app)
getAppSettings :: IO AppSettings
getAppSettings = loadYamlSettings [configSettingsYml] [] useEnv
-- | main function for use by yesod devel
develMain :: IO ()
develMain = develMainHelper getApplicationDev
-- | The @main@ function for an executable running this site.
appMain :: IO ()
appMain = do
-- Get the settings from all relevant sources
settings <- loadYamlSettingsArgs
-- fall back to compile-time values, set to [] to require values at runtime
[configSettingsYmlValue]
-- allow environment variables to override
useEnv
-- Generate the foundation from the settings
foundation <- makeFoundation settings
-- Generate a WAI Application from the foundation
app <- makeApplication foundation
-- Run the application with Warp
runSettings (warpSettings foundation) app
--------------------------------------------------------------
-- Functions for DevelMain.hs (a way to run the app from GHCi)
--------------------------------------------------------------
getApplicationRepl :: IO (Int, App, Application)
getApplicationRepl = do
settings <- getAppSettings
foundation <- makeFoundation settings
wsettings <- getDevSettings $ warpSettings foundation
app1 <- makeApplication foundation
return (getPort wsettings, foundation, app1)
shutdownApp :: App -> IO ()
shutdownApp _ = return ()
---------------------------------------------
-- Functions for use in development with GHCi
---------------------------------------------
-- | Run a handler
handler :: Handler a -> IO a
handler h = getAppSettings >>= makeFoundation >>= flip unsafeHandler h
-- | Run DB queries
db :: ReaderT SqlBackend (HandlerT App IO) a -> IO a
db = handler . runDB
| PKAuth/pkcloud-accounts | src/Application.hs | apache-2.0 | 7,165 | 0 | 13 | 1,809 | 1,059 | 570 | 489 | 113 | 3 |
import XMonad
import XMonad.Hooks.DynamicLog
import XMonad.Hooks.ManageDocks
import XMonad.Hooks.EwmhDesktops
import XMonad.Hooks.ICCCMFocus
import XMonad.Hooks.SetWMName
import XMonad.Layout.NoBorders
import XMonad.Layout.ThreeColumns
import XMonad.Util.Run(spawnPipe)
import XMonad.Util.EZConfig(additionalKeys)
import System.IO
import qualified XMonad.StackSet as W
import XMonad.Util.EZConfig
myLayout = tiled ||| Full ||| ThreeCol 1 (3/100) (1/3)
where
-- default tiling algorithm partitions the screen into two panes
tiled = Tall nmaster delta ratio
-- The default number of windows in the master pane
nmaster = 1
-- Default proportion of screen occupied by master pane
ratio = 1/2
-- Percent of screen to increment by when resizing panes
delta = 3/100
myModMask = mod4Mask
main = do
xmonad $ ewmh defaultConfig
{ layoutHook = smartBorders $ myLayout
, terminal = "urxvtc"
, modMask = myModMask
, borderWidth = 2
, normalBorderColor = "#0c0d0e"
, focusedBorderColor = "#333333"
, handleEventHook = fullscreenEventHook
, startupHook = setWMName "LG3D"
, logHook = takeTopFocus
}
`additionalKeys`
[ ((myModMask, xK_q), spawn "date +'%c' | dzen2 -p 2 -fn '-*-terminus-bold-*-*-*-28-*-*-*-*-*-*-*' -bg '#0c0d0e' -fg '#7f8f9f'")
, ((myModMask, xK_w), spawn "acpi -b | dzen2 -p 2 -fn '-*-terminus-bold-*-*-*-28-*-*-*-*-*-*-*' -bg '#0c0d0e' -fg '#7f8f9f'")
, ((myModMask, xK_e), spawn "wmctrl -a eclipse")
, ((myModMask, xK_i), spawn "dmenu-switch")
, ((myModMask, xK_Right), windows W.focusDown)
, ((myModMask, xK_Left), windows W.focusUp)
, ((myModMask, xK_Down), sendMessage Shrink)
, ((myModMask, xK_Up), sendMessage Expand)
, ((myModMask, xK_j), windows W.focusDown)
, ((myModMask, xK_k), windows W.focusUp)
, ((myModMask, xK_h), sendMessage Shrink)
, ((myModMask, xK_l), sendMessage Expand)
, ((myModMask .|. mod3Mask, xK_j), windows W.focusDown)
, ((myModMask .|. mod3Mask, xK_k), windows W.focusUp)
, ((myModMask .|. mod3Mask, xK_h), sendMessage Shrink)
, ((myModMask .|. mod3Mask, xK_l), sendMessage Expand)
, ((myModMask .|. shiftMask, xK_Right), windows W.swapDown)
, ((myModMask .|. shiftMask, xK_Left), windows W.swapUp)
, ((myModMask .|. shiftMask, xK_Down), sendMessage (IncMasterN (-1)))
, ((myModMask .|. shiftMask, xK_Up), sendMessage (IncMasterN 1))
, ((myModMask .|. shiftMask, xK_j), windows W.swapDown)
, ((myModMask .|. shiftMask, xK_k), windows W.swapUp)
, ((myModMask .|. shiftMask, xK_h), sendMessage (IncMasterN (-1)))
, ((myModMask .|. shiftMask, xK_l), sendMessage (IncMasterN 1))
, ((myModMask .|. shiftMask, xK_F9), spawn "suspend-to-mem")
, ((myModMask, xK_F8), spawn "slock")
, ((myModMask .|. shiftMask, xK_F11), spawn "reboot")
, ((myModMask .|. shiftMask, xK_F12), spawn "shutdown")
, ((myModMask, xK_a), screenWorkspace 2 >>= flip whenJust (windows . W.view))
, ((myModMask, xK_s), screenWorkspace 0 >>= flip whenJust (windows . W.view))
, ((myModMask, xK_d), screenWorkspace 1 >>= flip whenJust (windows . W.view))
]
`additionalKeysP`
[ ("M-S-a", kill)
, ("M-<Insert>", spawn "amixer -q set Master toggle")
, ("M-<Page_Up>", spawn "amixer set Master 1+")
, ("M-<Page_Down>", spawn "amixer set Master 1-")
, ("M-z", windows $ W.greedyView "1")
, ("S-M-z", windows $ W.shift "1")
, ("M-x", windows $ W.greedyView "2")
, ("S-M-x", windows $ W.shift "2")
, ("M-c", windows $ W.greedyView "3")
, ("S-M-c", windows $ W.shift "3")
, ("M-v", windows $ W.greedyView "4")
, ("S-M-v", windows $ W.shift "4")
, ("M-b", windows $ W.greedyView "5")
, ("S-M-b", windows $ W.shift "5")
]
| beloglazov/dotfiles | tag-xmonad/xmonad/xmonad.hs | apache-2.0 | 4,527 | 22 | 15 | 1,482 | 1,230 | 721 | 509 | 77 | 1 |
-- |Adds constraints for the browser DOM to the environment.
module Ovid.DOM
( topLevelIds
, topLevelPreprocessing
) where
--{{{ Imports
import CFA
import CFA.Labels
import Prelude hiding (lookup)
import Ovid.Prelude
import Text.ParserCombinators.Parsec.Pos (initialPos)
import qualified Data.Map as M
import WebBits.JavaScript.JavaScript hiding (Statement)
import qualified WebBits.JavaScript.JavaScript as Js
import Ovid.Abstraction
import Ovid.Environment
import Ovid.ConstraintUtils
--}}}
--{{{ Helpers
type Statement = Js.Statement Ann
noPos = initialPos "Ovid/DOM.hs"
object :: (MonadIO m)
=> Label -- ^ primes this label with 2,3,4
-> String
-> Label
-> [(String,(Label,Contour))]
-> CfaT Value m Label
object objectLabel name this properties = do
-- resultant object is stored in objectSet
ct <- emptyContour
let objectSet = (objectLabel,ct)
-- The object has a collection of properties, stored at propSet
let propLbl = primeLabel objectLabel 1
let propSet = (propLbl,ct)
let fnVal = ABuiltin name objectLabel this (Just propLbl)
-- object has a .prototype property, its value is stored at prototypeSet
let prototypeLbl = primeLabel propLbl 1
let prototypeSet = (prototypeLbl,ct)
newValue (AProperty "prototype" (ValueSet prototypeSet)) propSet
-- the .prototype property is set to an object, whose properties are stored at baseSet.
let baseLbl = primeLabel objectLabel 2
let baseSet = (baseLbl,ct)
newValue (AObject baseLbl baseSet PNotSpecial) prototypeSet -- the prototypical object (which has no prototype)
let insertProperty (id,val) = newValue (AProperty id (ValueSet val)) baseSet
mapM_ insertProperty properties
newValue fnVal objectSet
return baseLbl
property id set this = do
newValue (AProperty id (ValueSet set)) (this,topContour)
function name this = do
lbl <- builtinLabel name
ct <- emptyContour
let fn = (ABuiltin name lbl this Nothing)
newValue fn (lbl,ct)
return (lbl,ct)
-- |Primes 'lbl' with 2
topFunction name lbl = do
let this = primeLabel lbl 1
let ct = topContour
let fn = ABuiltin name lbl this Nothing
newValue fn (lbl,ct)
return (name,lbl)
--}}}
-- |List of names to add to the top-level.
topLevelIds =
["Array","Function","eval","window","XMLHttpRequest","print","String", "addEventListener","document","Element",
"Object","undefined","$A","$w"]
initArrays lblArray = do
let this = primeLabel lblArray 1
push <- function "Array.push" this
concat <- function "Array.concat" this
slice <- function "Array.slice" this
prototypeLbl <- object lblArray "Array" this [("push",push),("concat",concat),("slice",slice)]
return [("Array",lblArray),("Array-props",prototypeLbl)]
initStrings lblString = do
let this = primeLabel lblString 1
any <- function "String.any" this
prototypeLbl <- object lblString "String" this [("any",any)]
return [("String",lblString),("String-props",prototypeLbl)]
initFunctions lblFunction = do
let this = primeLabel lblFunction 1
apply <- function "Function.apply" this
prototypeLbl <- object lblFunction "Function" this [("apply",apply)]
return [("Function",lblFunction),("Function-props",prototypeLbl)]
initObjects objectLbl = do
let this = primeLabel objectLbl 1
prototypeLbl <- object objectLbl "Object" this []
return [("Object",objectLbl),("Object-props",prototypeLbl)]
initEval evalLbl = do
let this = primeLabel evalLbl 1
eval <- function "eval" this
evalSet <- emptyContour >>= \ct -> return (evalLbl,ct)
subsetOf eval evalSet
return [("eval",evalLbl)]
initWindow windowLbl = do
let this = primeLabel windowLbl 1
addEventListener <- function "window.addEventListener" this
prototypeLbl <- object windowLbl "window" this
[("addEventListener",addEventListener)]
return [("window",windowLbl),("window-props",prototypeLbl)]
initElements eltLbl = do
let this = primeLabel eltLbl 1
prototypeLbl <- object eltLbl "Element" this []
return [("Element",eltLbl),("Element-props",prototypeLbl)]
initDocument documentLbl = do
let this = primeLabel documentLbl 1
-- getElementByTagName <- function "document.getElementByTagName" this
-- getElementById <- function "document.getElementById" this
write <- function "document.write" this
property "write" write this
newValue (AObject documentLbl (this,topContour) PNotSpecial {- but it is!!! -}) (documentLbl,topContour)
return [("document",documentLbl)]
initXMLHttpRequest xhrLbl = do
let this = primeLabel xhrLbl 1
send <- function "XMLHttpRequest.send" this
open <- function "XMLHttpRequest.open" this
prototypeLbl <- object xhrLbl "XMLHttpRequest" this [("send",send),("open",open)]
return [("XMLHttpRequest-props",prototypeLbl),("XMLHttpRequest",xhrLbl), ("XMLHttpRequest:send",fst send)]
lookup k m = case M.lookup k m of
Nothing -> fail $ "lookup: key not found--" ++ show k
Just v -> return v
-- |Preprocessing before interpreting any files
topLevelPreprocessing :: (MonadIO m)
=> M.Map String Label -- ^top level names
-> CfaT Value
(StateT (JsCFAState Contour) m)
(M.Map String Label)
topLevelPreprocessing topLevel = do
let def fn = lookup fn topLevel >>= topFunction fn
arrayNames <- lookup "Array" topLevel >>= initArrays
strings <- lookup "String" topLevel >>= initStrings
elements <- lookup "Element" topLevel >>= initElements
objects <- lookup "Object" topLevel >>= initObjects
functionNames <- lookup "Function" topLevel >>= initFunctions
evalNames <- lookup "eval" topLevel >>= initEval
print <- def "print"
dollarA <- def "$A"
dollarw <- def "$w"
addEventListener <- def "addEventListener"
windowNames <- lookup "window" topLevel >>= initWindow
documentNames <- lookup "document" topLevel >>= initDocument
xhrNames <- lookup "XMLHttpRequest" topLevel >>= initXMLHttpRequest
-- bind undefined
newValue UndefinedVal (runIdentity $ lookup "undefined" topLevel,topContour)
return $ M.union topLevel $ M.fromList $ dollarA : dollarw : print : addEventListener: (evalNames ++ arrayNames
++ functionNames ++ windowNames ++ xhrNames ++ documentNames ++ strings ++ elements ++ objects)
| brownplt/ovid | src/Ovid/DOM.hs | bsd-2-clause | 6,278 | 0 | 16 | 1,128 | 1,873 | 943 | 930 | 130 | 2 |
module FractalFlame.Types.Plottable where
import FractalFlame.Point.Types.CartesianPoint
import FractalFlame.Types.Base
data Plottable = Plottable {
point :: CartesianPoint
, colorIx :: Coord
} deriving (Show)
| anthezium/fractal_flame_renderer_haskell | FractalFlame/Types/Plottable.hs | bsd-2-clause | 221 | 0 | 8 | 33 | 48 | 31 | 17 | 7 | 0 |
{-# LANGUAGE OverloadedStrings #-}
{- |
Module : Glider.NLP.TokenizerSpec
Copyright : Copyright (C) 2013-2014 Krzysztof Langner
License : BSD3
Maintainer : Krzysztof Langner <klangner@gmail.com>
Stability : alpha
Portability : portable
-}
module Glider.NLP.TokenizerSpec (spec) where
import Glider.NLP.Tokenizer
import Test.Hspec
spec :: Spec
spec = describe "Tokenize" $ do
it "empty string" $ tokenize "" `shouldBe` []
it "text strings" $ tokenize "one two three" `shouldBe` [ Word "one"
, Whitespace
, Word "two"
, Whitespace
, Word "three"
]
| klangner/glider-nlp | test-src/Glider/NLP/TokenizerSpec.hs | bsd-2-clause | 866 | 0 | 10 | 399 | 106 | 58 | 48 | 12 | 1 |
{-# LANGUAGE DeriveDataTypeable
, NoImplicitPrelude
, UnicodeSyntax
#-}
{-
Lot's of code in this module was 'borrowed' from criterion.
-}
module Test.Complexity.Config where
--------------------------------------------------------------------------------
-- Imports
--------------------------------------------------------------------------------
-- from base:
import Control.Monad ( (>>=), fail )
import Data.String ( String )
import Data.Eq ( Eq )
import Data.Function ( on )
import Data.Maybe ( Maybe(Just) )
import Data.Monoid ( Monoid(..), Last(..) )
import Data.Ord ( Ord )
import Data.Typeable ( Typeable )
import Prelude ( Bounded, Enum, Integer, fromInteger )
import Text.Read ( Read )
import Text.Show ( Show )
-- from base-unicode-symbols:
import Data.Function.Unicode ( (∘) )
--------------------------------------------------------------------------------
-- Configurations
--------------------------------------------------------------------------------
data Verbosity = Quiet
| Normal
| Verbose
deriving (Eq, Ord, Bounded, Enum, Read, Show, Typeable)
data Exit = ExitWithVersion
| ExitWithHelp
deriving (Eq, Ord, Bounded, Enum, Read, Show, Typeable)
data Config = Config { cfgVerbosity ∷ Last Verbosity
, cfgDataFile ∷ Last String
, cfgTimeout ∷ Last Integer
, cfgExit ∷ Last Exit
} deriving (Eq, Read, Show, Typeable)
instance Monoid Config where
mempty = emptyConfig
mappend = appendConfig
ljust ∷ α → Last α
ljust = Last ∘ Just
emptyConfig ∷ Config
emptyConfig = Config { cfgVerbosity = mempty
, cfgDataFile = mempty
, cfgTimeout = mempty
, cfgExit = mempty
}
defaultConfig ∷ Config
defaultConfig = Config { cfgVerbosity = ljust Normal
, cfgDataFile = mempty
, cfgTimeout = ljust 10
, cfgExit = mempty
}
appendConfig ∷ Config → Config → Config
appendConfig x y = Config { cfgVerbosity = app cfgVerbosity x y
, cfgDataFile = app cfgDataFile x y
, cfgTimeout = app cfgTimeout x y
, cfgExit = app cfgExit x y
}
where app f = mappend `on` f
| roelvandijk/complexity | Test/Complexity/Config.hs | bsd-3-clause | 2,633 | 0 | 9 | 929 | 526 | 310 | 216 | 49 | 1 |
{-
Module Regressions gives the tools to perform gradient decent including adding new features, scaling data and fitting polynomial to data.
You can't scale after adding free term.
-}
module Regressions
( scale
, addFreeTerm
, getXYContainer
, getX
, getY
, getHeaders
, getAmountOfBasicFeatures
, gradientDescent
, getLastTheta
, getLastCost
, makeTrainingSet
, createNewFeature
, createNewFeaturesFromListToTrainingSet
, evaluateInputData
, GradDescentInfo
, Alpha
, Epsilon
, Cost
, Theta
, NormalizeConst
, TrainingSet
, XYContainer
, VariableInd
, NewFeature
) where
import Matrix
import DataBuilder (NumContainer(..), Header)
import MaybeResult
import System.IO
import Data.List
import MaybeResult
-- | Matrix of data, columns are features, rows training sets
type X = Matrix Double
-- | Vertical vector of the result
type Y = Matrix Double
--Vertical vector of theta
type Theta = Matrix Double
-- | Specifies the amount of features that are real, not created by program
type AmountOfBasicFeatures = Int
-- | Index of free term column
type FreeTermColumnInd = Maybe Int
-- | holder of X matrix, its headers, Y vector, information
-- | about amount of basic features and information about if free term column has been added to X matrix,
-- | a list of new features (tuples with information to what power which variable has been raised to in order to create new feature)
data XYContainer = XYContainer ([Header], X, Y, AmountOfBasicFeatures, FreeTermColumnInd, [NewFeature], Scaled)
-- | Horizontal vector of data of one single training set
type TrainingSet = Matrix Double
-- | Const that is used to multiply one of thetas element and then add the product to a cost function
type NormalizeConst = Double
-- | Learn speed rate
type Alpha = Double
-- | Convergence condition. Specifies how small should the difference between next costs be to stop gradient descent.
type Epsilon = Double
-- | Cost of polynomial fitting
type Cost = Double
-- | Index of a variable
type VariableInd = Int
-- | Number to which we take a number to
type Power = Int
-- | Maximum of iteration that gradient descent can perform
type MaxIter = Int
-- | Tuple with information on an added feature to data, in detail: about a power
-- | to which variable on index VariableInd has been raised in order to create new feature
type NewFeature = (Power, VariableInd) -- freeterm nie jest newfeaturem
type Scaled = Bool
-- | Holds information about training. As a tuple: (Produced Theta, Last Cost)
type GradDescentInfo = (Theta, Cost)
-- * Instances
instance Show XYContainer where
show (XYContainer (headers, x, y, am, _, _, _)) = "---------X--------- \n" ++ show headers ++ "\n" ++ show x ++ "\n" ++ "---------Y--------- \n" ++ show y
++ "\n" ++ "Amount of basic features: " ++ show am
-- * FUNCTIONS INDEX
-- | Takes an y column index, NumContainer and produces XYContainer - holder of X matrix, its headers, Y vector, information
-- | about amount of basic features and information about if free term column has been added to X matrix. Indexing from 1
getXYContainer :: Int -> NumContainer -> XYContainer
-- | Scales data in XYContainer. For each element: x' = (x - avg(column where x is)) / range_of_values(column where x is)
scale :: XYContainer -> MaybeRes (XYContainer)
-- | Adds a column of ones at the end of X.
addFreeTerm :: XYContainer -> MaybeRes (XYContainer)
-- | Creates a TrainingSet out of a list
makeTrainingSet :: [Double] -> TrainingSet
-- | Creates new features to X by taking VariableInd-th feature and raise it to the power Power
createNewFeature :: VariableInd -> Power -> XYContainer -> MaybeRes (XYContainer)
-- | Performs a gradient descent algorithm for data in XYContainer. Alpha is a learn speed rate, epsilon is the convergence
-- | condition (gradient descent stops when the difference between current cost and next cost is lower than epsilon),
-- | MaxIter is a maximum of iteration you allow gradient descent to go through, and a list of (NormalizeConst, VariableInd)
-- | is a list pairs of normalize const and variable index - it adds to the cost function the sum of products of elements of each pair.
gradientDescent :: XYContainer -> Alpha -> Epsilon -> MaxIter -> [(NormalizeConst, VariableInd)] -> IO (GradDescentInfo)
-- | Evaluates input data (just basic features needed to pass), Param: input data, theta, baseContainer (before scaling), fullyDoneContainer (after adding all the staff)
evaluateInputData :: TrainingSet -> Theta -> XYContainer -> XYContainer -> Double
-- * getters
getX :: XYContainer -> X
getY :: XYContainer -> Y
getHeaders :: XYContainer -> [Header]
getAmountOfBasicFeatures :: XYContainer -> AmountOfBasicFeatures
getFreeTermColumnInd :: XYContainer -> FreeTermColumnInd
getNewFeatureList :: XYContainer -> [NewFeature]
getLastCost :: GradDescentInfo -> Cost
getLastTheta :: GradDescentInfo -> Theta
getXYContainer yColumnIndex (NumContainer (s, m)) = XYContainer (allBut_ yColumnIndex s, deleteColumns [yColumnIndex] m, packM [toList $ getColumn yColumnIndex m], (length s) - 1, Nothing, [], False)
createNewFeature varInd power (XYContainer (s , mx, my, am, wf, newF, False)) =
JustRes $ XYContainer (
s ++ [(takeElement varInd s) ++ " to power " ++ show power],
getResult (mx `conver` (fmap (^ power) columnToAlter)),
my,
am,
wf,
newF ++ [(power, varInd)],
False
)
where
columnToAlter = getColumn varInd mx
unJust = \(Just a) -> a
takeElement 1 (x:xs) = x
takeElement i (x:xs) = takeElement (i-1) xs
createNewFeature varInd power (XYContainer (s , mx, my, am, wf, newF, True)) = Error "Can't add new features after scaling!"
scale (XYContainer (s, mx, my, am, Nothing, newF, False)) = JustRes $ XYContainer (s, scaleLines mx, scaleLines my, am, Nothing, newF, True)
scale (XYContainer (s, mx, my, am, _, newF, True)) = Error "Can't scale more than one time."
scale (XYContainer (s, mx, my, am, _, newF, _)) = Error "Can't scale after adding free term."
addFreeTerm (XYContainer (s , mx, my, am, Nothing, newF, sc)) = JustRes $ XYContainer (s ++ ["Free term"],
getResult (mx `conver` vectorOfOnes),
my,
am,
Just $ (length s) + 1,
newF ++ [(0, 2)], --we add free term which is any number to power 0
sc
)
where
vectorOfOnes = vector (replicate (getHeight $ mx) 1) 0
addFreeTerm (XYContainer (s , mx, my, am, _, _, _)) = Error "Free term already has been added."
gradientDescent xyc alpha epsilon maxiter ns = loop epsilon (thetaInit xyc 1) 0
where
loop eps tht i = do
currentCost <- return $ costNormalized xyc tht ns
newCost <- return $ costNormalized xyc (gradientDescentStep xyc tht alpha ns) ns
if abs(currentCost - newCost) < eps || i == maxiter
then return ((gradientDescentStep xyc tht alpha ns), currentCost)
else
print ("Current cost = " ++ (show currentCost)) >>
loop eps (gradientDescentStep xyc tht alpha ns) (i+1)
-- | Creates new features to the training set as specified in a list of info about new features. XYContainer is a base
-- | container - before scaling and adding free term to it
createNewFeaturesFromListToTrainingSet :: [NewFeature] -> TrainingSet -> TrainingSet
createNewFeaturesFromListToTrainingSet nf trSet = getResult $ trSet `conver` (loop nf)
where
loop [] = trSet
loop [(power, varInd)] = (fmap (^ power) columnToAlter varInd)
loop ((power, varInd):nf) = getResult ( (fmap (^ power) columnToAlter varInd) `conver` (loop nf) )
columnToAlter var = getColumn var trSet
evaluateInputData inputData tht baseContainer fullyDone = case (getWidth withNewFeatures) == (getHeight tht) of
True -> getResult $ getElementByInd (1, 1) $ (getResult $ scaleTrainingSet baseContainer withNewFeatures) * tht
False -> getResult $ getElementByInd (1, 1) $ (insertColumnAfter ((unJust . getFreeTermColumnInd $ fullyDone) - 1) 1 . getResult . scaleTrainingSet baseContainer $ withNewFeatures) * tht
where
withNewFeatures = createNewFeaturesFromListToTrainingSet (getNewFeatureList baseContainer) inputData
insertColumnAfter i val m = getResult (m `conver` (packM [[val]]))
scaleTrainingSet :: XYContainer -> TrainingSet -> MaybeRes (TrainingSet)
scaleTrainingSet baseContainer trainSet
| isOK (zipWithM (*) rangeMatrix trainSet) && isOK (zipWithM (+) (getResult $ zipWithM (*) rangeMatrix trainSet) avgMatrix)
= zipWithM (+) (getResult $ zipWithM (*) rangeMatrix trainSet) avgMatrix
| otherwise = Error "Error while scaling training set."
where
avgMatrix = getAvgColumnsMatrix . getX $ (baseContainer)
rangeMatrix = getRangeColumnsMatrix . getX $ (baseContainer)
-----------------------------------------
makeTrainingSet xs = vector xs 1
--getters
getX (XYContainer (_, x, _, _, _, _, _)) = x
getY (XYContainer (_, _, y, _, _, _, _)) = y
getHeaders (XYContainer (xs, _, _, _, _, _, _)) = xs
getAmountOfBasicFeatures (XYContainer (_, _, _, am, _, _, _)) = am
getFreeTermColumnInd (XYContainer (_, _, _, _, wf, _, _)) = wf
getNewFeatureList (XYContainer (_, _, _, _, _, newF, _)) = newF
isScaled (XYContainer (_, _, _, _, _, _, sc)) = sc
getLastCost (_, cost) = cost
getLastTheta (theta, _) = theta
--PRIVATE FUNCTIONS
gradientDescentStep :: XYContainer -> Theta -> Alpha -> [(NormalizeConst, VariableInd)] -> Theta
gradientDescentStep xyc theta alpha ns = loop (getWidth . getX $ xyc)
where
loop 1 = packM ([[(getResult $ getElementByInd (1, 1) theta) - (alpha * (costeval' 1 xyc theta ns))]])
loop i = getResult ((packM ([[(getResult $ getElementByInd (1, i) theta) - (alpha * (costeval' i xyc theta ns))]])) `conhor` (loop (i-1)))
unJust = \(Just a) -> a
costeval' varOfDer xyCon tht ns = (costNormalized' varOfDer tht xyCon ns)
cost :: Theta -> XYContainer -> Double
cost theta (XYContainer(_, mx, my, _, _, _, _)) = (addLinesAndGetDouble . fmap (^2) $ (vectorOfEvaluatedHypothesis) - (transposeM $ my)) / (2*(fromIntegral . length $ unpackedmx))
where
unpackedmx = unpackM . transposeM $ mx --transposed list of lists of matrix X
addLinesAndGetDouble = getResult . getElementByInd (1, 1) . zipWithLines (+)
forEachListEvalHypothesis = (\xs -> [evalHypothesis (vector xs 1) theta])
vectorOfEvaluatedHypothesis = packM $ map forEachListEvalHypothesis unpackedmx
cost' :: Int -> Theta -> XYContainer -> Double
cost' varOfDer theta (XYContainer (_, mx, my, _, _, _, _)) =
((getElement $ ((vectorOfEvaluatedHypothesis) - (transposeM $ my))*(getAllTrainingSetsOfOneFeature varOfDer mx)) / (fromIntegral . length $ unpackedmx))
where
unpackedmx = unpackM . transposeM $ mx --transposed list of lists of matrix X
getElement = getResult . getElementByInd (1, 1)
forEachListEvalHypothesis = (\xs -> [evalHypothesis (vector xs 1) theta])
vectorOfEvaluatedHypothesis = packM $ map forEachListEvalHypothesis unpackedmx
costNormalized :: XYContainer -> Theta -> [(NormalizeConst, VariableInd)] -> Double --counts normalized cost for normalize consts and linked to them variables specified in the third argument
costNormalized xyc theta nvs = cost theta xyc + sumNorms nvs
where
sumNorms [] = 0
sumNorms [n] = evalNorms n
sumNorms (n:ns) = evalNorms n + sumNorms ns
evalNorms (norm, var) = norm * (getResult $ getElementByInd (1, var) theta)
costNormalized' :: Int -> Theta -> XYContainer -> [(NormalizeConst, VariableInd)] -> Double
costNormalized' varOfDer tht (XYContainer (s, x, y, basic, ext, newF, sc)) ns =
(cost' varOfDer tht (XYContainer (s, x, y, basic, ext, newF, sc))) + sumNorms ns
where
sumNorms [] = 0
sumNorms [nv] = getNorm nv
sumNorms (nv:nvs) = getNorm nv + sumNorms nvs
getNorm (norm, var) = norm
evalHypothesis :: TrainingSet -> Theta -> Double
evalHypothesis x theta = getResult $ getElementByInd (1, 1) (theta * x)
getTrainingSet :: Int -> X -> TrainingSet
getTrainingSet = getRow
getAllTrainingSetsOfOneFeature :: Int -> X -> Matrix Double
getAllTrainingSetsOfOneFeature i mx = getColumn i mx
thetaInit :: XYContainer -> Double -> Theta
thetaInit (XYContainer (xs, _, _, _, _, _, _)) initval = vector (replicate (length xs) initval) 0
allBut_ :: Int -> [a] -> [a]
allBut_ _ [] = []
allBut_ 1 (x:xs) = allBut_ 0 xs
allBut_ n (x:xs) = x:(allBut_ (n-1) xs)
avg :: (Num a, Real a, Fractional a) => [a] -> a
avg xs = realToFrac (sum xs) / genericLength xs
range :: (Num a, Ord a) => [a] -> a
range xs = maximum xs - minimum xs
unJust :: Maybe a -> a
unJust (Just x) = x
inJust Nothing = error " "
| kanes115/Regressions | src/Regressions.hs | bsd-3-clause | 15,184 | 0 | 19 | 4,964 | 3,592 | 2,001 | 1,591 | 180 | 3 |
{-# Language BangPatterns #-}
module Network.Openflow.Ethernet.Generator where
import Network.Openflow.Ethernet.Frame
import Network.Openflow.Misc
import Network.Openflow.StrictPut
import Data.Word
import Data.Monoid
import qualified Data.ByteString as BS
import Blaze.ByteString.Builder --import Data.ByteString.Lazy.Builder
-- TODO: possibly, there is a way to calculate crc32 on the fly,
-- without generating the actual bytestring
putEthernetFrame :: EthernetFrame a => a -> PutM ()
putEthernetFrame x = putFrame
where
putFrame = do
putMAC (dstMacAddress x)
putMAC (srcMacAddress x)
putVLAN (vlanID x)
putWord16be (typeCode x)
putPayload x
putWord32be 0 -- FIXME: CRC!
{-# INLINE putFrame #-}
-- FIXME: fix checksum calculation
--putCRC32 = putWord32be 0 -- (crc32 bs)
-- {-# INLINE putCRC32 #-}
{-# INLINE putEthernetFrame #-}
buildEthernetFrame :: EthernetFrame a => a -> Builder
buildEthernetFrame x =
buildMAC (dstMacAddress x)
<> buildMAC (srcMacAddress x)
<> buildVLAN (vlanID x)
<> fromWord16be (typeCode x)
<> fromByteString pl
<> fromWord32be 0
where pl = runPutToByteString 32768 (putPayload x) -- FIXME use only Builder
makeEthernetFrame :: EthernetFrame a => a -> BS.ByteString
makeEthernetFrame = runPutToByteString 2048 . putEthernetFrame
{-# INLINABLE makeEthernetFrame #-}
{-# DEPRECATED makeEthernetFrame "use putEthernetFrame instead" #-}
putVLAN :: Maybe Word16 -> PutM ()
putVLAN Nothing = return ()
putVLAN (Just vlan) = putWord16be 0x8100 >> putWord16be vlan
{-# INLINE putVLAN #-}
buildVLAN :: Maybe Word16 -> Builder
buildVLAN Nothing = mempty
buildVLAN (Just vlan) = fromWord16be 0x8100 <> fromWord16be vlan
{-# INLINE buildVLAN #-}
putEmptyPayload :: Int -> PutM ()
putEmptyPayload = putZeros
{-# INLINE putEmptyPayload #-}
| ARCCN/hcprobe | src/Network/Openflow/Ethernet/Generator.hs | bsd-3-clause | 1,883 | 0 | 12 | 365 | 414 | 213 | 201 | 43 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell #-}
module API.IB.Data where
import Control.Applicative
import Control.Lens (makeLenses)
import Control.Monad
import Currency
import Data.Attoparsec.ByteString.Char8
import Data.ByteString (ByteString)
import qualified Data.IntMap as IntMap (lookup)
import Data.List.Split (splitOn)
import Data.Map (Map)
import qualified Data.Map as Map (empty, fromList,
lookup)
import Data.Maybe
import Data.Time
import Data.Time.Zones
import API.IB.Constant
import API.IB.Enum
import API.IB.Parse
import API.IB.Util
-- -----------------------------------------------------------------------------
-- Types
type IBTagValues = Map String String
parseTagValues :: Parser IBTagValues
parseTagValues = do
count' <- parseIntField
Map.fromList <$> replicateM count' ((,) <$> parseStringField <*> parseStringField)
-- -----------------------------------------------------------------------------
-- Request
data IBRequest =
RequestMarketData
{ _reqTickerId :: Int
, _reqContract :: IBContract
, _reqTickerList :: [IBGenericTickType]
, _reqSnapshotFlag :: Bool
}
| CancelMarketData
{_reqTickerId :: Int
}
| PlaceOrder
{ _reqOrderId :: ByteString
, _reqContract :: IBContract
, _reqOrder :: IBOrder
}
| CancelOrder
{ _reqOrderId :: ByteString
}
| RequestOpenOrders
| RequestAccountData
{ _reqSubscribe :: Bool
, _reqAccount :: String
}
| RequestExecutions
{ _reqRequestId :: Int
, _reqExecutionFilter :: IBExecutionFilter
}
| RequestIds
{ _reqNumIds :: Int
}
| RequestContractData
{ _reqRequestId :: Int
, _reqContract :: IBContract
}
| RequestAutoOpenOrders
{ _reqAutoBind :: Bool
}
| RequestAllOpenOrders
| RequestManagedAccounts
| RequestHistoricalData
{ _reqTickerId :: Int
, _reqContract :: IBContract
, _reqEndDateTime :: LocalTime
, _reqDuration :: IBDuration
, _reqBarSize :: Int
, _reqBarBasis :: IBBarBasis
, _reqRegularTradingHours :: Bool
, _reqFormatDate :: IBFormatDate
}
| CancelHistoricalData
{ _reqTickerId :: Int
}
| RequestCurrentTime
| RequestRealTimeBars
{ _reqTickerId :: Int
, _reqContract :: IBContract
, _reqBarSize :: Int
, _reqBarBasis :: IBBarBasis
, _reqRegularTradingHours :: Bool
}
| CancelRealTimeBars
{ _reqTickerId :: Int
}
| RequestGlobalCancel
| RequestMarketDataType
{ _reqMarketDataType :: IBMarketDataType
}
| RequestPositions
| RequestAccountSummary
{ _reqRequestId :: Int
, _reqGroup :: IBGroup
, _reqTags :: IBTags
}
| CancelAccountSummary
{ _req :: Int
}
| CancelPositions
deriving Show
-- -----------------------------------------------------------------------------
-- Response
data IBHistoricalDataItem = IBHistoricalDataItem
{ _hdiDate :: Day
, _hdiTime :: TimeOfDay
, _hdiOpen :: Double
, _hdiHigh :: Double
, _hdiLow :: Double
, _hdiClose :: Double
, _hdiVolume :: Int
, _hdiWAP :: Double
, _hdiHasGaps :: Bool
, _hdiBarCount :: Int
}
deriving Show
data IBResponse =
Connection
{ _connServerVersion :: Int
, _connServerTime :: LocalTime
, _connServerTimeZoneDesc :: String
, _connServerTimeZone :: Maybe TZ
}
| TickPrice
{ _tpTickerId :: Int
, _tpTickType :: IBTickType
, _tpPrice :: Double
, _tpCanAutoExecute :: Bool
}
| TickSize
{ _tsTickerId :: Int
, _tsTickType :: IBTickType
, _tsSize :: Int
}
| OrderStatus
{ _osOrderId :: ByteString
, _osOrderStatus :: IBOrderStatus
, _osFilled :: Int
, _osRemaining :: Int
, _osAvgFillPrice :: Double
, _osPermId :: Int
, _osParentId :: Int
, _osLastFillPrice :: Double
, _osClientId :: Int
, _osWhyHeld :: IBOrderWhyHeld
}
| Error
{ _errId :: Int
, _errCode :: Int
, _errDesc :: String
}
| OpenOrder
{ _ooOrderId :: ByteString
, _ooContract :: IBContract
, _ooOrder :: IBOrder
, _ooOrderState :: IBOrderState
}
| HistoricalData
{ _hdRequestId :: Int
, _hdItems :: [IBHistoricalDataItem]
}
| RealTimeBar
{ _rtbReqId :: Int
, _rtbTime :: UTCTime -- Int
, _rtbOpen :: Double
, _rtbHigh :: Double
, _rtbLow :: Double
, _rtbClose :: Double
, _rtbVolume :: Int
, _rtbWAP :: Double
, _rtbCount :: Int
}
| NextValidId
{ _nvId :: Int
}
| ContractData
{ _cdReqId :: Int
, _cdContractDetails :: IBContractDetails
}
| ContractDataEnd
{ _cdReqId :: Int
}
| ManagedAccounts
{ _maAccounts :: [String]
}
| TickGeneric
{ _tgTickerId :: Int
, _tgTickType :: IBTickType
, _tgValue :: Double
}
| TickString
{ _tsTickerId :: Int
, _tsTickType :: IBTickType
, _tsValue :: String
}
| TickTime
{ _tsTickerId :: Int
, _tsTickType :: IBTickType
, _tsDateTime :: UTCTime
}
| CurrentTime
{ _ctDateTime :: UTCTime
}
| Position
{ _posAccount :: String
, _posContract :: IBContract
, _posPosition :: Int
, _posAvgCost :: Double
}
| PositionEnd
| AccountSummary
{ _asReqId :: Int
, _asAccount :: String
, _asTag :: IBTag
, _asValue :: String
, _asCurrency :: Currency
}
| AccountSummaryEnd
{ _asReqId :: Int
}
| OpenOrderEnd
| AccountValue
{ _avTag :: IBTag
, _avValue :: String
, _avCurrency :: Maybe Currency
, _avAccount :: ByteString
}
| PortfolioValue
{ _pvContract :: IBContract
, _pvPosition :: Int
, _pvMarketPrice :: Double
, _pvMarketValue :: Double
, _pvAverageCost :: Double
, _pvUnrealisedPnL :: Double
, _pvRealisedPnL :: Double
, _pvAccount :: String
}
| AccountUpdateTime
{ _acUpdateTime :: TimeOfDay
}
| ExecutionData
{ _exReqId :: Int
, _exContract :: IBContract
, _exExecution :: IBExecution
}
| ExecutionDataEnd
{ _exReqId :: Int
}
| TickSnapshotEnd
{ _tssReqId :: Int
}
| MarketDataType
{ _mdtReqId :: Int
, _mdtMarketDataType :: IBMarketDataType
}
| CommissionReport
{ _crCommissionReport :: IBCommissionReport
}
| AccountDownloadEnd
{ _acAccount :: String
}
deriving Show
type IBResponses = Map IBResponseType (Parser IBResponse)
responses :: IBResponses
responses = Map.fromList $
[(TickPriceT,parseTickPrice),
(TickSizeT,parseTickSize),
(OrderStatusT,parseOrderStatus),
(ErrorMessageT,parseError),
(OpenOrderT,parseOpenOrder),
(NextValidIdT,parseNextValidId),
(ContractDataT,parseContractData),
(ContractDataEndT,parseContractDataEnd),
(ManagedAccountsT,parseManagedAccounts),
(HistoricalDataT,parseHistoricalData),
(TickGenericT,parseTickGeneric),
(TickStringT,parseTickString),
(CurrentTimeT,parseCurrentTime),
(RealTimeBarT,parseRealTimeBar),
(PositionT,parsePosition),
(PositionEndT,parsePositionEnd),
(AccountSummaryT,parseAccountSummary),
(AccountSummaryEndT,parseAccountSummaryEnd),
(OpenOrderEndT,parseOpenOrderEnd),
(AccountValueT,parseAccountValue),
(PortfolioValueT,parsePortfolioValue),
(AccountUpdateTimeT,parseAccountUpdateTime),
(ExecutionDataT,parseExecutionData),
(ExecutionDataEndT,parseExecutionDataEnd),
(TickSnapshotEndT,parseTickSnapshotEnd),
(MarketDataTypeT,parseMarketDataType),
(CommissionReportT,parseCommissionReport),
(AccountDownloadEndT,parseAccountDownloadEnd)
]
parseIBResponse :: Parser IBResponse
parseIBResponse =
parseTypedResponses <|>
parseConnection
parseResponseType :: Parser Int
parseResponseType = parseIntField
parseTypedResponses :: Parser IBResponse
parseTypedResponses = do
i <- parseResponseType
case IntMap.lookup i ibResponseTypesM' of
Nothing -> fail ""
Just t -> fromMaybe (fail "") (Map.lookup t responses)
parseConnection :: Parser IBResponse
parseConnection = do
sv <- parseField decimal
d <- parseDayYYYYMMDD "" <* skipSpace
t <- parseTimeOfDayHHMMSS ":" <* skipSpace
tz <- parseStringField
return $ Connection sv (LocalTime d t) tz Nothing
parseVersion :: Parser Int
parseVersion = parseIntField
parseTickPrice :: Parser IBResponse
parseTickPrice = do
v <- parseVersion
tid <- parseIntField
tt <- parseField parseIBTickType
-- let stt = Map.lookup tt $ Map.fromList [(Bid,BidSize),(Ask,AskSize),(Last,LastSize)]
p <- fromMaybe 0 <$> parseMaybeDoubleField
_ <- if v >= 2 then parseIntField else return 0
c <- if v >= 3 then parseBoolBinaryField else return False
return $ TickPrice tid tt p c -- (maybe [] (\stt' -> [TickSize tid stt' s]) stt) -- looks like a separate TickSize is always sent
parseTickSize :: Parser IBResponse
parseTickSize = do
_ <- parseVersion
TickSize <$>
parseIntField <*>
parseField parseIBTickType <*>
parseIntField
parseOrderStatus :: Parser IBResponse
parseOrderStatus = do
v <- parseVersion
OrderStatus <$>
parseByteStringField <*>
parseField parseIBOrderStatus <*>
parseIntField <*>
parseIntField <*>
(fromMaybe 0 <$> parseMaybeDoubleField) <*>
(if v >= 2 then parseIntField else return 0) <*>
(if v >= 3 then parseIntField else return 0) <*>
(if v >= 4 then fromMaybe 0 <$> parseMaybeDoubleField else return 0.0) <*>
(if v >= 5 then parseIntField else return 0) <*>
(if v >= 6
then parseField parseIBOrderWhyHeld <|> (return NoReason <* parseEmptyField)
else return NoReason)
parseError :: Parser IBResponse
parseError = do
_ <- parseVersion
Error <$>
parseSignedIntField <*>
parseIntField <*>
parseStringField
parseOpenOrder :: Parser IBResponse
parseOpenOrder = do
v <- parseVersion
orderId' <- parseByteStringField
contract <-
bConId newIBContract
>>= bConSymbol
>>= bConSecType
>>= bConExpiry
>>= bConStrike
>>= bConRight
>>= when' (v>=32) bConMultiplier
>>= bConExchange
>>= bConCurrency
>>= bConLocalSymbol
>>= when' (v>=32) bConTradingClass
(order,contract') <- parseIBOrder contract
orderState <- parseIBOrderState
return $ OpenOrder orderId' contract' order{_orderId = orderId'} orderState
parseNextValidId :: Parser IBResponse
parseNextValidId = do
_ <- parseVersion
NextValidId <$> parseIntField
parseContractData :: Parser IBResponse
parseContractData = do
_ <- parseVersion
reqId' <- parseIntField
contract' <-
bConSymbol newIBContract
>>= bConSecType
>>= bConExpiry
>>= bConStrike
>>= bConRight
>>= bConExchange
>>= bConCurrency
>>= bConLocalSymbol
cdMarketName' <- parseStringField
contract'' <- bConTradingClass contract' >>= bConId
cdMinTick' <- parseDoubleField
contract''' <- bConMultiplier contract''
cdOrderTypes' <- parseStringField
cdValidExchanges' <- parseStringField
cdPriceMagnifier' <- parseIntField
cdUnderConId' <- parseIntField
cdLongName' <- parseStringField
contract'''' <- bConPrimaryExch contract'''
cdContractMonth' <- parseStringField
cdIndustry' <- parseStringField
cdCategory' <- parseStringField
cdSubCategory' <- parseStringField
cdTimeZoneId' <- parseStringField
cdTradingHours' <- parseStringField
cdLiquidHours' <- parseStringField
cdEvRule' <- parseStringField
cdEvMultiplier' <- parseDoubleField'
numSecIds <- parseIntField
secIdsList <- count numSecIds $ (,) <$> parseStringField <*> parseStringField
let
contractDetails' = newIBContractDetails
{ _cdSummary = contract''''
, _cdMarketName = cdMarketName'
, _cdMinTick = cdMinTick'
, _cdPriceMagnifier = cdPriceMagnifier'
, _cdOrderTypes = cdOrderTypes'
, _cdValidExchanges = cdValidExchanges'
, _cdUnderConId = cdUnderConId'
, _cdLongName = cdLongName'
, _cdContractMonth = cdContractMonth'
, _cdIndustry = cdIndustry'
, _cdCategory = cdCategory'
, _cdSubCategory = cdSubCategory'
, _cdTimeZoneId = cdTimeZoneId'
, _cdTradingHours = cdTradingHours'
, _cdLiquidHours = cdLiquidHours'
, _cdEvRule = cdEvRule'
, _cdEvMultiplier = cdEvMultiplier'
, _cdSecIds = Map.fromList secIdsList
}
return $ ContractData reqId' contractDetails'
parseContractDataEnd :: Parser IBResponse
parseContractDataEnd = do
_ <- parseVersion
ContractDataEnd <$>
parseIntField
parseManagedAccounts :: Parser IBResponse
parseManagedAccounts = do
_ <- parseVersion
(ManagedAccounts . splitOn ",") <$> parseStringField
parseHistoricalData :: Parser IBResponse
parseHistoricalData = do
_ <- parseVersion
reqid <- parseIntField
_ <- parseStringField
_ <- parseStringField
items <- parseIntField
HistoricalData reqid <$> count items parseHistoricalDataItem
parseHistoricalDataItem :: Parser IBHistoricalDataItem
parseHistoricalDataItem =
IBHistoricalDataItem <$>
(parseDayYYYYMMDD "" <* skipSpace) <*>
(parseTimeOfDayHHMMSS ":" <* char sepC) <*>
parseDoubleField <*>
parseDoubleField <*>
parseDoubleField <*>
parseDoubleField <*>
parseSignedIntField <*>
parseSignedDoubleField <*>
parseBoolStringField <*>
parseSignedIntField
parseTickGeneric :: Parser IBResponse
parseTickGeneric = do
_ <- parseVersion
TickGeneric <$>
parseIntField <*>
parseField parseIBTickType <*>
parseDoubleField
parseTickString :: Parser IBResponse
parseTickString = do
_ <- parseVersion
i <- parseIntField
t <- parseField parseIBTickType
case t of
LastTimestamp -> TickTime i t <$> parseUTCTimeField
_ -> TickString i t <$> parseStringField
parseCurrentTime :: Parser IBResponse
parseCurrentTime = do
_ <- parseVersion
CurrentTime <$> parseUTCTimeField
parseRealTimeBar :: Parser IBResponse
parseRealTimeBar = do
_ <- parseVersion
RealTimeBar <$>
parseIntField <*>
parseUTCTimeField <*> -- parseIntField <*>
parseDoubleField <*>
parseDoubleField <*>
parseDoubleField <*>
parseDoubleField <*>
parseIntField <*>
parseDoubleField <*>
parseIntField
parsePosition :: Parser IBResponse
parsePosition = do
v <- parseVersion
Position <$>
parseStringField <*>
(bConId newIBContract
>>= bConSymbol
>>= bConSecType
>>= bConExpiry
>>= bConStrike
>>= bConRight
>>= bConMultiplier
>>= bConExchange
>>= bConCurrency
>>= bConLocalSymbol
>>= when' (v>=2) bConTradingClass) <*>
parseSignedIntField <*>
if v >= 3 then parseDoubleField else return 0.0
parsePositionEnd :: Parser IBResponse
parsePositionEnd = do
_ <- parseVersion
return PositionEnd
parseAccountSummary :: Parser IBResponse
parseAccountSummary = do
_ <- parseVersion
AccountSummary <$>
parseIntField <*>
parseStringField <*>
parseField parseIBTag <*>
parseStringField <*>
parseField parseStringToEnum
parseAccountSummaryEnd :: Parser IBResponse
parseAccountSummaryEnd = do
_ <- parseVersion
AccountSummaryEnd <$>
parseIntField
parseOpenOrderEnd :: Parser IBResponse
parseOpenOrderEnd = do
_ <- parseVersion
return OpenOrderEnd
parseAccountDownloadEnd :: Parser IBResponse
parseAccountDownloadEnd = do
_ <- parseVersion
AccountDownloadEnd <$>
parseStringField
parseAccountValue :: Parser IBResponse
parseAccountValue = do
v <- parseVersion
AccountValue <$>
parseField parseIBTag <*>
parseStringField <*>
parseMaybeEmptyField stringToEnum <*>
if v >= 2 then parseByteStringField else return ""
parsePortfolioValue :: Parser IBResponse
parsePortfolioValue = do
v <- parseVersion
PortfolioValue <$>
parseContract' v <*>
parseSignedIntField <*>
parseDoubleField <*>
parseDoubleField <*>
(if v >= 3 then parseDoubleField else return 0.0) <*>
(if v >= 3 then parseDoubleField else return 0.0) <*>
(if v >= 3 then parseDoubleField else return 0.0) <*>
(if v >= 4 then parseStringField else return "")
where
parseContract' v =
(if v>=6 then bConId newIBContract >>= bConSymbol else bConSymbol newIBContract)
>>= bConSecType
>>= bConExpiry
>>= bConStrike
>>= bConRight
>>= when' (v>=7) (bConMultiplier >=> bConPrimaryExch)
>>= bConCurrency
>>= bConLocalSymbol
>>= when' (v>=8) bConTradingClass
parseAccountUpdateTime :: Parser IBResponse
parseAccountUpdateTime = do
_ <- parseVersion
AccountUpdateTime <$>
parseField (parseTimeOfDayHHMM ":")
parseExecutionData :: Parser IBResponse
parseExecutionData = do
v <- parseVersion
reqId' <- if v >= 7 then parseSignedIntField else return (-1)
execOrderId' <- parseByteStringField
contract' <-
bConId newIBContract
>>= bConSymbol
>>= bConSecType
>>= bConExpiry
>>= bConStrike
>>= bConRight
>>= when' (v>=9) bConMultiplier
>>= bConExchange
>>= bConCurrency
>>= bConLocalSymbol
>>= when' (v >=10) bConTradingClass
let execution = newIBExecution
execId' <- parseByteStringField
--execTime' <- parseStringField
execDay' <- parseDayYYYYMMDD "" <* skipSpace
execTime' <- parseTimeOfDayHHMMSS ":" <* char sepC
execAcctNumber' <- parseStringField
execExchange' <- parseStringField
--execSide' <- parseStringField
execSide' <- parseField parseIBExecutionSide
execShares' <- parseIntField
execPrice' <- parseDoubleField
execPermId' <- parseIntField
execClientId' <- parseIntField
execLiquidation' <- parseIntField
execCumQty' <- if v >= 6 then parseIntField else return $ _execCumQty execution
execAvgPrice' <- if v >= 6 then parseDoubleField else return $ _execAvgPrice execution
execOrderRef' <- if v >= 8 then parseStringField else return $ _execOrderRef execution
execEvRule' <- if v >= 9 then parseStringField else return $ _execEvRule execution
execEvMultiplier' <- if v >= 9 then parseDoubleField' else return $ _execEvMultiplier execution
let execution' = execution {
_execOrderId = execOrderId'
, _execClientId = execClientId'
, _execId = execId'
, _execTime = LocalTime execDay' execTime'
, _execAcctNumber = execAcctNumber'
, _execExchange = execExchange'
, _execSide = execSide'
, _execShares = execShares'
, _execPrice = execPrice'
, _execPermId = execPermId'
, _execLiquidation = execLiquidation'
, _execCumQty = execCumQty'
, _execAvgPrice = execAvgPrice'
, _execOrderRef = execOrderRef'
, _execEvRule = execEvRule'
, _execEvMultiplier = execEvMultiplier'
}
return $ ExecutionData reqId' contract' execution'
parseExecutionDataEnd :: Parser IBResponse
parseExecutionDataEnd = do
_ <- parseVersion
ExecutionDataEnd <$>
parseIntField
parseTickSnapshotEnd :: Parser IBResponse
parseTickSnapshotEnd = do
_ <- parseVersion
TickSnapshotEnd <$>
parseIntField
parseMarketDataType :: Parser IBResponse
parseMarketDataType = do
_ <- parseVersion
MarketDataType <$>
parseIntField <*>
parseField parseIBMarketDataType
parseCommissionReport :: Parser IBResponse
parseCommissionReport = do
_ <- parseVersion
CommissionReport <$>
parseIBCommissionReport
-- -----------------------------------------------------------------------------
-- Contract
data IBContract = IBContract
{ _conId :: Int
, _conSymbol :: String
, _conSecType :: IBSecurityType -- String
, _conExpiry :: String
, _conStrike :: Double
, _conRight :: String
, _conMultiplier :: String
, _conExchange :: String
, _conCurrency :: String
, _conLocalSymbol :: String
, _conTradingClass :: String
, _conPrimaryExch :: String -- not SMART
, _conIncludeExpired :: Bool -- False for orders
, _conSecIdType :: String -- CUSIP;SEDOL;ISIN;RIC
, _conSecId :: String
, _conComboLegsDescrip :: String -- received in open order version 14 and up for all combos
, _conComboLegs :: [IBComboLeg]
, _conUnderComp :: Maybe IBUnderComp -- delta-neutral
} deriving Show
newIBContract :: IBContract
newIBContract = IBContract
{ _conId = 0
, _conSymbol = ""
, _conSecType = IBForex
, _conExpiry = ""
, _conStrike = 0.0
, _conRight = ""
, _conMultiplier = ""
, _conExchange = ""
, _conCurrency = ""
, _conLocalSymbol = ""
, _conTradingClass = ""
, _conPrimaryExch = ""
, _conIncludeExpired = False
, _conSecIdType = ""
, _conSecId = ""
, _conComboLegsDescrip = ""
, _conComboLegs = []
, _conUnderComp = Nothing
}
bConId :: IBContract -> Parser IBContract
bConId contract = parseIntField >>= \f -> return contract {_conId = f}
bConSymbol :: IBContract -> Parser IBContract
bConSymbol contract = parseStringField >>= \f -> return contract {_conSymbol = f}
bConSecType :: IBContract -> Parser IBContract
bConSecType contract = parseField parseIBSecurityType >>= \f -> return contract {_conSecType = f}
bConExpiry :: IBContract -> Parser IBContract
bConExpiry contract = parseStringField >>= \f -> return contract {_conExpiry = f}
bConStrike :: IBContract -> Parser IBContract
bConStrike contract = parseDoubleField >>= \f -> return contract {_conStrike= f}
bConRight :: IBContract -> Parser IBContract
bConRight contract = parseStringField >>= \f -> return contract {_conRight = f}
bConMultiplier :: IBContract -> Parser IBContract
bConMultiplier contract = parseStringField >>= \f -> return contract {_conMultiplier = f}
bConExchange :: IBContract -> Parser IBContract
bConExchange contract = parseStringField >>= \f -> return contract {_conExchange = f}
bConCurrency :: IBContract -> Parser IBContract
bConCurrency contract = parseStringField >>= \f -> return contract {_conCurrency = f}
bConLocalSymbol :: IBContract -> Parser IBContract
bConLocalSymbol contract = parseStringField >>= \f -> return contract {_conLocalSymbol = f}
bConTradingClass :: IBContract -> Parser IBContract
bConTradingClass contract = parseStringField >>= \f -> return contract {_conTradingClass = f}
bConPrimaryExch :: IBContract -> Parser IBContract
bConPrimaryExch contract = parseStringField >>= \f -> return contract {_conPrimaryExch = f}
parseIBContractComboLegs :: IBContract -> Parser IBContract
parseIBContractComboLegs contract = do
conComboLegsDescrip' <- parseStringField
conComboLegsCount <- parseIntField
conComboLegs' <- replicateM conComboLegsCount parseIBComboLeg
return contract
{ _conComboLegsDescrip = conComboLegsDescrip'
, _conComboLegs = conComboLegs'
}
parseIBContractUnderComp :: IBContract -> Parser IBContract
parseIBContractUnderComp contract = do
under' <- parseBoolBinaryField
conUnderComp' <- if under'
then
Just <$> parseIBUnderComp
else
return Nothing
return contract{_conUnderComp = conUnderComp'}
-- -----------------------------------------------------------------------------
-- Combo leg
data IBComboLeg = IBComboLeg
{ _comConId :: Int
, _comRatio :: Int
, _comAction :: String -- BUY/SELL/SSHORT/SSHORTX
, _comExchange :: String
, _comOpenClose :: Int
-- for stock legs when doing short sale
, _comShortSaleSlot :: Int -- 1 = clearing broker, 2 = third party
, _comDesignatedLocation :: String
, _comExemptCode :: Int
} deriving Show
parseIBComboLeg :: Parser IBComboLeg
parseIBComboLeg =
IBComboLeg <$>
parseIntField <*>
parseIntField <*>
parseStringField <*>
parseStringField <*>
parseIntField <*>
parseIntField <*>
parseStringField <*>
parseIntField
-- -----------------------------------------------------------------------------
-- Under comp - TBC
data IBUnderComp = IBUnderComp
{ _ucConId :: Int
, _ucDelta :: Double
, _ucPrice :: Double
} deriving Show
parseIBUnderComp :: Parser IBUnderComp
parseIBUnderComp =
IBUnderComp <$>
parseIntField <*>
parseSignedDoubleField <*>
parseDoubleField
-- -----------------------------------------------------------------------------
-- Contract details
data IBContractDetails = IBContractDetails
{ _cdSummary :: IBContract
, _cdMarketName :: String
, _cdMinTick :: Double
, _cdPriceMagnifier :: Int
, _cdOrderTypes :: String
, _cdValidExchanges :: String
, _cdUnderConId :: Int
, _cdLongName :: String
, _cdContractMonth :: String
, _cdIndustry :: String
, _cdCategory :: String
, _cdSubCategory :: String
, _cdTimeZoneId :: String
, _cdTradingHours :: String
, _cdLiquidHours :: String
, _cdEvRule :: String
, _cdEvMultiplier :: Double
, _cdSecIds :: IBTagValues
} deriving Show
newIBContractDetails :: IBContractDetails
newIBContractDetails = IBContractDetails
{ _cdSummary = newIBContract
, _cdMarketName = ""
, _cdMinTick = 0
, _cdPriceMagnifier = 0
, _cdOrderTypes = ""
, _cdValidExchanges = ""
, _cdUnderConId = 0
, _cdLongName = ""
, _cdContractMonth = ""
, _cdIndustry = ""
, _cdCategory = ""
, _cdSubCategory = ""
, _cdTimeZoneId = ""
, _cdTradingHours = ""
, _cdLiquidHours = ""
, _cdEvRule = ""
, _cdEvMultiplier = 0
, _cdSecIds = Map.empty
}
-- -----------------------------------------------------------------------------
-- Combo leg
data IBOrderComboLeg = IBOrderComboLeg
{ _oclPrice :: Double
} deriving Show
parseIBOrderComboLeg :: Parser IBOrderComboLeg
parseIBOrderComboLeg =
IBOrderComboLeg <$>
parseDoubleField'
type IBOrderComboLegs = [IBOrderComboLeg]
-- -----------------------------------------------------------------------------
-- Order
data IBOrder = IBOrder
-- Main order fields
{ _orderId :: ByteString
, _orderClientId :: Int
, _orderPermId :: Maybe Int -- Populated in open order message (permanent id for subitted and open orders, not used for new order?)
, _orderAction :: IBOrderAction -- BUY, SELL, ?
, _orderTotalQuantity :: Int
, _orderType :: IBOrderType -- e.g. MKT, LMT
, _orderLmtPrice :: Maybe Double
, _orderAuxPrice :: Maybe Double
-- Extended order fields
, _orderTif :: IBOrderTimeInForce -- "Time in Force" - DAY, GTC, etc.
, _orderOcaGroup :: Maybe String -- one cancels all group name
, _orderOcaType :: Maybe IBOrderOCAType -- 1 = CANCEL_WITH_BLOCK, 2 = REDUCE_WITH_BLOCK, 3 = REDUCE_NON_BLOCK
, _orderRef :: String
, _orderTransmit :: Bool -- if false, order will be created but not transmited
, _orderParentId :: Maybe Int -- Parent order Id, to associate Auto STP or TRAIL orders with the original order.
, _orderBlockOrder :: Bool
, _orderSweepToFill :: Bool
, _orderDisplaySize :: Maybe Int -- TBC
, _orderTriggerMethod :: IBOrderTriggerMethod -- 0=Default, 1=Double_Bid_Ask, 2=Last, 3=Double_Last, 4=Bid_Ask, 7=Last_or_Bid_Ask, 8=Mid-point
, _orderOutsideRth :: Bool
, _orderHidden :: Bool
, _orderGoodAfterTime :: Maybe String -- FORMAT: 20060505 08:00:00 {time zone}
, _orderGoodTillDate :: Maybe String -- FORMAT: 20060505 08:00:00 {time zone}
, _orderOverridePercentageConstraints :: Bool
, _orderRule80A :: Maybe IBOrderRule80A -- Individual = 'I', Agency = 'A', AgentOtherMember = 'W', IndividualPTIA = 'J', AgencyPTIA = 'U', AgentOtherMemberPTIA = 'M', IndividualPT = 'K', AgencyPT = 'Y', AgentOtherMemberPT = 'N'
, _orderAllOrNone :: Bool
, _orderMinQty :: Maybe Int
, _orderPercentOffset :: Maybe Double -- REL orders only; specify the decimal, e.g. .04 not 4
, _orderTrailStopPrice :: Maybe Double -- for TRAILLIMIT orders only
, _orderTrailingPercent :: Maybe Double -- specify the percentage, e.g. 3, not .03
-- Financial advisors only
, _orderFAGroup :: String
, _orderFAProfile :: String
, _orderFAMethod :: String
, _orderFAPercentage :: String
-- Institutional orders only
, _orderOpenClose :: IBOrderOpenClose -- O=Open, C=Close
, _orderOrigin :: IBOrderOrigin -- 0=Customer, 1=Firm
, _orderShortSaleSlot :: Maybe IBOrderShortSaleSlot -- 1 if you hold the shares, 2 if they will be delivered from elsewhere. Only for Action="SSHORT
, _orderDesignatedLocation :: Maybe String -- set when slot=2 only.
, _orderExemptCode :: Int -- TBC
-- SMART routing only
, _orderDiscretionaryAmt :: Double
, _orderETradeOnly :: Bool
, _orderFirmQuoteOnly :: Bool
, _orderNBBOPriceCap :: Maybe Double
, _orderOptOutSmartRouting :: Bool
-- Box or vol orders only
, _orderAuctionStrategy :: Maybe IBOrderAuctionStrategy -- 1=AUCTION_MATCH, 2=AUCTION_IMPROVEMENT, 3=AUCTION_TRANSPARENT
-- Box orders only
, _orderStartingPrice :: Maybe Double
, _orderStockRefPrice :: Maybe Double
, _orderDelta :: Maybe Double
-- Pegged to stock or vol orders
, _orderStockRangeLower :: Maybe Double
, _orderStockRangeUpper :: Maybe Double
-- Volatility orders only
, _orderVolatility :: Maybe Double -- Enter percentage not decimal, e.g. 2 not .02
, _orderVolatilityType :: Maybe IBOrderVolatilityType -- 1=daily, 2=annual
, _orderContinuousUpdate :: Maybe Int -- TBC
, _orderReferencePriceType :: Maybe IBOrderRefPriceType -- 1=Bid/Ask midpoint, 2 = BidOrAsk
, _orderDeltaNeutralOrderType :: Maybe String -- TBC
, _orderDeltaNeutralAuxPrice :: Maybe Double
, _orderDeltaNeutralConId :: Maybe Int
, _orderDeltaNeutralSettlingFirm :: Maybe String
, _orderDeltaNeutralClearingAccount :: Maybe String
, _orderDeltaNeutralClearingIntent :: Maybe String
, _orderDeltaNeutralOpenClose :: Maybe IBOrderOpenClose -- TBC
, _orderDeltaNeutralShortSale :: Bool
, _orderDeltaNeutralShortSaleSlot :: Maybe IBOrderShortSaleSlot -- TBC
, _orderDeltaNeutralDesignatedLocation :: Maybe String
-- Combo orders only
, _orderBasisPoints :: Maybe Double -- TBC. EFP orders only, download only
, _orderBasisPointsType :: Maybe Int -- TBC. EFP orders only, download only
-- Scale orders only
, _orderScaleInitLevelSize :: Maybe Int
, _orderScaleSubsLevelSize :: Maybe Int
, _orderScalePriceIncrement :: Maybe Double
, _orderScalePriceAdjustValue :: Maybe Double
, _orderScalePriceAdjustInterval :: Maybe Int
, _orderScaleProfitOffset :: Maybe Double
, _orderScaleAutoReset :: Bool
, _orderScaleInitPosition :: Maybe Int
, _orderScaleInitFillQty :: Maybe Int
, _orderScaleRandomPercent :: Bool
-- Hedge orders only
, _orderHedgeType :: Maybe IBOrderHedgeType -- 'D' - delta, 'B' - beta, 'F' - FX, 'P' - pair
, _orderHedgeParam :: Maybe String -- TBC. beta value for beta hedge (in range 0-1), ratio for pair hedge
-- Clearing info
, _orderAccount :: String -- IB account
, _orderSettlingFirm :: String
, _orderClearingAccount :: String -- True beneficiary of the order
, _orderClearingIntent :: String -- "" (Default), "IB", "Away", "PTA" (PostTrade)
-- Algo orders only
, _orderAlgoStrategy :: Maybe String
, _orderAlgoParams :: IBTagValues
-- What-if
, _orderWhatIf :: Bool
-- Not Held
, _orderNotHeld :: Bool
-- Smart combo routing params
, _orderSmartComboRoutingParams :: IBTagValues
-- Order combo legs
, _orderComboLegs :: IBOrderComboLegs
} deriving Show
newIBOrder :: IBOrder
newIBOrder = IBOrder
{ _orderId = ""
, _orderClientId = 0
, _orderPermId = Nothing
, _orderAction = Buy
, _orderTotalQuantity = 0
, _orderType = Market
, _orderLmtPrice = Nothing
, _orderAuxPrice = Nothing
, _orderTif = Day
, _orderOcaGroup = Nothing
, _orderOcaType = Nothing
, _orderRef = ""
, _orderTransmit = False
, _orderParentId = Nothing
, _orderBlockOrder = False
, _orderSweepToFill = False
, _orderDisplaySize = Nothing
, _orderTriggerMethod = TriggerDefault
, _orderOutsideRth = False
, _orderHidden = False
, _orderGoodAfterTime = Nothing
, _orderGoodTillDate = Nothing
, _orderOverridePercentageConstraints = False
, _orderRule80A = Nothing
, _orderAllOrNone = False
, _orderMinQty = Nothing
, _orderPercentOffset = Nothing
, _orderTrailStopPrice = Nothing
, _orderTrailingPercent = Nothing
, _orderFAGroup = ""
, _orderFAProfile = ""
, _orderFAMethod = ""
, _orderFAPercentage = ""
, _orderOpenClose = OrderOpen
, _orderOrigin = Customer
, _orderShortSaleSlot = Nothing
, _orderDesignatedLocation = Nothing
, _orderExemptCode = -1
, _orderDiscretionaryAmt = 0
, _orderETradeOnly = False
, _orderFirmQuoteOnly = False
, _orderNBBOPriceCap = Nothing
, _orderOptOutSmartRouting = False
, _orderAuctionStrategy = Nothing
, _orderStartingPrice = Nothing
, _orderStockRefPrice = Nothing
, _orderDelta = Nothing
, _orderStockRangeLower = Nothing
, _orderStockRangeUpper = Nothing
, _orderVolatility = Nothing
, _orderVolatilityType = Nothing
, _orderContinuousUpdate = Nothing
, _orderReferencePriceType = Nothing
, _orderDeltaNeutralOrderType = Nothing
, _orderDeltaNeutralAuxPrice = Nothing
, _orderDeltaNeutralConId = Nothing
, _orderDeltaNeutralSettlingFirm = Nothing
, _orderDeltaNeutralClearingAccount = Nothing
, _orderDeltaNeutralClearingIntent = Nothing
, _orderDeltaNeutralOpenClose = Nothing
, _orderDeltaNeutralShortSale = False
, _orderDeltaNeutralShortSaleSlot = Nothing
, _orderDeltaNeutralDesignatedLocation = Nothing
, _orderBasisPoints = Nothing
, _orderBasisPointsType = Nothing
, _orderScaleInitLevelSize = Nothing
, _orderScaleSubsLevelSize = Nothing
, _orderScalePriceIncrement = Nothing
, _orderScalePriceAdjustValue = Nothing
, _orderScalePriceAdjustInterval = Nothing
, _orderScaleProfitOffset = Nothing
, _orderScaleAutoReset = False
, _orderScaleInitPosition = Nothing
, _orderScaleInitFillQty = Nothing
, _orderScaleRandomPercent = False
, _orderHedgeType = Nothing
, _orderHedgeParam = Nothing
, _orderAccount = ""
, _orderSettlingFirm = ""
, _orderClearingAccount = ""
, _orderClearingIntent = ""
, _orderAlgoStrategy = Nothing
, _orderAlgoParams = Map.empty
, _orderWhatIf = False
, _orderNotHeld = False
, _orderSmartComboRoutingParams = Map.empty
, _orderComboLegs = []
}
parseIBOrder :: IBContract -> Parser (IBOrder,IBContract)
parseIBOrder contract = do
let order = newIBOrder
orderAction' <- parseField parseIBOrderAction
orderTotalQuantity' <- parseIntField
orderType' <- parseField parseIBOrderType
orderLmtPrice' <- parseMaybeDoubleField
orderAuxPrice' <- parseMaybeDoubleField
orderTif' <- parseField parseIBOrderTimeInForce
orderOcaGroup' <- parseMaybe parseStringField
orderAccount' <- parseStringField
orderOpenClose' <- parseField parseIBOrderOpenClose
orderOrigin' <- parseField parseIBOrderOrigin
orderRef' <- parseStringField
orderClientId' <- parseIntField
orderPermId' <- Just <$> parseIntField
orderOutsideRth' <- parseBoolBinaryField
orderHidden' <- parseBoolBinaryField
orderDiscretionaryAmt' <- parseDoubleField'
orderGoodAfterTime' <- parseMaybeStringField
_ <- parseStringField
orderFAGroup' <- parseStringField
orderFAProfile' <- parseStringField
orderFAMethod' <- parseStringField
orderFAPercentage' <- parseStringField
orderGoodTillDate' <- parseMaybeStringField
orderRule80A' <- parseMaybe $ parseField parseIBOrderRule80A
orderPercentOffset' <- parseMaybeDoubleField
orderSettlingFirm' <- parseStringField
orderShortSaleSlot' <- parseMaybe $ parseField parseIBOrderShortSaleSlot
orderDesignatedLocation' <- parseMaybeStringField
orderExemptCode' <- parseSignedIntField
orderAuctionStrategy' <- parseMaybe $ parseField parseIBOrderAuctionStrategy
orderStartingPrice' <- parseMaybeDoubleField
orderStockRefPrice' <- parseMaybeDoubleField
orderDelta' <- parseMaybeDoubleField
orderStockRangeLower' <- parseMaybeDoubleField
orderStockRangeUpper' <- parseMaybeDoubleField
orderDisplaySize' <- parseMaybeIntField
orderBlockOrder' <- parseBoolBinaryField
orderSweepToFill' <- parseBoolBinaryField
orderAllOrNone' <- parseBoolBinaryField
orderMinQty' <- parseMaybeIntField
orderOcaType' <- parseMaybe $ parseField parseIBOrderOCAType
orderETradeOnly' <- parseBoolBinaryField
orderFirmQuoteOnly' <- parseBoolBinaryField
orderNBBOPriceCap' <- parseMaybeDoubleField
orderParentId' <- parseMaybeIntField
orderTriggerMethod' <- parseField parseIBOrderTriggerMethod
orderVolatility' <- parseMaybeDoubleField
orderVolatilityType' <- parseMaybe $ parseField parseIBOrderVolatilityType
orderDeltaNeutralOrderType'' <- parseStringField
let dn' = not (null orderDeltaNeutralOrderType'')
let orderDeltaNeutralOrderType' = if dn' then Just orderDeltaNeutralOrderType'' else Nothing
orderDeltaNeutralAuxPrice' <- parseMaybeDoubleField
orderDeltaNeutralConId' <- if dn' then parseMaybeIntField else return $ _orderDeltaNeutralConId order
orderDeltaNeutralSettlingFirm' <- if dn' then parseMaybeStringField else return $ _orderDeltaNeutralSettlingFirm order
orderDeltaNeutralClearingAccount' <- if dn' then parseMaybeStringField else return $ _orderDeltaNeutralClearingAccount order
orderDeltaNeutralClearingIntent' <- if dn' then parseMaybeStringField else return $ _orderDeltaNeutralClearingIntent order
orderDeltaNeutralOpenClose' <- if dn' then parseMaybe (parseField parseIBOrderOpenClose) else return $ _orderDeltaNeutralOpenClose order
orderDeltaNeutralShortSale' <- if dn' then parseBoolBinaryField else return $ _orderDeltaNeutralShortSale order
orderDeltaNeutralShortSaleSlot' <- if dn' then parseMaybe (parseField parseIBOrderShortSaleSlot) else return $ _orderDeltaNeutralShortSaleSlot order
orderDeltaNeutralDesignatedLocation' <- if dn' then parseMaybeStringField else return $ _orderDeltaNeutralDesignatedLocation order
orderContinuousUpdate' <- parseMaybeIntField
orderReferencePriceType' <- parseMaybe $ parseField parseIBOrderRefPriceType
orderTrailStopPrice' <- parseMaybeDoubleField
orderTrailingPercent' <- parseMaybeDoubleField
orderBasisPoints' <- parseMaybeDoubleField
orderBasisPointsType' <- parseMaybeIntField
contract' <- parseIBContractComboLegs contract
orderComboLegsCount' <- parseIntField
orderComboLegs' <- replicateM orderComboLegsCount' parseIBOrderComboLeg
orderSmartComboRoutingParamsCount' <- parseIntField
orderSmartComboRoutingParams' <- if orderSmartComboRoutingParamsCount' > 0 then parseTagValues else return $ _orderSmartComboRoutingParams order
orderScaleInitLevelSize' <- parseMaybeIntField
orderScaleSubsLevelSize' <- parseMaybeIntField
orderScalePriceIncrement' <- parseMaybeDoubleField
let scale' = fmap (>0) orderScalePriceIncrement' == Just True
orderScalePriceAdjustValue' <- if scale' then parseMaybeDoubleField else return $ _orderScalePriceAdjustValue order
orderScalePriceAdjustInterval' <- if scale' then parseMaybeIntField else return $ _orderScalePriceAdjustInterval order
orderScaleProfitOffset' <- if scale' then parseMaybeDoubleField else return $ _orderScaleProfitOffset order
orderScaleAutoReset' <- if scale' then parseBoolBinaryField else return $ _orderScaleAutoReset order
orderScaleInitPosition' <- if scale' then parseMaybeIntField else return $ _orderScaleInitPosition order
orderScaleInitFillQty' <- if scale' then parseMaybeIntField else return $ _orderScaleInitFillQty order
orderScaleRandomPercent' <- if scale' then parseBoolBinaryField else return $ _orderScaleRandomPercent order
orderHedgeType' <- parseMaybe $ parseField parseIBOrderHedgeType
orderHedgeParam' <- if isJust orderHedgeType' then parseMaybeStringField else return $ _orderHedgeParam order
orderOptOutSmartRouting' <- parseBoolBinaryField
orderClearingAccount' <- parseStringField
orderClearingIntent' <- parseStringField
orderNotHeld' <- parseBoolBinaryField
contract'' <- parseIBContractUnderComp contract'
orderAlgoStrategy' <- parseMaybeStringField
orderAlgoParams' <- if isJust orderAlgoStrategy' then parseTagValues else return $ _orderAlgoParams order
orderWhatIf' <- parseBoolBinaryField
return (
order
{ _orderClientId = orderClientId'
, _orderPermId = orderPermId'
, _orderAction = orderAction'
, _orderTotalQuantity = orderTotalQuantity'
, _orderType = orderType'
, _orderLmtPrice = orderLmtPrice'
, _orderAuxPrice = orderAuxPrice'
, _orderTif = orderTif'
, _orderOcaGroup = orderOcaGroup'
, _orderOcaType = orderOcaType'
, _orderRef = orderRef'
--orderTransmit = orderTransmit'
, _orderParentId = orderParentId'
, _orderBlockOrder = orderBlockOrder'
, _orderSweepToFill = orderSweepToFill'
, _orderDisplaySize = orderDisplaySize'
, _orderTriggerMethod = orderTriggerMethod'
, _orderOutsideRth = orderOutsideRth'
, _orderHidden = orderHidden'
, _orderGoodAfterTime = orderGoodAfterTime'
, _orderGoodTillDate = orderGoodTillDate'
--orderOverridePercentageConstraints = orderOverridePercentageConstraints'
, _orderRule80A = orderRule80A'
, _orderAllOrNone = orderAllOrNone'
, _orderMinQty = orderMinQty'
, _orderPercentOffset = orderPercentOffset'
, _orderTrailStopPrice = orderTrailStopPrice'
, _orderTrailingPercent = orderTrailingPercent'
, _orderFAGroup = orderFAGroup'
, _orderFAProfile = orderFAProfile'
, _orderFAMethod = orderFAMethod'
, _orderFAPercentage = orderFAPercentage'
, _orderOpenClose = orderOpenClose'
, _orderOrigin = orderOrigin'
, _orderShortSaleSlot = orderShortSaleSlot'
, _orderDesignatedLocation = orderDesignatedLocation'
, _orderExemptCode = orderExemptCode'
, _orderDiscretionaryAmt = orderDiscretionaryAmt'
, _orderETradeOnly = orderETradeOnly'
, _orderFirmQuoteOnly = orderFirmQuoteOnly'
, _orderNBBOPriceCap = orderNBBOPriceCap'
, _orderOptOutSmartRouting = orderOptOutSmartRouting'
, _orderAuctionStrategy = orderAuctionStrategy'
, _orderStartingPrice = orderStartingPrice'
, _orderStockRefPrice = orderStockRefPrice'
, _orderDelta = orderDelta'
, _orderStockRangeLower = orderStockRangeLower'
, _orderStockRangeUpper = orderStockRangeUpper'
, _orderVolatility = orderVolatility'
, _orderVolatilityType = orderVolatilityType'
, _orderContinuousUpdate = orderContinuousUpdate'
, _orderReferencePriceType = orderReferencePriceType'
, _orderDeltaNeutralOrderType = orderDeltaNeutralOrderType'
, _orderDeltaNeutralAuxPrice = orderDeltaNeutralAuxPrice'
, _orderDeltaNeutralConId = orderDeltaNeutralConId'
, _orderDeltaNeutralSettlingFirm = orderDeltaNeutralSettlingFirm'
, _orderDeltaNeutralClearingAccount = orderDeltaNeutralClearingAccount'
, _orderDeltaNeutralClearingIntent = orderDeltaNeutralClearingIntent'
, _orderDeltaNeutralOpenClose = orderDeltaNeutralOpenClose'
, _orderDeltaNeutralShortSale = orderDeltaNeutralShortSale'
, _orderDeltaNeutralShortSaleSlot = orderDeltaNeutralShortSaleSlot'
, _orderDeltaNeutralDesignatedLocation = orderDeltaNeutralDesignatedLocation'
, _orderBasisPoints = orderBasisPoints'
, _orderBasisPointsType = orderBasisPointsType'
, _orderScaleInitLevelSize = orderScaleInitLevelSize'
, _orderScaleSubsLevelSize = orderScaleSubsLevelSize'
, _orderScalePriceIncrement = orderScalePriceIncrement'
, _orderScalePriceAdjustValue = orderScalePriceAdjustValue'
, _orderScalePriceAdjustInterval = orderScalePriceAdjustInterval'
, _orderScaleProfitOffset = orderScaleProfitOffset'
, _orderScaleAutoReset = orderScaleAutoReset'
, _orderScaleInitPosition = orderScaleInitPosition'
, _orderScaleInitFillQty = orderScaleInitFillQty'
, _orderScaleRandomPercent = orderScaleRandomPercent'
, _orderHedgeType = orderHedgeType'
, _orderHedgeParam = orderHedgeParam'
, _orderAccount = orderAccount'
, _orderSettlingFirm = orderSettlingFirm'
, _orderClearingAccount = orderClearingAccount'
, _orderClearingIntent = orderClearingIntent'
, _orderAlgoStrategy = orderAlgoStrategy'
, _orderAlgoParams = orderAlgoParams'
, _orderWhatIf = orderWhatIf'
, _orderNotHeld = orderNotHeld'
, _orderSmartComboRoutingParams = orderSmartComboRoutingParams'
, _orderComboLegs = orderComboLegs'
},
contract'')
-- -----------------------------------------------------------------------------
-- Order state
data IBOrderState = IBOrderState
{ _osStatus :: IBOrderStatus
, _osInitMargin :: String
, _osMaintMargin :: String
, _osEquityWithLoan :: String
, _osCommission :: Double
, _osMinCommission :: Double
, _osMaxCommission :: Double
, _osCommissionCurrency :: String
, _osWarningText :: String
} deriving Show
newIBOrderState :: IBOrderState
newIBOrderState = IBOrderState
{ _osStatus = Inactive
, _osInitMargin = ""
, _osMaintMargin = ""
, _osEquityWithLoan = ""
, _osCommission = 0.0
, _osMinCommission = 0.0
, _osMaxCommission = 0.0
, _osCommissionCurrency = ""
, _osWarningText = ""
}
parseIBOrderState :: Parser IBOrderState
parseIBOrderState =
IBOrderState <$>
parseField parseIBOrderStatus <*>
parseStringField <*>
parseStringField <*>
parseStringField <*>
parseDoubleField' <*>
parseDoubleField' <*>
parseDoubleField' <*>
parseStringField <*>
parseStringField
-- -----------------------------------------------------------------------------
-- Execution
data IBExecution = IBExecution
{ _execOrderId :: ByteString
, _execClientId :: Int
, _execId :: ByteString
, _execTime :: LocalTime --String
, _execAcctNumber :: String
, _execExchange :: String
, _execSide :: IBExecutionSide --String
, _execShares :: Int
, _execPrice :: Double
, _execPermId :: Int
, _execLiquidation :: Int
, _execCumQty :: Int
, _execAvgPrice :: Double
, _execOrderRef :: String
, _execEvRule :: String
, _execEvMultiplier :: Double
} deriving Show
newIBExecution :: IBExecution
newIBExecution = IBExecution
{ _execOrderId = ""
, _execClientId = 0
, _execId = ""
, _execTime = zeroTimeLocal
, _execAcctNumber = ""
, _execExchange = ""
, _execSide = Bought
, _execShares = 0
, _execPrice = 0.0
, _execPermId = 0
, _execLiquidation = 0
, _execCumQty = 0
, _execAvgPrice = 0.0
, _execOrderRef = ""
, _execEvRule = ""
, _execEvMultiplier = 0.0
}
-- -----------------------------------------------------------------------------
-- Commission report
data IBCommissionReport = IBCommissionReport
{ _crExecId :: ByteString
, _crCommission :: Double
, _crCurrency :: Currency
, _crRealisedPNL :: Double
, _crYield :: Double
, _crYieldRedemptionDate :: Int
} deriving Show
newIBCommissionReport :: IBCommissionReport
newIBCommissionReport = IBCommissionReport
{ _crExecId = ""
, _crCommission = 0.0
, _crCurrency = "USD"
, _crRealisedPNL = 0.0
, _crYield = 0.0
, _crYieldRedemptionDate = 0
}
parseIBCommissionReport :: Parser IBCommissionReport
parseIBCommissionReport =
IBCommissionReport <$>
parseByteStringField <*>
parseDoubleField <*>
parseField parseStringToEnum <*>
parseDoubleField <*>
parseDoubleField <*>
parseIntField'
-- -----------------------------------------------------------------------------
-- Execution filter
data IBExecutionFilter = IBExecutionFilter
{ _efClientId :: Int -- zero means no filtering on this field
, _efAcctCode :: String
, _efTime :: String
, _efSymbol :: String
, _efSecType :: IBSecurityType -- String, TODO: Maybe? Check if blank means no filter
, _efExchange :: String
, _efSide :: String --TODO: enum?
} deriving Show
newIBExecutionFilter :: IBExecutionFilter
newIBExecutionFilter = IBExecutionFilter
{ _efClientId = 0 -- zero means no filtering on this field
, _efAcctCode = ""
, _efTime = ""
, _efSymbol = ""
, _efSecType = IBFuture
, _efExchange = ""
, _efSide = ""
}
-- -----------------------------------------------------------------------------
-- Lenses
makeLenses ''IBRequest
makeLenses ''IBHistoricalDataItem
makeLenses ''IBResponse
makeLenses ''IBContract
makeLenses ''IBComboLeg
makeLenses ''IBUnderComp
makeLenses ''IBContractDetails
makeLenses ''IBOrderComboLeg
makeLenses ''IBOrder
makeLenses ''IBOrderState
makeLenses ''IBExecution
makeLenses ''IBCommissionReport
makeLenses ''IBExecutionFilter
| RobinKrom/interactive-brokers | library/API/IB/Data.hs | bsd-3-clause | 54,274 | 0 | 21 | 15,240 | 9,299 | 5,277 | 4,022 | 1,247 | 20 |
{-# OPTIONS_GHC -Wall #-}
{-# LANGUAGE OverloadedStrings #-}
module Deps.Get
( all
, AllPackages
, Mode(..)
, versions
, info
, docs
)
where
import Prelude hiding (all)
import Control.Monad.Except (catchError, liftIO)
import qualified Data.ByteString as BS
import qualified Data.List as List
import qualified Data.Map as Map
import Data.Map (Map)
import qualified System.Directory as Dir
import System.FilePath ((</>))
import qualified Text.PrettyPrint.ANSI.Leijen as P
import qualified Elm.Docs as Docs
import qualified Elm.Package as Pkg
import Elm.Package (Name, Version)
import qualified Deps.Website as Website
import qualified Elm.Project.Json as Project
import qualified Elm.Utils as Utils
import qualified File.IO as IO
import qualified Reporting.Error as Error
import qualified Reporting.Error.Assets as E
import qualified Reporting.Progress as Progress
import qualified Reporting.Task as Task
import qualified Json.Decode as Decode
-- ALL VERSIONS
data Mode = RequireLatest | AllowOffline
newtype AllPackages = AllPackages (Map Name [Version])
all :: Mode -> Task.Task AllPackages
all mode =
do dir <- Task.getPackageCacheDir
let versionsFile = dir </> "versions.dat"
exists <- liftIO $ Dir.doesFileExist versionsFile
if exists
then fetchNew versionsFile mode
else fetchAll versionsFile
fetchAll :: FilePath -> Task.Task AllPackages
fetchAll versionsFile =
do packages <- Website.getAllPackages
let size = Map.foldr ((+) . length) 0 packages
IO.writeBinary versionsFile (size, packages)
return (AllPackages packages)
fetchNew :: FilePath -> Mode -> Task.Task AllPackages
fetchNew versionsFile mode =
do (size, packages) <- IO.readBinary versionsFile
news <-
case mode of
RequireLatest ->
Website.getNewPackages size
AllowOffline ->
Website.getNewPackages size `catchError` \_ ->
do Task.report Progress.UnableToLoadLatestPackages
return []
if null news
then return (AllPackages packages)
else
do let newAllPkgs = List.foldl' addNew packages news
IO.writeBinary versionsFile (size + length news, newAllPkgs)
return (AllPackages newAllPkgs)
addNew :: Map Name [Version] -> (Name, Version) -> Map Name [Version]
addNew packages (name, version) =
Map.insertWith (++) name [version] packages
-- VERSIONS
versions :: Name -> AllPackages -> Either [Name] [Version]
versions name (AllPackages pkgs) =
case Map.lookup name pkgs of
Just vsns ->
Right vsns
Nothing ->
Left (Utils.nearbyNames Pkg.toString name (Map.keys pkgs))
-- PACKAGE INFO
info :: Name -> Version -> Task.Task Project.PkgInfo
info name version =
do dir <- Task.getPackageCacheDirFor name version
let elmJson = dir </> "elm.json"
exists <- liftIO $ Dir.doesFileExist elmJson
json <-
if exists
then liftIO (BS.readFile elmJson)
else
do bits <- Website.getElmJson name version
liftIO (BS.writeFile elmJson bits)
return bits
case Decode.parse "elm.json" "project" E.badContentToDocs Project.pkgDecoder json of
Right pkgInfo ->
return pkgInfo
Left _ ->
do IO.remove elmJson
Task.throw $ Error.Assets $ E.CorruptElmJson name version
-- DOCS
docs :: Name -> Version -> Task.Task Docs.Documentation
docs name version =
do dir <- Task.getPackageCacheDirFor name version
let docsJson = dir </> "docs.json"
exists <- liftIO $ Dir.doesFileExist docsJson
json <-
if exists
then liftIO (BS.readFile docsJson)
else
do bits <- Website.getDocs name version
liftIO (BS.writeFile docsJson bits)
return bits
case Decode.parse "docs.json" "docs" errorToDocs (Docs.toDict <$> Decode.list Docs.decoder) json of
Right pkgInfo ->
return pkgInfo
Left _ ->
do IO.remove docsJson
Task.throw $ Error.Assets $ E.CorruptDocumentation name version
errorToDocs :: Docs.Error -> [P.Doc]
errorToDocs err =
let
details =
case err of
Docs.BadAssociativity txt ->
["Binary","operators","cannot","have",P.red (P.text (show txt)),"as","their","associativity."]
Docs.BadName ->
["It","is","not","a","valid","module","name."]
Docs.BadType ->
["It","is","not","a","valid","Elm","type."]
in
details
++
["This","should","not","happen","in","general,","so","please","report","this","at"
,"<https://github.com/elm-lang/package.elm-lang.org/issues>"
,"if","you","think","it","is","on","the","Elm","side!"
]
| evancz/builder | src/Deps/Get.hs | bsd-3-clause | 4,812 | 0 | 17 | 1,202 | 1,415 | 755 | 660 | 122 | 3 |
{-# LANGUAGE ScopedTypeVariables,GADTs,DeriveDataTypeable,FlexibleInstances,
ExistentialQuantification, StandaloneDeriving, TypeSynonymInstances, FlexibleContexts,
DeriveFunctor,RankNTypes,MultiParamTypeClasses #-}
{-| Provides the expression data type as well as the type-checking algorithm.
-}
module Language.GTL.Expression
(Fix(..),
Term(..),
GTLConstant,
Expr,
Typed(..),
TypedExpr,
BoolOp(..),
UnBoolOp(..),
TimeSpec(..),
IntOp(..),
Relation(..),
ExprOrdering(..),
VarUsage(..),
var,
constant,
gnot,
gand,
gor,
geq,
gneq,
galways,
gfinally,
gimplies,
enumConst,
isInput,isOutput,isState,
typeCheck,
compareExpr,
compareExprDebug,
distributeNot,pushNot,
makeTypedExpr,
getConstant,
constantType,
mapGTLVars,
getVars,
relTurn,
relNot,
maximumHistory,
getClocks,
automatonClocks,
flattenExpr,flattenVar,flattenConstant,
defaultValue,constantToExpr,typedConstantToExpr,
showTermWith
) where
import Language.GTL.Parser.Syntax
import Language.GTL.Parser.Token
import Language.GTL.Buchi
import Language.GTL.Types
import Data.AtomContainer
import Data.Binary
import Data.Maybe
import Data.Map as Map hiding (foldl)
import Data.Set as Set hiding (foldl)
import Data.List as List (genericLength,genericIndex,genericReplicate)
import Data.Either
import Data.Foldable
import Data.Traversable
import Prelude hiding (foldl,foldl1,concat,elem,mapM_,mapM)
import Control.Monad.Error ()
import Control.Exception
import Data.Fix
import Debug.Trace
import Control.Monad.Error.Class (MonadError(..))
import Control.Monad (liftM)
import Text.Show
import Data.Typeable
-- | States how a variable is being used in a formula
data VarUsage = Input -- ^ The variable is an input variable in a contract
| Output -- ^ The variable is an output variable
| StateIn -- ^ The variable is being read from a local state variable
| StateOut -- ^ The variable is being used to define the value of a local state variable
deriving (Show,Eq,Ord)
-- | Represents a GTL term without recursion, which can be added by applying the 'Fix' constructor.
data Term v r = Var v Integer VarUsage -- ^ A variable with a name and a history level
| Value (GTLValue r) -- ^ A value which may contain more terms
| BinBoolExpr BoolOp r r -- ^ A logical binary expression
| BinRelExpr Relation r r -- ^ A relation between two terms
| BinIntExpr IntOp r r -- ^ An arithmetic expression
| UnBoolExpr UnBoolOp r -- ^ A unary logical expression
| IndexExpr r Integer -- ^ Use an index to access a subcomponent of an expression
| Automaton (Maybe String) (BA [r] String) -- ^ A automaton specifying a temporal logical condition
| ClockReset Integer Integer
| ClockRef Integer
| BuiltIn String [r]
deriving (Eq,Ord)
-- | A constant is a value applied to the 'Fix' constructor
type GTLConstant = Fix GTLValue
-- | An expression is a recursive term
type Expr v = Fix (Term v)
-- | Used to supply type information to expressions
data Typed a r = Typed { getType :: GTLType
, getValue :: a r
} deriving (Eq,Ord)
instance Typeable v => Typeable (Fix (Typed (Term v))) where
typeOf (_::Fix (Typed (Term v)))
= mkTyConApp (mkTyCon3 "gtl" "Data.Fix" "Fix")
[mkTyConApp (mkTyCon3 "gtl" "Language.GTL.Expression" "Typed")
[mkTyConApp (mkTyCon3 "gtl" "Language.GTL.Expression" "Term")
[typeOf (undefined::v)]]]
-- | A typed expression is a recursive term with type informations
type TypedExpr v = Fix (Typed (Term v))
instance Functor (Term v) where
fmap f (Var x lvl u) = Var x lvl u
fmap f (Value val) = Value (fmap f val)
fmap f (BinBoolExpr op l r) = BinBoolExpr op (f l) (f r)
fmap f (BinRelExpr op l r) = BinRelExpr op (f l) (f r)
fmap f (BinIntExpr op l r) = BinIntExpr op (f l) (f r)
fmap f (UnBoolExpr op p) = UnBoolExpr op (f p)
fmap f (IndexExpr x i) = IndexExpr (f x) i
fmap f (ClockReset x y) = ClockReset x y
fmap f (ClockRef x) = ClockRef x
instance Functor a => Functor (Typed a) where
fmap f t = Typed { getType = getType t
, getValue = fmap f (getValue t)
}
instance Binary VarUsage where
put u = put ((case u of
Input -> 0
Output -> 1
StateIn -> 2
StateOut -> 3)::Word8)
get = do
w <- get
return $ case (w::Word8) of
0 -> Input
1 -> Output
2 -> StateIn
3 -> StateOut
instance (Binary r,Binary v,Ord v) => Binary (Term v r) where
put (Var v l u) = put (0::Word8) >> put v >> put l >> put u
put (Value val) = put (1::Word8) >> put val
put (BinBoolExpr op l r) = put (2::Word8) >> put op >> put l >> put r
put (BinRelExpr op l r) = put (3::Word8) >> put op >> put l >> put r
put (BinIntExpr op l r) = put (4::Word8) >> put op >> put l >> put r
put (UnBoolExpr op p) = put (5::Word8) >> put op >> put p
put (IndexExpr e i) = put (6::Word8) >> put i >> put e
put (Automaton _ aut) = put (7::Word8) >> put aut
put (ClockReset x y) = put (8::Word8) >> put x >> put y
put (ClockRef x) = put (9::Word8) >> put x
get = do
(i::Word8) <- get
case i of
0 -> do
v <- get
l <- get
u <- get
return $ Var v l u
1 -> fmap Value get
2 -> do
op <- get
l <- get
r <- get
return $ BinBoolExpr op l r
3 -> do
op <- get
l <- get
r <- get
return $ BinRelExpr op l r
4 -> do
op <- get
l <- get
r <- get
return $ BinIntExpr op l r
5 -> do
op <- get
p <- get
return $ UnBoolExpr op p
6 -> do
i <- get
e <- get
return $ IndexExpr e i
7 -> do
aut <- get
return $ Automaton Nothing aut
8 -> do
x <- get
y <- get
return $ ClockReset x y
9 -> do
x <- get
return $ ClockRef x
isInput :: VarUsage -> Bool
isInput Input = True
isInput StateIn = True
isInput _ = False
isOutput :: VarUsage -> Bool
isOutput Output = True
isOutput StateOut = True
isOutput _ = False
isState :: VarUsage -> Bool
isState StateIn = True
isState StateOut = True
isState _ = False
-- | Construct a variable of a given type
var :: GTLType -> v -> Integer -> VarUsage -> TypedExpr v
var t name lvl u = Fix $ Typed t (Var name lvl u)
-- | Create a GTL value from a haskell constant
constant :: ToGTL a => a -> TypedExpr v
constant x = Fix $ Typed (gtlTypeOf x) (Value (toGTL x))
-- | Negate a given expression
gnot :: TypedExpr v -> TypedExpr v
gnot expr
| getType (unfix expr) == gtlBool = Fix $ Typed gtlBool (UnBoolExpr Not expr)
-- | Create the logical conjunction of two expressions
gand :: TypedExpr v -> TypedExpr v -> TypedExpr v
gand x y
| getType (unfix x) == gtlBool && getType (unfix y) == gtlBool = Fix $ Typed gtlBool (BinBoolExpr And x y)
-- | Create the logical disjunction of two expressions
gor :: TypedExpr v -> TypedExpr v -> TypedExpr v
gor x y
| getType (unfix x) == gtlBool && getType (unfix y) == gtlBool = Fix $ Typed gtlBool (BinBoolExpr Or x y)
-- | Create an equality relation between two expressions
geq :: TypedExpr v -> TypedExpr v -> TypedExpr v
geq x y
| baseType (getType (unfix x)) == baseType (getType (unfix y)) = Fix $ Typed gtlBool (BinRelExpr BinEq x y)
| otherwise = error $ "Language.GTL.Expression.geq: Type mismatch between "++show (getType (unfix x))++" and "++show (getType (unfix y))
-- | Create an unequality relation between two expressions
gneq :: TypedExpr v -> TypedExpr v -> TypedExpr v
gneq x y
| getType (unfix x) == getType (unfix y) = Fix $ Typed gtlBool (BinRelExpr BinNEq x y)
galways :: TypedExpr v -> TypedExpr v
galways x
| getType (unfix x) == gtlBool = Fix $ Typed gtlBool (UnBoolExpr Always x)
gfinally :: TypedExpr v -> TypedExpr v
gfinally x
| getType (unfix x) == gtlBool = Fix $ Typed gtlBool (UnBoolExpr (Finally NoTime) x)
gimplies :: TypedExpr v -> TypedExpr v -> TypedExpr v
gimplies x y
| getType (unfix x) == gtlBool && getType (unfix y) == gtlBool = Fix $ Typed gtlBool (BinBoolExpr Implies x y)
-- | Create a enumeration value for a given enumeration type
enumConst :: [String] -> String -> TypedExpr v
enumConst tp v = Fix $ Typed (gtlEnum tp) (Value (GTLEnumVal v))
instance Binary2 a => Binary2 (Typed a) where
put2 x = put (getType x) >> put2 (getValue x)
get2 = do
tp <- get
val <- get2
return (Typed tp val)
instance Eq v => Eq2 (Term v) where
eq2 = (==)
instance Ord v => Ord2 (Term v) where
compare2 = compare
instance (Binary v,Ord v) => Binary2 (Term v) where
get2 = get
put2 = put
instance (Show v) => Show2 (Term v) where
show2 = showTerm show
instance Show2 a => Show2 (Typed a) where
show2 x = show2 (getValue x)
instance Eq v => Eq2 (Typed (Term v)) where
eq2 = (==)
instance Ord v => Ord2 (Typed (Term v)) where
compare2 = compare
-- | Render a term by applying a recursive rendering function to it.
showTerm :: Show v => (r -> String) -> Term v r -> String
showTerm g t = showTermWith (\name lvl -> showsPrec 0 name . (if lvl==0 then id else (showChar '_' . showsPrec 0 lvl))) (\p r -> showString $ g r) 0 t ""
opPrec And = 5
opPrec Or = 4
opPrec Implies = 6
opPrec (Until _) = 3
opPrec (UntilOp _) = 3
intPrec OpPlus = 9
intPrec OpMinus = 10
intPrec OpMult = 11
intPrec OpDiv = 12
unPrec Not = 7
unPrec Always = 2
unPrec (Next _) = 2
unPrec (Finally _) = 2
showTermWith :: (v -> Integer -> ShowS) -> (Integer -> r -> ShowS) -> Integer -> Term v r -> ShowS
showTermWith f g p (Var name lvl u) = (if u == StateOut
then showString "#out "
else id) . f name lvl
showTermWith f g p (Value val) = showString $ showGTLValue (\r -> g 0 r "") 0 val ""
showTermWith f g p (BinBoolExpr op l r)
= showParen (p > opPrec op) $
(g (opPrec op) l) .
(case op of
And -> showString " and "
Or -> showString " or "
Implies -> showString " implies "
Until ts -> showString $ " until"++show ts++" "
UntilOp ts -> showString $ " untilOp"++show ts++" "
) . (g (opPrec op) r)
showTermWith f g p (BinRelExpr rel l r)
= showParen (p > 8) $
(g 8 l) . (showString $ case rel of
BinLT -> " < "
BinLTEq -> " <= "
BinGT -> " > "
BinGTEq -> " >= "
BinEq -> " = "
BinNEq -> " != "
BinAssign -> " := ") . (g 8 r)
showTermWith f g p (BinIntExpr op l r)
= showParen (p > intPrec op) $
(g (intPrec op) l) .
(showString $ case op of
OpPlus -> " + "
OpMinus -> " - "
OpMult -> " * "
OpDiv -> " / ") .
(g (intPrec op) r)
showTermWith f g p (UnBoolExpr op arg)
= showParen (p > unPrec op) $
(showString $ case op of
Not -> "not "
Always -> "always "
Next ts -> "next"++show ts++" "
Finally ts -> "finaly"++show ts++" ") .
(g (unPrec op) arg)
showTermWith f g p (IndexExpr expr idx) = showParen (p > 13) $ g 13 expr . showChar '[' . showsPrec 0 idx . showChar ']'
showTermWith f g p (ClockReset clk limit) = showString "clock(" . showsPrec 0 clk . showString ") := " . showsPrec 0 limit
showTermWith f g p (ClockRef clk) = showString "clock(" . showsPrec 0 clk . showChar ')'
showTermWith f g p (Automaton name ba)
= showString "automaton "
. (case name of
Nothing -> id
Just n -> showString n . showChar ' ')
. showChar '{'
. foldl (.) id [ (if Set.member st (baInits ba)
then showString "init "
else id) .
(if Set.member st (baFinals ba)
then showString "final "
else id) .
showString "state " .
shows st .
showString " {" .
foldl (.) id [ showString " transition"
. showListWith (g 0) cond
. showString " -> "
. shows trg
. showString ";"
| (cond,trg) <- trans ] .
showString "}"
| (st,trans) <- Map.toList $ baTransitions ba ]
. showChar '}'
-- | Helper function for type checking: If the two supplied types are the same,
-- return 'Right' (), otherwise generate an error using the supplied identifier.
enforceType :: MonadError String m =>
String -- ^ A string representation of the type checked entity
-> GTLType -- ^ The actual type of the entity
-> GTLType -- ^ The expected type
-> m ()
enforceType expr ac tp = if isSubtypeOf ac tp || isSubtypeOf tp ac
then return ()
else throwError $ expr ++ " should have type "++show tp++" but it has type "++show ac
-- | Convert a untyped, generalized expression into a typed expression by performing type checking
makeTypedExpr :: (Ord v,Show v,MonadError String m) =>
(Maybe String -> String -> Maybe ContextInfo -> m (v,VarUsage)) -- ^ A function to create variable names from qualified and unqualified variables
-> Map v GTLType -- ^ A type mapping for variables
-> Set [String] -- ^ All possible enum types
-> PExpr -- ^ The generalized expression to type check
-> m (TypedExpr v)
makeTypedExpr f varmp enums expr = parseTerm f Map.empty Nothing expr >>= typeCheck varmp enums
-- | Convert an expression into a constant, if it is one.
-- If not, return 'Nothing'.
getConstant :: TypedExpr v -> Maybe GTLConstant
getConstant e = case getValue (unfix e) of
Value p -> do
np <- mapM getConstant p
return $ Fix np
_ -> Nothing
-- | Get the type of a GTL constant.
constantType :: Set [String] -- ^ All possible enum types
-> GTLConstant
-> GTLType
constantType enums c = case unfix c of
GTLIntVal _ -> gtlInt
GTLByteVal _ -> gtlByte
GTLBoolVal _ -> gtlBool
GTLFloatVal _ -> gtlFloat
GTLEnumVal v -> case find (elem v) enums of
Nothing -> error $ "Language.GTL.Expression.constantType: Enum value "++v++" not found in possible enum types "++show enums++"."
Just vals -> gtlEnum vals
GTLArrayVal [] -> error $ "Language.GTL.Expression.constantType: Can't get type of zero-length array."
GTLArrayVal (v:vs) -> gtlArray (genericLength vs+1) (constantType enums v)
GTLTupleVal vs -> gtlTuple (fmap (constantType enums) vs)
-- | Convert a type and a constant to a typed expression.
-- Performs type checking to make sure the constant actually has the type claimed.
typedConstantToExpr :: GTLType -> GTLConstant -> TypedExpr v
typedConstantToExpr t@(Fix GTLInt) (Fix (GTLIntVal i)) = Fix (Typed t (Value (GTLIntVal i)))
typedConstantToExpr t@(Fix GTLByte) (Fix (GTLByteVal i)) = Fix (Typed t (Value (GTLByteVal i)))
typedConstantToExpr t@(Fix GTLBool) (Fix (GTLBoolVal i)) = Fix (Typed t (Value (GTLBoolVal i)))
typedConstantToExpr t@(Fix GTLFloat) (Fix (GTLFloatVal i)) = Fix (Typed t (Value (GTLFloatVal i)))
typedConstantToExpr t@(Fix (GTLEnum enums)) (Fix (GTLEnumVal i))
| i `elem` enums = Fix (Typed t (Value (GTLEnumVal i)))
| otherwise = error $ "Language.GTL.Expression.typedConstantToExpr: "++i++" is not an enum value of "++show t
typedConstantToExpr t@(Fix (GTLArray sz tp)) (Fix (GTLArrayVal vals))
| genericLength vals == sz = Fix (Typed t (Value (GTLArrayVal (fmap (typedConstantToExpr tp) vals))))
| otherwise = error $ "Language.GTL.Expression.typedConstantToExpr: Array size mismatch (should be "++show sz++")"
typedConstantToExpr t@(Fix (GTLTuple tps)) (Fix (GTLTupleVal vals))
= Fix (Typed t (Value (GTLTupleVal (zipWith typedConstantToExpr tps vals))))
typedConstantToExpr (Fix (GTLNamed _ tp)) c = typedConstantToExpr tp c
typedConstantToExpr t v = error $ "Language.GTL.Expression.typedConstantToExpr: "++show v++" doesn't have type "++show t
-- | Type-check an untyped expression.
typeCheck :: (Ord v,Show v,MonadError String m) =>
Map v GTLType -- ^ A type mapping for all variables
-> Set [String] -- ^ A set of all allowed enum types
-> Expr v -- ^ The untyped expression
-> m (TypedExpr v)
typeCheck varmp enums e = liftM Fix $ typeCheck' (typeCheck varmp enums) (getType.unfix) (show . untyped) varmp enums (unfix e)
where
typeCheck' :: (Ord v,Show v,Ord r2,MonadError String m) =>
(r1 -> m r2)
-> (r2 -> GTLType)
-> (r2 -> String)
-> Map v GTLType -> Set [String] -> Term v r1 -> m (Typed (Term v) r2)
typeCheck' mu mutp mus varmp enums (Var x lvl u) = case Map.lookup x varmp of
Nothing -> throwError $ "Unknown variable "++show x
Just tp -> return $ Typed tp (Var x lvl u)
typeCheck' mu mutp mus varmp enums (Value val) = case val of
GTLIntVal i -> return $ Typed gtlInt (Value $ GTLIntVal i)
GTLByteVal i -> return $ Typed gtlByte (Value $ GTLByteVal i)
GTLBoolVal i -> return $ Typed gtlBool (Value $ GTLBoolVal i)
GTLFloatVal i -> return $ Typed gtlFloat (Value $ GTLFloatVal i)
GTLEnumVal x -> case find (elem x) enums of
Nothing -> throwError $ "Unknown enum value "++show x
Just e -> return $ Typed (gtlEnum e) (Value $ GTLEnumVal x)
GTLArrayVal vals -> do
res <- mapM mu vals
case res of
[] -> throwError "Empty arrays not allowed"
(x:xs) -> mapM_ (\tp -> if (mutp tp)==(mutp x)
then return ()
else throwError "Not all array elements have the same type") xs
return $ Typed (gtlArray (genericLength res) (mutp (head res))) (Value $ GTLArrayVal res)
GTLTupleVal vals -> do
tps <- mapM mu vals
return $ Typed (gtlTuple (fmap mutp tps)) (Value $ GTLTupleVal tps)
typeCheck' mu mutp mus varmp enums (BinBoolExpr op l r) = do
ll <- mu l
rr <- mu r
enforceType (mus ll) (mutp ll) gtlBool
enforceType (mus rr) (mutp rr) gtlBool
return $ Typed gtlBool (BinBoolExpr op ll rr)
typeCheck' mu mutp mus varmp enums (BinRelExpr rel l r) = do
ll <- mu l
rr <- mu r
if rel==BinEq || rel==BinNEq
then (do
enforceType (mus rr) (mutp rr) (mutp ll))
else (do
enforceType (mus ll) (mutp ll) gtlInt
enforceType (mus rr) (mutp rr) gtlInt)
return $ Typed gtlBool (BinRelExpr rel ll rr)
typeCheck' mu mutp mus varmp enums (BinIntExpr op l r) = do
ll <- mu l
rr <- mu r
enforceType (mus ll) (mutp ll) gtlInt
enforceType (mus rr) (mutp rr) gtlInt
return $ Typed gtlInt (BinIntExpr op ll rr)
typeCheck' mu mutp mus varmp enums (UnBoolExpr op p) = do
pp <- mu p
enforceType (mus pp) (mutp pp) gtlBool
return $ Typed gtlBool (UnBoolExpr op pp)
typeCheck' mu mutp mus varmp enums (IndexExpr p idx) = do
pp <- mu p
case unfix $ baseType $ mutp pp of
GTLArray sz tp -> if idx < sz
then return $ Typed tp (IndexExpr pp idx)
else throwError $ "Index "++show idx++" out of bounds "++show sz
GTLTuple tps -> if idx < genericLength tps
then return $ Typed (tps `genericIndex` idx) (IndexExpr pp idx)
else throwError $ "Index "++show idx++" out of bounds "++show (genericLength tps)
_ -> throwError $ "Expression " ++ mus pp ++ " is not indexable"
typeCheck' mu mutp mus varmp enums (Automaton name buchi) = do
ntrans <- mapM (\trans -> mapM (\(cond,trg) -> do
ncond <- mapM mu cond
return (ncond,trg)
) trans
) (baTransitions buchi)
return $ Typed gtlBool (Automaton name $ buchi { baTransitions = ntrans })
typeCheck' mu mutp mus varmp enums (BuiltIn name args) = do
tps <- mapM mu args
case name of
"equal" -> do
case tps of
[] -> return $ Typed gtlBool (BuiltIn name [])
x:xs -> do
mapM_ (\tp -> if (mutp tp)==(mutp x)
then return ()
else throwError "Not all \"equal\" arguments have the same type") xs
return $ Typed gtlBool (BuiltIn name tps)
_ -> throwError $ "Unknown built-in "++show name
-- | Discard type information for an expression
untyped :: TypedExpr v -> Expr v
untyped expr = Fix $ fmap untyped (getValue (unfix expr))
-- | Convert a generalized expression into a regular one.
parseTerm :: (MonadError String m, Ord v) =>
(Maybe String -> String -> Maybe ContextInfo -> m (v,VarUsage)) -- ^ A function to create variable names and usage from qualified or unqualified variables
-> ExistsBinding v -- ^ All existentially bound variables
-> Maybe ContextInfo -- ^ Information about variable context (input or output)
-> PExpr -- ^ The generalized expression
-> m (Expr v)
parseTerm f ex inf e = liftM Fix $ parseTerm' (\ex' inf' expr -> parseTerm f ex' inf' expr) f ex inf e
where
parseTerm' :: (MonadError String m, Ord r) => (ExistsBinding v -> Maybe ContextInfo -> PExpr -> m r)
-> (Maybe String -> String -> Maybe ContextInfo -> m (v,VarUsage))
-> ExistsBinding v
-> Maybe ContextInfo
-> PExpr -> m (Term v r)
parseTerm' mu f ex inf (_,GBin op tspec l r) = do
rec_l <- mu ex inf l
rec_r <- mu ex inf r
case toBoolOp op tspec of
Just rop -> return $ BinBoolExpr rop rec_l rec_r
Nothing -> case toRelOp op of
Just rop -> return $ BinRelExpr rop rec_l rec_r
Nothing -> case toIntOp op of
Just rop -> return $ BinIntExpr rop rec_l rec_r
Nothing -> throwError $ "Internal error, please implement parseTerm for operator "++show op
parseTerm' mu f ex inf (_,GUn op ts p) = do
rec <- mu (case op of
GOpNext -> fmap (\(v,lvl,u) -> (v,lvl+1,u)) ex
_ -> ex
) inf p
return $ UnBoolExpr (case op of
GOpAlways -> Always
GOpNext -> Next ts
GOpNot -> Not
GOpFinally -> Finally ts
GOpAfter -> After ts
) rec
parseTerm' mu f ex inf (_,GConst x) = return $ Value (GTLIntVal $ fromIntegral x)
parseTerm' mu f ex inf (_,GConstBool x) = return $ Value (GTLBoolVal x)
parseTerm' mu f ex inf (_,GEnum x) = return $ Value (GTLEnumVal x)
parseTerm' mu f ex inf (_,GTuple args) = do
res <- mapM (mu ex inf) args
return $ Value (GTLTupleVal res)
parseTerm' mu f ex inf (_,GArray args) = do
res <- mapM (mu ex inf) args
return $ Value (GTLArrayVal res)
parseTerm' mu f ex inf (_,GVar q n) = case q of
Nothing -> case Map.lookup n ex of
Nothing -> do
(var,u) <- f q n inf
return $ Var var 0 u
Just (r,lvl,u) -> return $ Var r lvl u
Just _ -> do
(var,u) <- f q n inf
return $ Var var 0 u
parseTerm' mu f ex inf (_,GExists b q n expr) = case q of
Nothing -> case Map.lookup n ex of
Nothing -> do
(var,u) <- f q n inf
parseTerm' mu f (Map.insert b (var,0,u) ex) inf expr
Just (v,lvl,u) -> parseTerm' mu f (Map.insert b (v,lvl,u) ex) inf expr
Just _ -> do
(var,u) <- f q n inf
parseTerm' mu f (Map.insert b (var,0,u) ex) inf expr
parseTerm' mu f ex inf (_,GAutomaton name sts) = do
stmp <- foldlM (\mp st -> do
let (exprs,nexts) = partitionEithers (stateContent st)
rexpr <- mapM (mu ex inf) exprs
rnexts <- mapM (\(trg,cond) -> do
rcond <- case cond of
Nothing -> return Nothing
Just cond' -> do
r <- mu ex inf cond'
return $ Just r
return (rcond,trg)
) nexts
return $ Map.insert (stateName st) (stateInitial st,stateFinal st,rexpr,rnexts) mp
) Map.empty sts
return $ Automaton name $
BA { baTransitions = fmap (\(_,_,_,nxts) -> [ (case cond of
Nothing -> tcond
Just t -> t:tcond,trg)
| (cond,trg) <- nxts,
let (_,_,tcond,_) = stmp!trg
]) stmp
, baInits = Map.keysSet $ Map.filter (\(init,_,_,_) -> init) stmp
, baFinals = Map.keysSet $ Map.filter (\(_,fin,_,_) -> fin) stmp
}
parseTerm' mu f ex inf (_,GIndex expr ind) = do
rind <- case ind of
(_,GConst x) -> return x
_ -> throwError $ "Index must be an integer"
rexpr <- mu ex inf expr
return $ IndexExpr rexpr (fromIntegral rind)
parseTerm' mu f ex inf (_,GBuiltIn name args) = do
res <- mapM (mu ex inf) args
return $ BuiltIn name res
parseTerm' mu f ex _ (_,GContext inf expr) = parseTerm' mu f ex (Just inf) expr
-- | Distribute a negation as deep as possible into an expression until it only ever occurs in front of variables.
distributeNot :: TypedExpr v -> TypedExpr v
distributeNot expr
| getType (unfix expr) == gtlBool = case getValue (unfix expr) of
Var x lvl u -> Fix $ Typed gtlBool $ UnBoolExpr Not expr
Value (GTLBoolVal x) -> Fix $ Typed gtlBool $ Value (GTLBoolVal (not x))
BinBoolExpr op l r -> Fix $ Typed gtlBool $ case op of
And -> BinBoolExpr Or (distributeNot l) (distributeNot r)
Or -> BinBoolExpr And (distributeNot l) (distributeNot r)
Implies -> BinBoolExpr And (pushNot l) (distributeNot r)
Until ts -> BinBoolExpr (UntilOp ts) (distributeNot l) (distributeNot r)
UntilOp ts -> BinBoolExpr (Until ts) (distributeNot l) (distributeNot r)
BinRelExpr rel l r -> Fix $ Typed gtlBool $ BinRelExpr (relNot rel) l r
UnBoolExpr op p -> case op of
Not -> pushNot p
Next NoTime -> Fix $ Typed gtlBool $ UnBoolExpr (Next NoTime) (distributeNot p)
Always -> Fix $ Typed gtlBool $ UnBoolExpr (Finally NoTime) (distributeNot p)
Finally NoTime -> Fix $ Typed gtlBool $ UnBoolExpr Always (distributeNot p)
Finally spec -> Fix $ Typed gtlBool $ UnBoolExpr (Next spec) (distributeNot p)
IndexExpr e i -> Fix $ Typed gtlBool $ UnBoolExpr Not expr
Automaton _ _ -> Fix $ Typed gtlBool $ UnBoolExpr Not expr
ClockRef x -> Fix $ Typed gtlBool $ UnBoolExpr Not expr
ClockReset _ _ -> error "Can't negate a clock reset"
-- | If negations occur in the given expression, push them as deep into the expression as possible.
pushNot :: TypedExpr v -> TypedExpr v
pushNot expr
| getType (unfix expr) == gtlBool = case getValue (unfix expr) of
BinBoolExpr op l r -> Fix $ Typed gtlBool $ BinBoolExpr op (pushNot l) (pushNot r)
UnBoolExpr Not p -> distributeNot p
UnBoolExpr op p -> Fix $ Typed gtlBool $ UnBoolExpr op (pushNot p)
IndexExpr e i -> Fix $ Typed (getType $ unfix expr) (IndexExpr (pushNot e) i)
_ -> expr
-- | Extracts the maximum level of history for each variable in the expression.
maximumHistory :: Ord v => TypedExpr v -> Map v Integer
maximumHistory exprs = foldl (\mp (n,_,_,lvl,_) -> Map.insertWith max n lvl mp) Map.empty (getVars exprs)
-- | Extracts all variables with their level of history from an expression.
getVars :: TypedExpr v -> [(v,VarUsage,[Integer],Integer,GTLType)]
getVars x = getTermVars getVars (unfix x)
-- | Extract all variables used in the given term.
getTermVars :: (r -> [(v,VarUsage,[Integer],Integer,GTLType)]) -> Typed (Term v) r -> [(v,VarUsage,[Integer],Integer,GTLType)]
getTermVars mu expr = case getValue expr of
Var n lvl u -> [(n,u,[],lvl,getType expr)]
Value x -> getValueVars mu x
BinBoolExpr op l r -> (mu l)++(mu r)
BinRelExpr op l r -> (mu l)++(mu r)
BinIntExpr op l r -> (mu l)++(mu r)
UnBoolExpr op p -> mu p
IndexExpr e i -> fmap (\(v,u,idx,lvl,tp) -> (v,u,i:idx,lvl,tp)) (mu e)
Automaton _ buchi -> concat [ concat $ fmap mu cond
| trans <- Map.elems (baTransitions buchi),
(cond,_) <- trans
]
BuiltIn _ args -> concat $ fmap mu args
-- | Get all variables used in a GTL value.
getValueVars :: (r -> [(v,VarUsage,[Integer],Integer,GTLType)]) -> GTLValue r -> [(v,VarUsage,[Integer],Integer,GTLType)]
getValueVars mu (GTLArrayVal xs) = concat (fmap mu xs)
getValueVars mu (GTLTupleVal xs) = concat (fmap mu xs)
getValueVars _ _ = []
-- | Change the type of the variables in an expression.
mapGTLVars :: (Ord v,Ord w) => (v -> w) -> TypedExpr v -> TypedExpr w
mapGTLVars f (Fix expr) = Fix $ Typed (getType expr) (mapTermVars f (mapGTLVars f) (getValue expr))
-- | Change the type of the variables used in a term
mapTermVars :: (Ord r1,Ord r2) => (v -> w) -> (r1 -> r2) -> Term v r1 -> Term w r2
mapTermVars f mu (Var name lvl u) = Var (f name) lvl u
mapTermVars f mu (Value x) = Value (mapValueVars mu x)
mapTermVars f mu (BinBoolExpr op l r) = BinBoolExpr op (mu l) (mu r)
mapTermVars f mu (BinRelExpr rel l r) = BinRelExpr rel (mu l) (mu r)
mapTermVars f mu (BinIntExpr op l r) = BinIntExpr op (mu l) (mu r)
mapTermVars f mu (UnBoolExpr op p) = UnBoolExpr op (mu p)
mapTermVars f mu (IndexExpr e i) = IndexExpr (mu e) i
mapTermVars f mu (Automaton name buchi)
= Automaton name $ buchi { baTransitions = fmap (fmap (\(cond,trg) -> (fmap mu cond,trg))) (baTransitions buchi) }
-- | Change the type of the variables used in a value
mapValueVars :: (r1 -> r2) -> GTLValue r1 -> GTLValue r2
mapValueVars mu (GTLIntVal x) = GTLIntVal x
mapValueVars mu (GTLByteVal x) = GTLByteVal x
mapValueVars mu (GTLBoolVal x) = GTLBoolVal x
mapValueVars mu (GTLFloatVal x) = GTLFloatVal x
mapValueVars mu (GTLEnumVal x) = GTLEnumVal x
mapValueVars mu (GTLArrayVal xs) = GTLArrayVal (fmap mu xs)
mapValueVars mu (GTLTupleVal xs) = GTLTupleVal (fmap mu xs)
-- | Binary boolean operators with the traditional semantics.
data BoolOp = And -- ^ ⋀
| Or -- ^ ⋁
| Implies -- ^ ⇒
| Until TimeSpec
| UntilOp TimeSpec
deriving (Show,Eq,Ord)
-- | Unary boolean operators with the traditional semantics.
data UnBoolOp = Not
| Always
| Next TimeSpec
| Finally TimeSpec
| After TimeSpec
deriving (Show,Eq,Ord)
instance Binary TimeSpec where
put NoTime = put (0::Word8)
put (TimeSteps n) = put (1::Word8) >> put n
put (TimeUSecs n) = put (2::Word8) >> put n
get = do
i <- get
case (i::Word8) of
0 -> return NoTime
1 -> do
n <- get
return $ TimeSteps n
2 -> do
n <- get
return $ TimeUSecs n
instance Binary BoolOp where
put And = put (0::Word8)
put Or = put (1::Word8)
put Implies = put (2::Word8)
put (Until ts) = put (3::Word8) >> put ts
put (UntilOp ts) = put (4::Word8) >> put ts
get = do
i <- get
case (i::Word8) of
0 -> return And
1 -> return Or
2 -> return Implies
3 -> do
ts <- get
return $ Until ts
4 -> do
ts <- get
return (UntilOp ts)
instance Binary UnBoolOp where
put Not = put (0::Word8)
put Always = put (1::Word8)
put (Next ts) = put (2::Word8) >> put ts
put (Finally ts) = put (3::Word8) >> put ts
get = do
i <- get
case (i::Word8) of
0 -> return Not
1 -> return Always
2 -> do
ts <- get
return $ Next ts
3 -> do
ts <- get
return $ Finally ts
-- | Arithmetik binary operators.
data IntOp = OpPlus -- ^ +
| OpMinus -- ^ \-
| OpMult -- ^ \*
| OpDiv -- ^ /
deriving (Show,Eq,Ord,Enum)
instance Binary IntOp where
put x = put (fromIntegral (fromEnum x) :: Word8)
get = fmap (toEnum . fromIntegral :: Word8 -> IntOp) get
-- | Integer relations.
data Relation = BinLT -- ^ <
| BinLTEq -- ^ <=
| BinGT -- ^ \>
| BinGTEq -- ^ \>=
| BinEq -- ^ =
| BinNEq -- ^ !=
| BinAssign -- ^ :=
deriving (Eq,Ord,Enum)
instance Binary Relation where
put x = put (fromIntegral (fromEnum x) :: Word8)
get = fmap (toEnum . fromIntegral :: Word8 -> Relation) get
instance Show Relation where
show BinLT = "<"
show BinLTEq = "<="
show BinGT = ">"
show BinGTEq = ">="
show BinEq = "="
show BinNEq = "!="
-- | Cast a binary operator into a boolean operator. Returns `Nothing' if the cast fails.
toBoolOp :: BinOp -> TimeSpec -> Maybe BoolOp
toBoolOp GOpAnd NoTime = Just And
toBoolOp GOpOr NoTime = Just Or
toBoolOp GOpImplies NoTime = Just Implies
toBoolOp GOpUntil spec = Just (Until spec)
toBoolOp _ _ = Nothing
-- | Cast a binary operator into a relation. Returns `Nothing' if the cast fails.
toRelOp :: BinOp -> Maybe Relation
toRelOp GOpLessThan = Just BinLT
toRelOp GOpLessThanEqual = Just BinLTEq
toRelOp GOpGreaterThan = Just BinGT
toRelOp GOpGreaterThanEqual = Just BinGTEq
toRelOp GOpEqual = Just BinEq
toRelOp GOpAssign = Just BinAssign
toRelOp GOpNEqual = Just BinNEq
toRelOp _ = Nothing
-- | Cast a binary operator into an element operator. Returns `Nothing' if the cast fails.
toElemOp :: BinOp -> Maybe Bool
toElemOp GOpIn = Just True
toElemOp GOpNotIn = Just False
toElemOp _ = Nothing
-- | Binds variables to other variables from the past.
type ExistsBinding a = Map String (a,Integer,VarUsage)
-- | Cast a binary operator into an arithmetic operator. Returns `Nothing' if the cast fails.
toIntOp :: BinOp -> Maybe IntOp
toIntOp GOpPlus = Just OpPlus
toIntOp GOpMinus = Just OpMinus
toIntOp GOpMult = Just OpMult
toIntOp GOpDiv = Just OpDiv
toIntOp _ = Nothing
-- | Negates a relation
relNot :: Relation -> Relation
relNot rel = case rel of
BinLT -> BinGTEq
BinLTEq -> BinGT
BinGT -> BinLTEq
BinGTEq -> BinLT
BinEq -> BinNEq
BinNEq -> BinEq
--BinAssign -> error "Can't negate assignments"
-- | Switches the operands of a relation.
-- Turns x < y into y > x.
relTurn :: Relation -> Relation
relTurn rel = case rel of
BinLT -> BinGT
BinLTEq -> BinGTEq
BinGT -> BinLT
BinGTEq -> BinLTEq
BinEq -> BinEq
BinNEq -> BinNEq
--BinAssign -> error "Can't turn assignments"
getClocks :: TypedExpr v -> [Integer]
getClocks (Fix e) = case getValue e of
ClockReset c _ -> [c]
ClockRef c -> [c]
BinBoolExpr _ lhs rhs -> (getClocks lhs) ++ (getClocks rhs)
UnBoolExpr _ r -> getClocks r
Automaton _ aut -> automatonClocks id aut
BuiltIn _ r -> concat $ fmap getClocks r
_ -> []
automatonClocks :: (a -> [TypedExpr v]) -> BA a st -> [Integer]
automatonClocks f aut = concat [ concat $ fmap getClocks (f cond)
| trans <- Map.elems (baTransitions aut),
(cond,_) <- trans
]
-- | Convert a typed expression to a linear combination of variables.
toLinearExpr :: Ord v => TypedExpr v -> Map (Map (v,Integer,VarUsage) Integer) GTLConstant
toLinearExpr e = case getValue (unfix e) of
Var v h u -> Map.singleton (Map.singleton (v,h,u) 1) one
Value v -> let Just c = getConstant e
in Map.singleton Map.empty c
BinIntExpr op lhs rhs
-> let p1 = toLinearExpr lhs
p2 = toLinearExpr rhs
in case op of
OpPlus -> Map.unionWith (constantOp (+)) p1 p2
OpMinus -> Map.unionWith (constantOp (-)) p1 p2
OpMult -> Map.fromList [ (Map.unionWith (+) t1 t2,constantOp (*) c1 c2) | (t1,c1) <- Map.toList p1, (t2,c2) <- Map.toList p2 ]
where
one = Fix $ case unfix $ getType (unfix e) of
GTLInt -> GTLIntVal 1
GTLByte -> GTLByteVal 1
GTLFloat -> GTLFloatVal 1
-- | Apply an operation to a GTL value.
constantOp :: (forall a. Num a => a -> a -> a)
-> GTLConstant -> GTLConstant -> GTLConstant
constantOp iop x y = Fix $ case unfix x of
GTLIntVal x' -> let GTLIntVal y' = unfix y in GTLIntVal (iop x' y')
GTLByteVal x' -> let GTLByteVal y' = unfix y in GTLByteVal (iop x' y')
GTLFloatVal x' -> let GTLFloatVal y' = unfix y in GTLFloatVal (iop x' y')
compareExprDebug :: (Ord v,Show v) => TypedExpr v -> TypedExpr v -> ExprOrdering
compareExprDebug e1 e2 = let res = compareExpr e1 e2
in trace ("COMP ["++show e1++"] # ["++show e2++"]\t\t"++show res) res
-- TODO: Use a constraint solver here?
-- | Compare the value spaces of two expressions
compareExpr :: Ord v => TypedExpr v -> TypedExpr v -> ExprOrdering
compareExpr e1 e2
= assert (getType (unfix e1) == getType (unfix e2)) $
case unfix $ getType (unfix e1) of
GTLInt -> lincomp
GTLByte -> lincomp
GTLFloat -> lincomp
GTLBool -> case getValue (unfix e2) of
UnBoolExpr Not e2' -> case compareExpr e1 e2' of
EEQ -> ENEQ
_ -> EUNK
_ -> case getValue (unfix e1) of
Var v1 h1 u1 -> case getValue (unfix e2) of
Var v2 h2 u2 -> if v1==v2 && h1==h2 && u1 == u2
then EEQ
else EUNK
_ -> EUNK
Value c1 -> case getValue (unfix e2) of
Value c2 -> if c1 == c2
then EEQ
else ENEQ
_ -> EUNK
IndexExpr ee1 i1 -> case getValue (unfix e2) of
IndexExpr ee2 i2 -> case compareExpr ee1 ee2 of
EEQ -> if i1==i2
then EEQ
else EUNK
_ -> EUNK
_ -> EUNK
BinRelExpr op1 l1 r1 -> case getValue (unfix e2) of
BinRelExpr op2 l2 r2 -> case op1 of
BinEq -> case op2 of
BinEq -> case compareExpr l1 l2 of
EEQ -> compareExpr r1 r2
ENEQ -> case compareExpr r1 r2 of
EEQ -> ENEQ
ENEQ -> EUNK
_ -> EUNK
_ -> EUNK
BinNEq -> case compareExpr l1 l2 of
EEQ -> case compareExpr r1 r2 of
EEQ -> ENEQ
_ -> ELT
ENEQ -> case compareExpr r1 r2 of
EEQ -> ENEQ
_ -> EUNK
_ -> EUNK
_ -> EUNK
BinNEq -> case op2 of
BinNEq -> case compareExpr l1 l2 of
EEQ -> case compareExpr r1 r2 of
EEQ -> EEQ
ENEQ -> if getType (unfix l1) == gtlBool
then ENEQ
else EUNK
_ -> EUNK
_ -> EUNK
BinEq -> case compareExpr l1 l2 of
EEQ -> case compareExpr r1 r2 of
EEQ -> ENEQ
ENEQ -> EGT
_ -> EUNK
_ -> EUNK
_ -> EUNK
BinLT -> case op2 of
BinLT -> case compareExpr l1 l2 of
EEQ -> case compareExpr r1 r2 of
EEQ -> EEQ
_ -> EUNK
_ -> EUNK
BinGTEq -> case compareExpr l1 l2 of
EEQ -> case compareExpr r1 r2 of
EEQ -> ENEQ
_ -> EUNK
_ -> EUNK
_ -> EUNK
BinGTEq -> case op2 of
BinGTEq -> case compareExpr l1 l2 of
EEQ -> case compareExpr r1 r2 of
EEQ -> EEQ
_ -> EUNK
_ -> EUNK
BinLT -> case compareExpr l1 l2 of
EEQ -> case compareExpr r1 r2 of
EEQ -> ENEQ
_ -> EUNK
_ -> EUNK
_ -> EUNK
_ -> EUNK
UnBoolExpr Not p -> case getValue (unfix e2) of
UnBoolExpr Not p' -> case compareExpr p p' of
ELT -> EGT
EGT -> ELT
r -> r
_ -> case compareExpr p e2 of
EEQ -> ENEQ
_ -> EUNK
ClockReset x y -> case getValue (unfix e2) of
ClockReset x' y' -> if x==x'
then (if y==y' then EEQ else ENEQ)
else EUNK
_ -> EUNK
ClockRef x -> case getValue (unfix e2) of
ClockRef y -> if x==y then EEQ else EUNK
_ -> EUNK
_ -> case getValue (unfix e1) of
Value c1 -> case getValue (unfix e2) of
Value c2 -> if c1 == c2
then EEQ
else ENEQ
_ -> EUNK
_ -> if getValue (unfix e1) == getValue (unfix e2)
then EEQ
else EUNK
where
p1 = toLinearExpr e1
p2 = toLinearExpr e2
lincomp = if p1 == p2
then EEQ
else (if Map.size p1 == 1 && Map.size p2 == 1
then (case Map.lookup Map.empty p1 of
Nothing -> EUNK
Just c1 -> case Map.lookup Map.empty p2 of
Nothing -> EUNK
Just c2 -> ENEQ)
else EUNK)
flattenVar :: GTLType -> [Integer] -> [(GTLType,[Integer])]
flattenVar (Fix (GTLArray sz tp)) (i:is) = fmap (\(t,is) -> (t,i:is)) (flattenVar tp is)
flattenVar (Fix (GTLArray sz tp)) [] = concat [fmap (\(t,is) -> (t,i:is)) (flattenVar tp []) | i <- [0..(sz-1)] ]
flattenVar (Fix (GTLTuple tps)) (i:is) = fmap (\(t,is) -> (t,i:is)) (flattenVar (tps `genericIndex` i) is)
flattenVar (Fix (GTLTuple tps)) [] = concat [ fmap (\(t,is) -> (t,i:is)) (flattenVar tp []) | (i,tp) <- zip [0..] tps ]
flattenVar (Fix (GTLNamed _ tp)) idx = flattenVar tp idx
flattenVar tp [] = allPossibleIdx tp --[(tp,[])]
flattenConstant :: GTLConstant -> [GTLConstant]
flattenConstant c = case unfix c of
GTLArrayVal vs -> concat $ fmap flattenConstant vs
GTLTupleVal vs -> concat $ fmap flattenConstant vs
_ -> [c]
flattenExpr :: (Ord a,Ord b) => (a -> [Integer] -> b) -> [Integer] -> TypedExpr a -> TypedExpr b
flattenExpr f idx (Fix e) = Fix $ Typed (getType e) $ case getValue e of
Var v i u -> Var (f v idx) i u
Value v -> case idx of
[] -> Value (fmap (flattenExpr f []) v)
(i:is) -> case v of
GTLArrayVal vs -> getValue $ unfix $ flattenExpr f is (vs `genericIndex` i)
GTLTupleVal vs -> getValue $ unfix $ flattenExpr f is (vs `genericIndex` i)
BinBoolExpr op l r -> BinBoolExpr op (flattenExpr f idx l) (flattenExpr f idx r)
BinRelExpr rel l r -> getValue $ unfix $ foldl1 gand [ Fix $ Typed gtlBool (BinRelExpr rel el er)
| (el,er) <- zip (unpackExpr f idx l) (unpackExpr f idx r) ]
BinIntExpr op l r -> BinIntExpr op (flattenExpr f idx l) (flattenExpr f idx r)
UnBoolExpr op ne -> UnBoolExpr op (flattenExpr f idx ne)
IndexExpr e i -> getValue $ unfix $ flattenExpr f (i:idx) e
Automaton name buchi -> Automaton name (baMapAlphabet (fmap $ flattenExpr f idx) buchi)
unpackExpr :: (Ord a,Ord b) => (a -> [Integer] -> b) -> [Integer] -> TypedExpr a -> [TypedExpr b]
unpackExpr f i (Fix e) = case getValue e of
Var v lvl u -> case resolveIndices (getType e) i of
Left err -> [Fix $ Typed (getType e) (Var (f v i) lvl u)]
Right tp -> case unfix tp of
GTLArray sz tp' -> concat [ unpackExpr f [j] (Fix $ Typed tp' (Var v lvl u)) | j <- [0..(sz-1)] ]
GTLTuple tps -> concat [ unpackExpr f [j] (Fix $ Typed tp' (Var v lvl u)) | (tp',j) <- zip tps [0..] ]
GTLNamed _ tp' -> unpackExpr f i (Fix (e { getType = tp' }))
_ -> [Fix $ Typed tp (Var (f v i) lvl u)]
Value (GTLArrayVal vs) -> concat $ fmap (unpackExpr f i) vs
Value (GTLTupleVal vs) -> concat $ fmap (unpackExpr f i) vs
Value v -> [Fix $ Typed (getType e) (Value $ fmap (flattenExpr f i) v)]
BinBoolExpr op l r -> [Fix $ Typed (getType e) (BinBoolExpr op (flattenExpr f i l) (flattenExpr f i r))]
BinRelExpr rel l r -> [Fix $ Typed (getType e) (BinRelExpr rel (flattenExpr f i l) (flattenExpr f i r))]
BinIntExpr op l r -> [Fix $ Typed (getType e) (BinIntExpr op (flattenExpr f i l) (flattenExpr f i r))]
UnBoolExpr op ne -> [Fix $ Typed (getType e) (UnBoolExpr op (flattenExpr f i ne))]
IndexExpr ne ni -> unpackExpr f (ni:i) ne
Automaton _ _ -> [ flattenExpr f i (Fix e) ]
-- | Returns the initial default value for a given type, e.g. 0 for numbers, false for boolean etc.
defaultValue :: GTLType -> GTLConstant
defaultValue tp = case unfix tp of
GTLInt -> Fix $ GTLIntVal 0
GTLByte -> Fix $ GTLByteVal 0
GTLBool -> Fix $ GTLBoolVal False
GTLFloat -> Fix $ GTLFloatVal 0
GTLEnum (x:xs) -> Fix $ GTLEnumVal x
GTLArray sz tp -> Fix $ GTLArrayVal (genericReplicate sz (defaultValue tp))
GTLTuple tps -> Fix $ GTLTupleVal (fmap defaultValue tps)
GTLNamed _ tp -> defaultValue tp
constantToExpr :: Set [String] -> GTLConstant -> TypedExpr v
constantToExpr enums c = case unfix c of
GTLIntVal v -> Fix $ Typed gtlInt (Value (GTLIntVal v))
GTLByteVal v -> Fix $ Typed gtlByte (Value (GTLByteVal v))
GTLBoolVal v -> Fix $ Typed gtlBool (Value (GTLBoolVal v))
GTLFloatVal v -> Fix $ Typed gtlBool (Value (GTLFloatVal v))
GTLEnumVal v -> case find (elem v) enums of
Just enum -> Fix $ Typed (gtlEnum enum) (Value (GTLEnumVal v))
GTLArrayVal vs -> let e:es = fmap (constantToExpr enums) vs
tp = getType (unfix e)
in Fix $ Typed (gtlArray (genericLength vs) tp) (Value (GTLArrayVal (e:es)))
GTLTupleVal vs -> let es = fmap (constantToExpr enums) vs
tps = fmap (getType.unfix) es
in Fix $ Typed (gtlTuple tps) (Value (GTLTupleVal es))
instance (Ord v,Show v) => AtomContainer [TypedExpr v] (TypedExpr v) where
atomsTrue = []
atomSingleton True x = [x]
atomSingleton False x = [distributeNot x]
compareAtoms x y = compareAtoms' EEQ x y
where
compareAtoms' p [] [] = p
compareAtoms' p [] _ = case p of
EEQ -> EGT
EGT -> EGT
_ -> EUNK
compareAtoms' p (x:xs) ys = case compareAtoms'' p x ys of
Nothing -> case p of
EEQ -> compareAtoms' ELT xs ys
ELT -> compareAtoms' ELT xs ys
ENEQ -> ENEQ
_ -> EUNK
Just (p',ys') -> compareAtoms' p' xs ys'
compareAtoms'' p x [] = Nothing
compareAtoms'' p x (y:ys) = case compareExpr x y of
EEQ -> Just (p,ys)
ELT -> case p of
EEQ -> Just (ELT,ys)
ELT -> Just (ELT,ys)
_ -> Just (EUNK,ys)
EGT -> case p of
EEQ -> Just (EGT,ys)
EGT -> Just (EGT,ys)
_ -> Just (EUNK,ys)
ENEQ -> Just (ENEQ,ys)
EUNK -> case compareAtoms'' p x ys of
Nothing -> Nothing
Just (p',ys') -> Just (p',y:ys')
mergeAtoms [] ys = Just ys
mergeAtoms (x:xs) ys = case mergeAtoms' x ys of
Nothing -> Nothing
Just ys' -> mergeAtoms xs ys'
where
mergeAtoms' x [] = Just [x]
mergeAtoms' x (y:ys) = case compareExpr x y of
EEQ -> Just (y:ys)
ELT -> Just (x:ys)
EGT -> Just (y:ys)
EUNK -> case mergeAtoms' x ys of
Nothing -> Nothing
Just ys' -> Just (y:ys')
ENEQ -> Nothing
| hguenther/gtl | lib/Language/GTL/Expression.hs | bsd-3-clause | 48,877 | 1 | 34 | 15,963 | 18,003 | 8,951 | 9,052 | 1,034 | 72 |
module Platform.Test where
import Data.Int
import Data.List
import qualified Data.Map.Strict as S
import Control.Monad.State
import Control.Monad.Trans.Maybe
import System.Directory
import System.Exit
import System.FilePath.Posix
import Platform.Minimal64
import Spec.Decode
import Spec.Execute
import Platform.Run (readProgram)
import Platform.BufferMMIO
import Platform.Plic
import Spec.CSRFile
import Spec.Machine
import Spec.Spec
import Utility.Utility
import Spec.VirtualMemory
import Utility.MapMemory
data Test = Test { name :: String, instructionSet :: InstructionSet, input :: String, returnValue :: Int64, output :: String }
runTest :: Test -> IO Bool
runTest (Test name iset input returnValue output) = do
result <- runFile iset ("test/build/" ++ name) input
let isSuccess = (result == (returnValue, output))
when (not isSuccess) (putStrLn ("Running " ++ name ++ " gave output " ++ show result ++ " but expected " ++ show (returnValue, output)))
return $ isSuccess
-- TODO: Read this from a file.
tests :: [Test]
tests =
[Test "add64" RV64I "" 11 "",
Test "ebreak64" RV64IM "" 0 "D\n?\n",
Test "mul_support64" RV64IM "" 0 "A\n",
Test "mul_support64" RV64I "" 0 "cA\n",
Test "sub64" RV64I "" 7 "",
Test "mul64" RV64IM "" 42 "",
Test "and64" RV64I "" 35 "",
Test "or64" RV64IM "" 111 "",
Test "xor64" RV64I "" 76 "",
Test "csr64" RV64IM "" 29 "",
Test "hello64" RV64IM "" 0 "Hello, world!\n",
Test "reverse64" RV64IM "asdf" 0 "fdsa\n",
Test "thuemorse64" RV64IM "" 0 "01101001100101101001011001101001100101100110100101101001100101101001011001101001011010011001011001101001100101101001011001101001\n",
Test "illegal64" RV64IM "" 0 "!\n?\n"]
--Test "time64" RV64IM "" 0 "a\nb\nc\nd\ne\nf\ng\nh\ni\nj\nk\n!\n.\n"]
getRiscvTests :: IO [Test]
getRiscvTests = do
ls <- getDirectoryContents "riscv-tests/isa"
return (map makeTest (sort (filter isEnabled ls)))
where makeTest f = Test ("../../riscv-tests/isa/" ++ f) RV64IMAF "" 0 ""
isEnabled f = (isPrefixOf "rv64mi-" f || isPrefixOf "rv64si-" f || isPrefixOf "rv64ui-" f || isPrefixOf "rv64ua-" f
|| isPrefixOf "rv64uf-" f)
&& not (isSuffixOf ".dump" f)
runProgram :: InstructionSet -> Maybe Int64 -> Minimal64 -> String -> (Int64, String)
runProgram iset maybeToHostAddress comp input = (returnValue, output)
where ((returnValue, _), output) = runBufferIO (runStateT (stepHelper iset maybeToHostAddress (return DoNothing) (return (mtimecmp_addr,0)) (\inst -> return (inst /= 0x6f )) (return ()):: BufferState Minimal64 Int64) comp) input
runFile :: InstructionSet -> String -> String -> IO (Int64, String)
runFile iset f input = do
putStrLn $ "Run" ++ f
(maybeToHostAddress, mem) <- readProgram f
let c = Minimal64 { registers = S.empty,
fpregisters = (take 31 $ repeat 0),
csrs = (resetCSRFile 64),
pc = 0x80000000,
nextPC = 0,
privMode = Machine,
mem = MapMemory { bytes = S.fromList mem, reservation = Nothing } } in
return $ runProgram iset maybeToHostAddress c input
main :: IO ()
main = do
riscvTests <- getRiscvTests
let allTests = tests ++ riscvTests
results <- mapM runTest allTests
mapM_ (putStrLn . show) (zip (map (takeBaseName . name) allTests) results)
if all id results
then do
putStrLn "All tests passed!"
exitWith ExitSuccess
else do
putStrLn $ (show (sum (map fromEnum results))) ++ "/" ++ (show $ length allTests) ++ " tests passed."
exitWith (ExitFailure 1)
| mit-plv/riscv-semantics | src/Platform/Test.hs | bsd-3-clause | 3,710 | 0 | 19 | 855 | 1,158 | 606 | 552 | 80 | 2 |
import System.Environment (getArgs)
pali :: Integer -> Bool
pali x = x == reve x
reve :: Integer -> Integer
reve x = read . reverse $ show x
revadd :: Integer -> Integer -> String
revadd x y | pali y = show x ++ " " ++ show y
| x > 100 = "not found"
| otherwise = revadd (x + 1) (y + reve y)
main :: IO ()
main = do
[inpFile] <- getArgs
input <- readFile inpFile
putStr . unlines . map (revadd 0 . read) $ lines input
| nikai3d/ce-challenges | moderate/reverse_add.hs | bsd-3-clause | 466 | 0 | 12 | 143 | 219 | 105 | 114 | 14 | 1 |
module Data.TrieMap.ProdMap.Tests where
import Data.TrieMap.ProdMap ()
import Data.TrieMap.WordMap ()
import Data.Word
import qualified Data.TrieMap.TrieKey.Tests as TrieKeyTests
import Test.QuickCheck
tests :: Property
tests = TrieKeyTests.tests "Data.TrieMap.ProdMap" (0 :: Word, 0 :: Word) | lowasser/TrieMap | Data/TrieMap/ProdMap/Tests.hs | bsd-3-clause | 296 | 0 | 6 | 34 | 75 | 49 | 26 | 8 | 1 |
{-# LANGUAGE BangPatterns, ScopedTypeVariables #-}
-- |
-- Module: Database.PostgreSQL.Simple.Time.Internal.Parser
-- Copyright: (c) 2012-2015 Leon P Smith
-- (c) 2015 Bryan O'Sullivan
-- License: BSD3
-- Maintainer: Leon P Smith <leon@melding-monads.com>
-- Stability: experimental
--
-- Parsers for parsing dates and times.
module Database.PostgreSQL.Simple.Time.Internal.Parser
(
day
, localTime
, timeOfDay
, timeZone
, UTCOffsetHMS(..)
, timeZoneHMS
, localToUTCTimeOfDayHMS
, utcTime
, zonedTime
) where
import Control.Applicative ((<$>), (<*>), (<*), (*>))
import Database.PostgreSQL.Simple.Compat (toPico)
import Data.Attoparsec.ByteString.Char8 as A
import Data.Bits ((.&.))
import Data.Char (ord)
import Data.Fixed (Pico)
import Data.Int (Int64)
import Data.Maybe (fromMaybe)
import Data.Time.Calendar (Day, fromGregorianValid, addDays)
import Data.Time.Clock (UTCTime(..))
import qualified Data.ByteString.Char8 as B8
import qualified Data.Time.LocalTime as Local
-- | Parse a date of the form @YYYY-MM-DD@.
day :: Parser Day
day = do
y <- decimal <* char '-'
m <- twoDigits <* char '-'
d <- twoDigits
maybe (fail "invalid date") return (fromGregorianValid y m d)
-- | Parse a two-digit integer (e.g. day of month, hour).
twoDigits :: Parser Int
twoDigits = do
a <- digit
b <- digit
let c2d c = ord c .&. 15
return $! c2d a * 10 + c2d b
-- | Parse a time of the form @HH:MM:SS[.SSS]@.
timeOfDay :: Parser Local.TimeOfDay
timeOfDay = do
h <- twoDigits <* char ':'
m <- twoDigits <* char ':'
s <- seconds
if h < 24 && m < 60 && s <= 60
then return (Local.TimeOfDay h m s)
else fail "invalid time"
-- | Parse a count of seconds, with the integer part being two digits
-- long.
seconds :: Parser Pico
seconds = do
real <- twoDigits
mc <- peekChar
case mc of
Just '.' -> do
t <- anyChar *> takeWhile1 isDigit
return $! parsePicos (fromIntegral real) t
_ -> return $! fromIntegral real
where
parsePicos :: Int64 -> B8.ByteString -> Pico
parsePicos a0 t = toPico (fromIntegral (t' * 10^n))
where n = max 0 (12 - B8.length t)
t' = B8.foldl' (\a c -> 10 * a + fromIntegral (ord c .&. 15)) a0
(B8.take 12 t)
-- | Parse a time zone, and return 'Nothing' if the offset from UTC is
-- zero. (This makes some speedups possible.)
timeZone :: Parser (Maybe Local.TimeZone)
timeZone = do
ch <- satisfy $ \c -> c == '+' || c == '-' || c == 'Z'
if ch == 'Z'
then return Nothing
else do
h <- twoDigits
mm <- peekChar
m <- case mm of
Just ':' -> anyChar *> twoDigits
_ -> return 0
let off | ch == '-' = negate off0
| otherwise = off0
off0 = h * 60 + m
case undefined of
_ | off == 0 ->
return Nothing
| h > 23 || m > 59 ->
fail "invalid time zone offset"
| otherwise ->
let !tz = Local.minutesToTimeZone off
in return (Just tz)
data UTCOffsetHMS = UTCOffsetHMS {-# UNPACK #-} !Int {-# UNPACK #-} !Int {-# UNPACK #-} !Int
-- | Parse a time zone, and return 'Nothing' if the offset from UTC is
-- zero. (This makes some speedups possible.)
timeZoneHMS :: Parser (Maybe UTCOffsetHMS)
timeZoneHMS = do
ch <- satisfy $ \c -> c == '+' || c == '-' || c == 'Z'
if ch == 'Z'
then return Nothing
else do
h <- twoDigits
m <- maybeTwoDigits
s <- maybeTwoDigits
case undefined of
_ | h == 0 && m == 0 && s == 0 ->
return Nothing
| h > 23 || m >= 60 || s >= 60 ->
fail "invalid time zone offset"
| otherwise ->
if ch == '+'
then let !tz = UTCOffsetHMS h m s
in return (Just tz)
else let !tz = UTCOffsetHMS (-h) (-m) (-s)
in return (Just tz)
where
maybeTwoDigits = do
ch <- peekChar
case ch of
Just ':' -> anyChar *> twoDigits
_ -> return 0
localToUTCTimeOfDayHMS :: UTCOffsetHMS -> Local.TimeOfDay -> (Integer, Local.TimeOfDay)
localToUTCTimeOfDayHMS (UTCOffsetHMS dh dm ds) (Local.TimeOfDay h m s) =
(\ !a !b -> (a,b)) dday (Local.TimeOfDay h'' m'' s'')
where
s' = s - fromIntegral ds
(!s'', m')
| s' < 0 = (s' + 60, m - dm - 1)
| s' >= 60 = (s' - 60, m - dm + 1)
| otherwise = (s' , m - dm )
(!m'', h')
| m' < 0 = (m' + 60, h - dh - 1)
| m' >= 60 = (m' - 60, h - dh + 1)
| otherwise = (m' , h - dh )
(!h'', dday)
| h' < 0 = (h' + 24, -1)
| h' >= 24 = (h' - 24, 1)
| otherwise = (h' , 0)
-- | Parse a date and time, of the form @YYYY-MM-DD HH:MM:SS@.
-- The space may be replaced with a @T@. The number of seconds may be
-- followed by a fractional component.
localTime :: Parser Local.LocalTime
localTime = Local.LocalTime <$> day <* daySep <*> timeOfDay
where daySep = satisfy (\c -> c == ' ' || c == 'T')
-- | Behaves as 'zonedTime', but converts any time zone offset into a
-- UTC time.
utcTime :: Parser UTCTime
utcTime = do
(Local.LocalTime d t) <- localTime
mtz <- timeZoneHMS
case mtz of
Nothing -> let !tt = Local.timeOfDayToTime t
in return (UTCTime d tt)
Just tz -> let !(dd,t') = localToUTCTimeOfDayHMS tz t
!d' = addDays dd d
!tt = Local.timeOfDayToTime t'
in return (UTCTime d' tt)
-- | Parse a date with time zone info. Acceptable formats:
--
-- @YYYY-MM-DD HH:MM:SS Z@
--
-- The first space may instead be a @T@, and the second space is
-- optional. The @Z@ represents UTC. The @Z@ may be replaced with a
-- time zone offset of the form @+0000@ or @-08:00@, where the first
-- two digits are hours, the @:@ is optional and the second two digits
-- (also optional) are minutes.
zonedTime :: Parser Local.ZonedTime
zonedTime = Local.ZonedTime <$> localTime <*> (fromMaybe utc <$> timeZone)
utc :: Local.TimeZone
utc = Local.TimeZone 0 False ""
| timmytofu/postgresql-simple | src/Database/PostgreSQL/Simple/Time/Internal/Parser.hs | bsd-3-clause | 6,189 | 0 | 21 | 1,863 | 1,877 | 962 | 915 | 140 | 4 |
module BowlingKata.Day5 (score) where
score :: [Int] -> Int
score ([]) = 0
score (lastRoll:[]) = lastRoll
score (roll1:roll2:[]) = roll1 + roll2
score (roll1:roll2:roll3:[]) = roll1 + roll2 + roll3
score (roll1:roll2:roll3:rolls) = do
if isStrike roll1
then 10 + roll2 + roll3 + score (roll2:roll3:rolls)
else if isSpare roll1 roll2
then 10 + roll3 + score (roll3:rolls)
else roll1 + roll2 + score (roll3:rolls)
isStrike :: Int -> Bool
isStrike roll = roll == 10
isSpare :: Int -> Int -> Bool
isSpare roll1 roll2 = roll1 + roll2 == 10
| Alex-Diez/haskell-tdd-kata | old-katas/src/BowlingKata/Day5.hs | bsd-3-clause | 642 | 0 | 12 | 200 | 275 | 144 | 131 | 16 | 3 |
module PackageManagement ( Transplantable(..)
, parseVersion
, parsePkgInfo
) where
import Distribution.Package (PackageIdentifier(..), PackageName(..))
import Distribution.Version (Version(..))
import Control.Monad (unless)
import Types
import MyMonad
import Process (outsideGhcPkg, insideGhcPkg)
import Util.Cabal (prettyPkgInfo, prettyVersion)
import qualified Util.Cabal (parseVersion, parsePkgInfo)
parseVersion :: String -> MyMonad Version
parseVersion s = case Util.Cabal.parseVersion s of
Nothing -> throwError $ MyException $ "Couldn't parse " ++ s ++ " as a package version"
Just version -> return version
parsePkgInfo :: String -> MyMonad PackageIdentifier
parsePkgInfo s = case Util.Cabal.parsePkgInfo s of
Nothing -> throwError $ MyException $ "Couldn't parse package identifier " ++ s
Just pkgInfo -> return pkgInfo
getDeps :: PackageIdentifier -> MyMonad [PackageIdentifier]
getDeps pkgInfo = do
let prettyPkg = prettyPkgInfo pkgInfo
debug $ "Extracting dependencies of " ++ prettyPkg
out <- indentMessages $ outsideGhcPkg ["field", prettyPkg, "depends"]
-- example output:
-- depends: ghc-prim-0.2.0.0-3fbcc20c802efcd7c82089ec77d92990
-- integer-gmp-0.2.0.0-fa82a0df93dc30b4a7c5654dd7c68cf4 builtin_rts
case words out of
[] -> throwError $ MyException $ "Couldn't parse ghc-pkg output to find dependencies of " ++ prettyPkg
_:depStrings -> do -- skip 'depends:'
indentMessages $ trace $ "Found dependency strings: " ++ unwords depStrings
mapM parsePkgInfo depStrings
-- things that can be copied from system's GHC pkg database
-- to GHC pkg database inside virtual environment
class Transplantable a where
transplantPackage :: a -> MyMonad ()
-- choose the highest installed version of package with this name
instance Transplantable PackageName where
transplantPackage (PackageName packageName) = do
debug $ "Copying package " ++ packageName ++ " to Virtual Haskell Environment."
indentMessages $ do
debug "Choosing package with highest version number."
out <- indentMessages $ outsideGhcPkg ["field", packageName, "version"]
-- example output:
-- version: 1.1.4
-- version: 1.2.0.3
let extractVersionString :: String -> MyMonad String
extractVersionString line = case words line of
[_, x] -> return x
_ -> throwError $ MyException $ "Couldn't extract version string from: " ++ line
versionStrings <- mapM extractVersionString $ lines out
indentMessages $ trace $ "Found version strings: " ++ unwords versionStrings
versions <- mapM parseVersion versionStrings
case versions of
[] -> throwError $ MyException $ "No versions of package " ++ packageName ++ " found"
(v:vs) -> do
indentMessages $ debug $ "Found: " ++ unwords (map prettyVersion versions)
let highestVersion = foldr max v vs
indentMessages $ debug $ "Using version: " ++ prettyVersion highestVersion
let pkgInfo = PackageIdentifier (PackageName packageName) highestVersion
transplantPackage pkgInfo
-- check if this package is already installed in Virtual Haskell Environment
checkIfInstalled :: PackageIdentifier -> MyMonad Bool
checkIfInstalled pkgInfo = do
let package = prettyPkgInfo pkgInfo
debug $ "Checking if " ++ package ++ " is already installed."
(do
_ <- indentMessages $ insideGhcPkg ["describe", package] Nothing
indentMessages $ debug "It is."
return True) `catchError` handler
where handler _ = do
debug "It's not."
return False
instance Transplantable PackageIdentifier where
transplantPackage pkgInfo = do
let prettyPkg = prettyPkgInfo pkgInfo
debug $ "Copying package " ++ prettyPkg ++ " to Virtual Haskell Environment."
indentMessages $ do
flag <- checkIfInstalled pkgInfo
unless flag $ do
deps <- getDeps pkgInfo
debug $ "Found: " ++ unwords (map prettyPkgInfo deps)
mapM_ transplantPackage deps
movePackage pkgInfo
-- copy single package that already has all deps satisfied
movePackage :: PackageIdentifier -> MyMonad ()
movePackage pkgInfo = do
let prettyPkg = prettyPkgInfo pkgInfo
debug $ "Moving package " ++ prettyPkg ++ " to Virtual Haskell Environment."
out <- outsideGhcPkg ["describe", prettyPkg]
_ <- insideGhcPkg ["register", "-"] (Just out)
return ()
| Paczesiowa/virthualenv | src/PackageManagement.hs | bsd-3-clause | 4,703 | 0 | 21 | 1,201 | 1,048 | 514 | 534 | 81 | 2 |
{-
(c) The University of Glasgow 2006
(c) The GRASP/AQUA Project, Glasgow University, 1992-1998
HsTypes: Abstract syntax: user-defined types
-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE UndecidableInstances #-} -- Note [Pass sensitive types]
-- in module PlaceHolder
{-# LANGUAGE ConstraintKinds #-}
module HsTypes (
HsType(..), LHsType, HsKind, LHsKind,
HsTyOp,LHsTyOp,
HsTyVarBndr(..), LHsTyVarBndr,
LHsTyVarBndrs(..),
HsWithBndrs(..),
HsTupleSort(..), HsExplicitFlag(..),
HsContext, LHsContext,
HsQuasiQuote(..),
HsTyWrapper(..),
HsTyLit(..),
HsIPName(..), hsIPNameFS,
LBangType, BangType, HsBang(..),
getBangType, getBangStrictness,
ConDeclField(..), LConDeclField, pprConDeclFields,
mkHsQTvs, hsQTvBndrs, isHsKindedTyVar, hsTvbAllKinded,
mkExplicitHsForAllTy, mkImplicitHsForAllTy, mkQualifiedHsForAllTy,
hsExplicitTvs,
hsTyVarName, mkHsWithBndrs, hsLKiTyVarNames,
hsLTyVarName, hsLTyVarNames, hsLTyVarLocName, hsLTyVarLocNames,
splitLHsInstDeclTy_maybe,
splitHsClassTy_maybe, splitLHsClassTy_maybe,
splitHsFunType,
splitHsAppTys, hsTyGetAppHead_maybe, mkHsAppTys, mkHsOpTy,
isWildcardTy, isNamedWildcardTy,
-- Printing
pprParendHsType, pprHsForAll, pprHsForAllExtra,
pprHsContext, pprHsContextNoArrow, pprHsContextMaybe
) where
import {-# SOURCE #-} HsExpr ( HsSplice, pprUntypedSplice )
import PlaceHolder ( PostTc,PostRn,DataId,PlaceHolder(..) )
import Name( Name )
import RdrName( RdrName )
import DataCon( HsBang(..) )
import TysPrim( funTyConName )
import Type
import HsDoc
import BasicTypes
import SrcLoc
import StaticFlags
import Outputable
import FastString
import Maybes( isJust )
import Data.Data hiding ( Fixity )
import Data.Maybe ( fromMaybe )
{-
************************************************************************
* *
Quasi quotes; used in types and elsewhere
* *
************************************************************************
-}
data HsQuasiQuote id = HsQuasiQuote
id -- The quasi-quoter
SrcSpan -- The span of the enclosed string
FastString -- The enclosed string
deriving (Data, Typeable)
instance OutputableBndr id => Outputable (HsQuasiQuote id) where
ppr = ppr_qq
ppr_qq :: OutputableBndr id => HsQuasiQuote id -> SDoc
ppr_qq (HsQuasiQuote quoter _ quote) =
char '[' <> ppr quoter <> ptext (sLit "|") <>
ppr quote <> ptext (sLit "|]")
{-
************************************************************************
* *
\subsection{Bang annotations}
* *
************************************************************************
-}
type LBangType name = Located (BangType name)
type BangType name = HsType name -- Bangs are in the HsType data type
getBangType :: LHsType a -> LHsType a
getBangType (L _ (HsBangTy _ ty)) = ty
getBangType ty = ty
getBangStrictness :: LHsType a -> HsBang
getBangStrictness (L _ (HsBangTy s _)) = s
getBangStrictness _ = HsNoBang
{-
************************************************************************
* *
\subsection{Data types}
* *
************************************************************************
This is the syntax for types as seen in type signatures.
Note [HsBSig binder lists]
~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider a binder (or pattern) decoarated with a type or kind,
\ (x :: a -> a). blah
forall (a :: k -> *) (b :: k). blah
Then we use a LHsBndrSig on the binder, so that the
renamer can decorate it with the variables bound
by the pattern ('a' in the first example, 'k' in the second),
assuming that neither of them is in scope already
See also Note [Kind and type-variable binders] in RnTypes
-}
type LHsContext name = Located (HsContext name)
type HsContext name = [LHsType name]
type LHsType name = Located (HsType name)
-- ^ May have 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnComma' when
-- in a list
type HsKind name = HsType name
type LHsKind name = Located (HsKind name)
type LHsTyVarBndr name = Located (HsTyVarBndr name)
data LHsTyVarBndrs name
= HsQTvs { hsq_kvs :: [Name] -- Kind variables
, hsq_tvs :: [LHsTyVarBndr name] -- Type variables
-- See Note [HsForAllTy tyvar binders]
}
deriving( Typeable )
deriving instance (DataId name) => Data (LHsTyVarBndrs name)
mkHsQTvs :: [LHsTyVarBndr RdrName] -> LHsTyVarBndrs RdrName
-- Just at RdrName because in the Name variant we should know just
-- what the kind-variable binders are; and we don't
-- We put an empty list (rather than a panic) for the kind vars so
-- that the pretty printer works ok on them.
mkHsQTvs tvs = HsQTvs { hsq_kvs = [], hsq_tvs = tvs }
emptyHsQTvs :: LHsTyVarBndrs name -- Use only when you know there are no kind binders
emptyHsQTvs = HsQTvs { hsq_kvs = [], hsq_tvs = [] }
hsQTvBndrs :: LHsTyVarBndrs name -> [LHsTyVarBndr name]
hsQTvBndrs = hsq_tvs
data HsWithBndrs name thing
= HsWB { hswb_cts :: thing -- Main payload (type or list of types)
, hswb_kvs :: PostRn name [Name] -- Kind vars
, hswb_tvs :: PostRn name [Name] -- Type vars
, hswb_wcs :: PostRn name [Name] -- Wildcards
}
deriving (Typeable)
deriving instance (Data name, Data thing, Data (PostRn name [Name]))
=> Data (HsWithBndrs name thing)
mkHsWithBndrs :: thing -> HsWithBndrs RdrName thing
mkHsWithBndrs x = HsWB { hswb_cts = x, hswb_kvs = PlaceHolder
, hswb_tvs = PlaceHolder
, hswb_wcs = PlaceHolder }
-- | These names are used early on to store the names of implicit
-- parameters. They completely disappear after type-checking.
newtype HsIPName = HsIPName FastString-- ?x
deriving( Eq, Data, Typeable )
hsIPNameFS :: HsIPName -> FastString
hsIPNameFS (HsIPName n) = n
instance Outputable HsIPName where
ppr (HsIPName n) = char '?' <> ftext n -- Ordinary implicit parameters
instance OutputableBndr HsIPName where
pprBndr _ n = ppr n -- Simple for now
pprInfixOcc n = ppr n
pprPrefixOcc n = ppr n
data HsTyVarBndr name
= UserTyVar -- no explicit kinding
name
| KindedTyVar
name
(LHsKind name) -- The user-supplied kind signature
-- ^
-- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen',
-- 'ApiAnnotation.AnnDcolon', 'ApiAnnotation.AnnClose'
deriving (Typeable)
deriving instance (DataId name) => Data (HsTyVarBndr name)
-- | Does this 'HsTyVarBndr' come with an explicit kind annotation?
isHsKindedTyVar :: HsTyVarBndr name -> Bool
isHsKindedTyVar (UserTyVar {}) = False
isHsKindedTyVar (KindedTyVar {}) = True
-- | Do all type variables in this 'LHsTyVarBndr' come with kind annotations?
hsTvbAllKinded :: LHsTyVarBndrs name -> Bool
hsTvbAllKinded = all (isHsKindedTyVar . unLoc) . hsQTvBndrs
-- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnDcolon',
-- 'ApiAnnotation.AnnTilde','ApiAnnotation.AnnRarrow',
-- 'ApiAnnotation.AnnOpen','ApiAnnotation.AnnClose',
-- 'ApiAnnotation.AnnComma'
data HsType name
= HsForAllTy HsExplicitFlag -- Renamer leaves this flag unchanged, to record the way
-- the user wrote it originally, so that the printer can
-- print it as the user wrote it
(Maybe SrcSpan) -- Indicates whether extra constraints may be inferred.
-- When Nothing, no, otherwise the location of the extra-
-- constraints wildcard is stored. For instance, for the
-- signature (Eq a, _) => a -> a -> Bool, this field would
-- be something like (Just 1:8), with 1:8 being line 1,
-- column 8.
(LHsTyVarBndrs name)
(LHsContext name)
(LHsType name)
-- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnForall',
-- 'ApiAnnotation.AnnDot','ApiAnnotation.AnnDarrow'
| HsTyVar name -- Type variable, type constructor, or data constructor
-- see Note [Promotions (HsTyVar)]
| HsAppTy (LHsType name)
(LHsType name)
| HsFunTy (LHsType name) -- function type
(LHsType name)
-- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnRarrow',
| HsListTy (LHsType name) -- Element type
| HsPArrTy (LHsType name) -- Elem. type of parallel array: [:t:]
| HsTupleTy HsTupleSort
[LHsType name] -- Element types (length gives arity)
| HsOpTy (LHsType name) (LHsTyOp name) (LHsType name)
| HsParTy (LHsType name) -- See Note [Parens in HsSyn] in HsExpr
-- Parenthesis preserved for the precedence re-arrangement in RnTypes
-- It's important that a * (b + c) doesn't get rearranged to (a*b) + c!
| HsIParamTy HsIPName -- (?x :: ty)
(LHsType name) -- Implicit parameters as they occur in contexts
| HsEqTy (LHsType name) -- ty1 ~ ty2
(LHsType name) -- Always allowed even without TypeOperators, and has special kinding rule
| HsKindSig (LHsType name) -- (ty :: kind)
(LHsKind name) -- A type with a kind signature
| HsQuasiQuoteTy (HsQuasiQuote name)
| HsSpliceTy (HsSplice name)
(PostTc name Kind)
| HsDocTy (LHsType name) LHsDocString -- A documented type
| HsBangTy HsBang (LHsType name) -- Bang-style type annotations
| HsRecTy [LConDeclField name] -- Only in data type declarations
| HsCoreTy Type -- An escape hatch for tunnelling a *closed*
-- Core Type through HsSyn.
| HsExplicitListTy -- A promoted explicit list
(PostTc name Kind) -- See Note [Promoted lists and tuples]
[LHsType name]
| HsExplicitTupleTy -- A promoted explicit tuple
[PostTc name Kind] -- See Note [Promoted lists and tuples]
[LHsType name]
| HsTyLit HsTyLit -- A promoted numeric literal.
| HsWrapTy HsTyWrapper (HsType name) -- only in typechecker output
| HsWildcardTy -- A type wildcard
| HsNamedWildcardTy name -- A named wildcard
deriving (Typeable)
deriving instance (DataId name) => Data (HsType name)
data HsTyLit
= HsNumTy Integer
| HsStrTy FastString
deriving (Data, Typeable)
data HsTyWrapper
= WpKiApps [Kind] -- kind instantiation: [] k1 k2 .. kn
deriving (Data, Typeable)
type LHsTyOp name = HsTyOp (Located name)
type HsTyOp name = (HsTyWrapper, name)
mkHsOpTy :: LHsType name -> Located name -> LHsType name -> HsType name
mkHsOpTy ty1 op ty2 = HsOpTy ty1 (WpKiApps [], op) ty2
{-
Note [HsForAllTy tyvar binders]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
After parsing:
* Implicit => empty
Explicit => the variables the user wrote
After renaming
* Implicit => the *type* variables free in the type
Explicit => the variables the user wrote (renamed)
Qualified currently behaves exactly as Implicit,
but it is deprecated to use it for implicit quantification.
In this case, GHC 7.10 gives a warning; see
Note [Context quantification] and Trac #4426.
In GHC 7.12, Qualified will no longer bind variables
and this will become an error.
The kind variables bound in the hsq_kvs field come both
a) from the kind signatures on the kind vars (eg k1)
b) from the scope of the forall (eg k2)
Example: f :: forall (a::k1) b. T a (b::k2)
Note [Unit tuples]
~~~~~~~~~~~~~~~~~~
Consider the type
type instance F Int = ()
We want to parse that "()"
as HsTupleTy HsBoxedOrConstraintTuple [],
NOT as HsTyVar unitTyCon
Why? Because F might have kind (* -> Constraint), so we when parsing we
don't know if that tuple is going to be a constraint tuple or an ordinary
unit tuple. The HsTupleSort flag is specifically designed to deal with
that, but it has to work for unit tuples too.
Note [Promotions (HsTyVar)]
~~~~~~~~~~~~~~~~~~~~~~~~~~~
HsTyVar: A name in a type or kind.
Here are the allowed namespaces for the name.
In a type:
Var: not allowed
Data: promoted data constructor
Tv: type variable
TcCls before renamer: type constructor, class constructor, or promoted data constructor
TcCls after renamer: type constructor or class constructor
In a kind:
Var, Data: not allowed
Tv: kind variable
TcCls: kind constructor or promoted type constructor
Note [Promoted lists and tuples]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Notice the difference between
HsListTy HsExplicitListTy
HsTupleTy HsExplicitListTupleTy
E.g. f :: [Int] HsListTy
g3 :: T '[] All these use
g2 :: T '[True] HsExplicitListTy
g1 :: T '[True,False]
g1a :: T [True,False] (can omit ' where unambiguous)
kind of T :: [Bool] -> * This kind uses HsListTy!
E.g. h :: (Int,Bool) HsTupleTy; f is a pair
k :: S '(True,False) HsExplicitTypleTy; S is indexed by
a type-level pair of booleans
kind of S :: (Bool,Bool) -> * This kind uses HsExplicitTupleTy
Note [Distinguishing tuple kinds]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Apart from promotion, tuples can have one of three different kinds:
x :: (Int, Bool) -- Regular boxed tuples
f :: Int# -> (# Int#, Int# #) -- Unboxed tuples
g :: (Eq a, Ord a) => a -- Constraint tuples
For convenience, internally we use a single constructor for all of these,
namely HsTupleTy, but keep track of the tuple kind (in the first argument to
HsTupleTy, a HsTupleSort). We can tell if a tuple is unboxed while parsing,
because of the #. However, with -XConstraintKinds we can only distinguish
between constraint and boxed tuples during type checking, in general. Hence the
four constructors of HsTupleSort:
HsUnboxedTuple -> Produced by the parser
HsBoxedTuple -> Certainly a boxed tuple
HsConstraintTuple -> Certainly a constraint tuple
HsBoxedOrConstraintTuple -> Could be a boxed or a constraint
tuple. Produced by the parser only,
disappears after type checking
-}
data HsTupleSort = HsUnboxedTuple
| HsBoxedTuple
| HsConstraintTuple
| HsBoxedOrConstraintTuple
deriving (Data, Typeable)
data HsExplicitFlag = Qualified | Implicit | Explicit deriving (Data, Typeable)
type LConDeclField name = Located (ConDeclField name)
-- ^ May have 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnComma' when
-- in a list
data ConDeclField name -- Record fields have Haddoc docs on them
= ConDeclField { cd_fld_names :: [Located name],
cd_fld_type :: LBangType name,
cd_fld_doc :: Maybe LHsDocString }
-- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnDcolon'
deriving (Typeable)
deriving instance (DataId name) => Data (ConDeclField name)
-----------------------
-- Combine adjacent for-alls.
-- The following awkward situation can happen otherwise:
-- f :: forall a. ((Num a) => Int)
-- might generate HsForAll (Just [a]) [] (HsForAll Nothing [Num a] t)
-- Then a isn't discovered as ambiguous, and we abstract the AbsBinds wrt []
-- but the export list abstracts f wrt [a]. Disaster.
--
-- A valid type must have one for-all at the top of the type, or of the fn arg types
mkImplicitHsForAllTy :: LHsContext RdrName -> LHsType RdrName -> HsType RdrName
mkExplicitHsForAllTy :: [LHsTyVarBndr RdrName] -> LHsContext RdrName -> LHsType RdrName -> HsType RdrName
mkQualifiedHsForAllTy :: LHsContext RdrName -> LHsType RdrName -> HsType RdrName
mkImplicitHsForAllTy ctxt ty = mkHsForAllTy Implicit [] ctxt ty
mkExplicitHsForAllTy tvs ctxt ty = mkHsForAllTy Explicit tvs ctxt ty
mkQualifiedHsForAllTy ctxt ty = mkHsForAllTy Qualified [] ctxt ty
mkHsForAllTy :: HsExplicitFlag -> [LHsTyVarBndr RdrName] -> LHsContext RdrName -> LHsType RdrName -> HsType RdrName
-- Smart constructor for HsForAllTy
mkHsForAllTy exp tvs (L _ []) ty = mk_forall_ty exp tvs ty
mkHsForAllTy exp tvs ctxt ty = HsForAllTy exp extra (mkHsQTvs tvs) cleanCtxt ty
where -- Separate the extra-constraints wildcard when present
(cleanCtxt, extra)
| (L l HsWildcardTy) <- ignoreParens (last (unLoc ctxt)) = (init `fmap` ctxt, Just l)
| otherwise = (ctxt, Nothing)
ignoreParens (L _ (HsParTy ty)) = ty
ignoreParens ty = ty
-- mk_forall_ty makes a pure for-all type (no context)
mk_forall_ty :: HsExplicitFlag -> [LHsTyVarBndr RdrName] -> LHsType RdrName -> HsType RdrName
mk_forall_ty exp1 tvs1 (L _ (HsForAllTy exp2 extra qtvs2 ctxt ty))
= addExtra $ mkHsForAllTy (exp1 `plus` exp2) (tvs1 ++ hsq_tvs qtvs2) ctxt ty
where addExtra (HsForAllTy exp _ qtvs ctxt ty) = HsForAllTy exp extra qtvs ctxt ty
addExtra ty = ty -- Impossible, as mkHsForAllTy always returns a HsForAllTy
mk_forall_ty exp tvs (L _ (HsParTy ty)) = mk_forall_ty exp tvs ty
mk_forall_ty exp tvs ty = HsForAllTy exp Nothing (mkHsQTvs tvs) (noLoc []) ty
-- Even if tvs is empty, we still make a HsForAll!
-- In the Implicit case, this signals the place to do implicit quantification
-- In the Explicit case, it prevents implicit quantification
-- (see the sigtype production in Parser.y)
-- so that (forall. ty) isn't implicitly quantified
plus :: HsExplicitFlag -> HsExplicitFlag -> HsExplicitFlag
Qualified `plus` Qualified = Qualified
Explicit `plus` _ = Explicit
_ `plus` Explicit = Explicit
_ `plus` _ = Implicit
hsExplicitTvs :: LHsType Name -> [Name]
-- The explicitly-given forall'd type variables of a HsType
hsExplicitTvs (L _ (HsForAllTy Explicit _ tvs _ _)) = hsLKiTyVarNames tvs
hsExplicitTvs _ = []
---------------------
hsTyVarName :: HsTyVarBndr name -> name
hsTyVarName (UserTyVar n) = n
hsTyVarName (KindedTyVar n _) = n
hsLTyVarName :: LHsTyVarBndr name -> name
hsLTyVarName = hsTyVarName . unLoc
hsLTyVarNames :: LHsTyVarBndrs name -> [name]
-- Type variables only
hsLTyVarNames qtvs = map hsLTyVarName (hsQTvBndrs qtvs)
hsLKiTyVarNames :: LHsTyVarBndrs Name -> [Name]
-- Kind and type variables
hsLKiTyVarNames (HsQTvs { hsq_kvs = kvs, hsq_tvs = tvs })
= kvs ++ map hsLTyVarName tvs
hsLTyVarLocName :: LHsTyVarBndr name -> Located name
hsLTyVarLocName = fmap hsTyVarName
hsLTyVarLocNames :: LHsTyVarBndrs name -> [Located name]
hsLTyVarLocNames qtvs = map hsLTyVarLocName (hsQTvBndrs qtvs)
---------------------
isWildcardTy :: HsType a -> Bool
isWildcardTy HsWildcardTy = True
isWildcardTy _ = False
isNamedWildcardTy :: HsType a -> Bool
isNamedWildcardTy (HsNamedWildcardTy _) = True
isNamedWildcardTy _ = False
splitHsAppTys :: LHsType n -> [LHsType n] -> (LHsType n, [LHsType n])
splitHsAppTys (L _ (HsAppTy f a)) as = splitHsAppTys f (a:as)
splitHsAppTys (L _ (HsParTy f)) as = splitHsAppTys f as
splitHsAppTys f as = (f,as)
-- retrieve the name of the "head" of a nested type application
-- somewhat like splitHsAppTys, but a little more thorough
-- used to examine the result of a GADT-like datacon, so it doesn't handle
-- *all* cases (like lists, tuples, (~), etc.)
hsTyGetAppHead_maybe :: LHsType n -> Maybe (n, [LHsType n])
hsTyGetAppHead_maybe = go []
where
go tys (L _ (HsTyVar n)) = Just (n, tys)
go tys (L _ (HsAppTy l r)) = go (r : tys) l
go tys (L _ (HsOpTy l (_, L _ n) r)) = Just (n, l : r : tys)
go tys (L _ (HsParTy t)) = go tys t
go tys (L _ (HsKindSig t _)) = go tys t
go _ _ = Nothing
mkHsAppTys :: OutputableBndr n => LHsType n -> [LHsType n] -> HsType n
mkHsAppTys fun_ty [] = pprPanic "mkHsAppTys" (ppr fun_ty)
mkHsAppTys fun_ty (arg_ty:arg_tys)
= foldl mk_app (HsAppTy fun_ty arg_ty) arg_tys
where
mk_app fun arg = HsAppTy (noLoc fun) arg
-- Add noLocs for inner nodes of the application;
-- they are never used
splitLHsInstDeclTy_maybe
:: LHsType name
-> Maybe (LHsTyVarBndrs name, HsContext name, Located name, [LHsType name])
-- Split up an instance decl type, returning the pieces
splitLHsInstDeclTy_maybe inst_ty = do
let (tvs, cxt, ty) = splitLHsForAllTy inst_ty
(cls, tys) <- splitLHsClassTy_maybe ty
return (tvs, cxt, cls, tys)
splitLHsForAllTy
:: LHsType name
-> (LHsTyVarBndrs name, HsContext name, LHsType name)
splitLHsForAllTy poly_ty
= case unLoc poly_ty of
HsParTy ty -> splitLHsForAllTy ty
HsForAllTy _ _ tvs cxt ty -> (tvs, unLoc cxt, ty)
_ -> (emptyHsQTvs, [], poly_ty)
-- The type vars should have been computed by now, even if they were implicit
splitHsClassTy_maybe :: HsType name -> Maybe (name, [LHsType name])
splitHsClassTy_maybe ty = fmap (\(L _ n, tys) -> (n, tys)) $ splitLHsClassTy_maybe (noLoc ty)
splitLHsClassTy_maybe :: LHsType name -> Maybe (Located name, [LHsType name])
--- Watch out.. in ...deriving( Show )... we use this on
--- the list of partially applied predicates in the deriving,
--- so there can be zero args.
-- In TcDeriv we also use this to figure out what data type is being
-- mentioned in a deriving (Generic (Foo bar baz)) declaration (i.e. "Foo").
splitLHsClassTy_maybe ty
= checkl ty []
where
checkl (L l ty) args = case ty of
HsTyVar t -> Just (L l t, args)
HsAppTy l r -> checkl l (r:args)
HsOpTy l (_, tc) r -> checkl (fmap HsTyVar tc) (l:r:args)
HsParTy t -> checkl t args
HsKindSig ty _ -> checkl ty args
_ -> Nothing
-- splitHsFunType decomposes a type (t1 -> t2 ... -> tn)
-- Breaks up any parens in the result type:
-- splitHsFunType (a -> (b -> c)) = ([a,b], c)
-- Also deals with (->) t1 t2; that is why it only works on LHsType Name
-- (see Trac #9096)
splitHsFunType :: LHsType Name -> ([LHsType Name], LHsType Name)
splitHsFunType (L _ (HsParTy ty))
= splitHsFunType ty
splitHsFunType (L _ (HsFunTy x y))
| (args, res) <- splitHsFunType y
= (x:args, res)
splitHsFunType orig_ty@(L _ (HsAppTy t1 t2))
= go t1 [t2]
where -- Look for (->) t1 t2, possibly with parenthesisation
go (L _ (HsTyVar fn)) tys | fn == funTyConName
, [t1,t2] <- tys
, (args, res) <- splitHsFunType t2
= (t1:args, res)
go (L _ (HsAppTy t1 t2)) tys = go t1 (t2:tys)
go (L _ (HsParTy ty)) tys = go ty tys
go _ _ = ([], orig_ty) -- Failure to match
splitHsFunType other = ([], other)
{-
************************************************************************
* *
\subsection{Pretty printing}
* *
************************************************************************
-}
instance (OutputableBndr name) => Outputable (HsType name) where
ppr ty = pprHsType ty
instance Outputable HsTyLit where
ppr = ppr_tylit
instance (OutputableBndr name) => Outputable (LHsTyVarBndrs name) where
ppr (HsQTvs { hsq_kvs = kvs, hsq_tvs = tvs })
= sep [ ifPprDebug $ braces (interppSP kvs), interppSP tvs ]
instance (OutputableBndr name) => Outputable (HsTyVarBndr name) where
ppr (UserTyVar n) = ppr n
ppr (KindedTyVar n k) = parens $ hsep [ppr n, dcolon, ppr k]
instance (Outputable thing) => Outputable (HsWithBndrs name thing) where
ppr (HsWB { hswb_cts = ty }) = ppr ty
pprHsForAll :: OutputableBndr name => HsExplicitFlag -> LHsTyVarBndrs name -> LHsContext name -> SDoc
pprHsForAll exp = pprHsForAllExtra exp Nothing
-- | Version of 'pprHsForAll' that can also print an extra-constraints
-- wildcard, e.g. @_ => a -> Bool@ or @(Show a, _) => a -> String@. This
-- underscore will be printed when the 'Maybe SrcSpan' argument is a 'Just'
-- containing the location of the extra-constraints wildcard. A special
-- function for this is needed, as the extra-constraints wildcard is removed
-- from the actual context and type, and stored in a separate field, thus just
-- printing the type will not print the extra-constraints wildcard.
pprHsForAllExtra :: OutputableBndr name => HsExplicitFlag -> Maybe SrcSpan -> LHsTyVarBndrs name -> LHsContext name -> SDoc
pprHsForAllExtra exp extra qtvs cxt
| show_forall = forall_part <+> pprHsContextExtra show_extra (unLoc cxt)
| otherwise = pprHsContextExtra show_extra (unLoc cxt)
where
show_extra = isJust extra
show_forall = opt_PprStyle_Debug
|| (not (null (hsQTvBndrs qtvs)) && is_explicit)
is_explicit = case exp of {Explicit -> True; Implicit -> False; Qualified -> False}
forall_part = forAllLit <+> ppr qtvs <> dot
pprHsContext :: (OutputableBndr name) => HsContext name -> SDoc
pprHsContext = maybe empty (<+> darrow) . pprHsContextMaybe
pprHsContextNoArrow :: (OutputableBndr name) => HsContext name -> SDoc
pprHsContextNoArrow = fromMaybe empty . pprHsContextMaybe
pprHsContextMaybe :: (OutputableBndr name) => HsContext name -> Maybe SDoc
pprHsContextMaybe [] = Nothing
pprHsContextMaybe [L _ pred] = Just $ ppr_mono_ty FunPrec pred
pprHsContextMaybe cxt = Just $ parens (interpp'SP cxt)
-- True <=> print an extra-constraints wildcard, e.g. @(Show a, _) =>@
pprHsContextExtra :: (OutputableBndr name) => Bool -> HsContext name -> SDoc
pprHsContextExtra False = pprHsContext
pprHsContextExtra True
= \ctxt -> case ctxt of
[] -> char '_' <+> darrow
_ -> parens (sep (punctuate comma ctxt')) <+> darrow
where ctxt' = map ppr ctxt ++ [char '_']
pprConDeclFields :: OutputableBndr name => [LConDeclField name] -> SDoc
pprConDeclFields fields = braces (sep (punctuate comma (map ppr_fld fields)))
where
ppr_fld (L _ (ConDeclField { cd_fld_names = ns, cd_fld_type = ty,
cd_fld_doc = doc }))
= ppr_names ns <+> dcolon <+> ppr ty <+> ppr_mbDoc doc
ppr_names [n] = ppr n
ppr_names ns = sep (punctuate comma (map ppr ns))
{-
Note [Printing KindedTyVars]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Trac #3830 reminded me that we should really only print the kind
signature on a KindedTyVar if the kind signature was put there by the
programmer. During kind inference GHC now adds a PostTcKind to UserTyVars,
rather than converting to KindedTyVars as before.
(As it happens, the message in #3830 comes out a different way now,
and the problem doesn't show up; but having the flag on a KindedTyVar
seems like the Right Thing anyway.)
-}
-- Printing works more-or-less as for Types
pprHsType, pprParendHsType :: (OutputableBndr name) => HsType name -> SDoc
pprHsType ty = getPprStyle $ \sty -> ppr_mono_ty TopPrec (prepare sty ty)
pprParendHsType ty = ppr_mono_ty TyConPrec ty
-- Before printing a type
-- (a) Remove outermost HsParTy parens
-- (b) Drop top-level for-all type variables in user style
-- since they are implicit in Haskell
prepare :: PprStyle -> HsType name -> HsType name
prepare sty (HsParTy ty) = prepare sty (unLoc ty)
prepare _ ty = ty
ppr_mono_lty :: (OutputableBndr name) => TyPrec -> LHsType name -> SDoc
ppr_mono_lty ctxt_prec ty = ppr_mono_ty ctxt_prec (unLoc ty)
ppr_mono_ty :: (OutputableBndr name) => TyPrec -> HsType name -> SDoc
ppr_mono_ty ctxt_prec (HsForAllTy exp extra tvs ctxt ty)
= maybeParen ctxt_prec FunPrec $
sep [pprHsForAllExtra exp extra tvs ctxt, ppr_mono_lty TopPrec ty]
ppr_mono_ty _ (HsBangTy b ty) = ppr b <> ppr_mono_lty TyConPrec ty
ppr_mono_ty _ (HsQuasiQuoteTy qq) = ppr qq
ppr_mono_ty _ (HsRecTy flds) = pprConDeclFields flds
ppr_mono_ty _ (HsTyVar name) = pprPrefixOcc name
ppr_mono_ty prec (HsFunTy ty1 ty2) = ppr_fun_ty prec ty1 ty2
ppr_mono_ty _ (HsTupleTy con tys) = tupleParens std_con (interpp'SP tys)
where std_con = case con of
HsUnboxedTuple -> UnboxedTuple
_ -> BoxedTuple
ppr_mono_ty _ (HsKindSig ty kind) = parens (ppr_mono_lty TopPrec ty <+> dcolon <+> ppr kind)
ppr_mono_ty _ (HsListTy ty) = brackets (ppr_mono_lty TopPrec ty)
ppr_mono_ty _ (HsPArrTy ty) = paBrackets (ppr_mono_lty TopPrec ty)
ppr_mono_ty prec (HsIParamTy n ty) = maybeParen prec FunPrec (ppr n <+> dcolon <+> ppr_mono_lty TopPrec ty)
ppr_mono_ty _ (HsSpliceTy s _) = pprUntypedSplice s
ppr_mono_ty _ (HsCoreTy ty) = ppr ty
ppr_mono_ty _ (HsExplicitListTy _ tys) = quote $ brackets (interpp'SP tys)
ppr_mono_ty _ (HsExplicitTupleTy _ tys) = quote $ parens (interpp'SP tys)
ppr_mono_ty _ (HsTyLit t) = ppr_tylit t
ppr_mono_ty _ HsWildcardTy = char '_'
ppr_mono_ty _ (HsNamedWildcardTy name) = ppr name
ppr_mono_ty ctxt_prec (HsWrapTy (WpKiApps _kis) ty)
= ppr_mono_ty ctxt_prec ty
-- We are not printing kind applications. If we wanted to do so, we should do
-- something like this:
{-
= go ctxt_prec kis ty
where
go ctxt_prec [] ty = ppr_mono_ty ctxt_prec ty
go ctxt_prec (ki:kis) ty
= maybeParen ctxt_prec TyConPrec $
hsep [ go FunPrec kis ty
, ptext (sLit "@") <> pprParendKind ki ]
-}
ppr_mono_ty ctxt_prec (HsEqTy ty1 ty2)
= maybeParen ctxt_prec TyOpPrec $
ppr_mono_lty TyOpPrec ty1 <+> char '~' <+> ppr_mono_lty TyOpPrec ty2
ppr_mono_ty ctxt_prec (HsAppTy fun_ty arg_ty)
= maybeParen ctxt_prec TyConPrec $
hsep [ppr_mono_lty FunPrec fun_ty, ppr_mono_lty TyConPrec arg_ty]
ppr_mono_ty ctxt_prec (HsOpTy ty1 (_wrapper, L _ op) ty2)
= maybeParen ctxt_prec TyOpPrec $
sep [ ppr_mono_lty TyOpPrec ty1
, sep [pprInfixOcc op, ppr_mono_lty TyOpPrec ty2 ] ]
-- Don't print the wrapper (= kind applications)
-- c.f. HsWrapTy
ppr_mono_ty _ (HsParTy ty)
= parens (ppr_mono_lty TopPrec ty)
-- Put the parens in where the user did
-- But we still use the precedence stuff to add parens because
-- toHsType doesn't put in any HsParTys, so we may still need them
ppr_mono_ty ctxt_prec (HsDocTy ty doc)
= maybeParen ctxt_prec TyOpPrec $
ppr_mono_lty TyOpPrec ty <+> ppr (unLoc doc)
-- we pretty print Haddock comments on types as if they were
-- postfix operators
--------------------------
ppr_fun_ty :: (OutputableBndr name) => TyPrec -> LHsType name -> LHsType name -> SDoc
ppr_fun_ty ctxt_prec ty1 ty2
= let p1 = ppr_mono_lty FunPrec ty1
p2 = ppr_mono_lty TopPrec ty2
in
maybeParen ctxt_prec FunPrec $
sep [p1, ptext (sLit "->") <+> p2]
--------------------------
ppr_tylit :: HsTyLit -> SDoc
ppr_tylit (HsNumTy i) = integer i
ppr_tylit (HsStrTy s) = text (show s)
| bitemyapp/ghc | compiler/hsSyn/HsTypes.hs | bsd-3-clause | 32,374 | 0 | 15 | 8,703 | 6,288 | 3,331 | 2,957 | 399 | 6 |
{-# language CPP #-}
-- No documentation found for Chapter "SemaphoreCreateFlags"
module Vulkan.Core10.Enums.SemaphoreCreateFlags (SemaphoreCreateFlags(..)) where
import Vulkan.Internal.Utils (enumReadPrec)
import Vulkan.Internal.Utils (enumShowsPrec)
import GHC.Show (showString)
import Numeric (showHex)
import Vulkan.Zero (Zero)
import Data.Bits (Bits)
import Data.Bits (FiniteBits)
import Foreign.Storable (Storable)
import GHC.Read (Read(readPrec))
import GHC.Show (Show(showsPrec))
import Vulkan.Core10.FundamentalTypes (Flags)
-- | VkSemaphoreCreateFlags - Reserved for future use
--
-- = Description
--
-- 'SemaphoreCreateFlags' is a bitmask type for setting a mask, but is
-- currently reserved for future use.
--
-- = See Also
--
-- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_VERSION_1_0 VK_VERSION_1_0>,
-- 'Vulkan.Core10.QueueSemaphore.SemaphoreCreateInfo'
newtype SemaphoreCreateFlags = SemaphoreCreateFlags Flags
deriving newtype (Eq, Ord, Storable, Zero, Bits, FiniteBits)
conNameSemaphoreCreateFlags :: String
conNameSemaphoreCreateFlags = "SemaphoreCreateFlags"
enumPrefixSemaphoreCreateFlags :: String
enumPrefixSemaphoreCreateFlags = ""
showTableSemaphoreCreateFlags :: [(SemaphoreCreateFlags, String)]
showTableSemaphoreCreateFlags = []
instance Show SemaphoreCreateFlags where
showsPrec = enumShowsPrec enumPrefixSemaphoreCreateFlags
showTableSemaphoreCreateFlags
conNameSemaphoreCreateFlags
(\(SemaphoreCreateFlags x) -> x)
(\x -> showString "0x" . showHex x)
instance Read SemaphoreCreateFlags where
readPrec = enumReadPrec enumPrefixSemaphoreCreateFlags
showTableSemaphoreCreateFlags
conNameSemaphoreCreateFlags
SemaphoreCreateFlags
| expipiplus1/vulkan | src/Vulkan/Core10/Enums/SemaphoreCreateFlags.hs | bsd-3-clause | 1,902 | 0 | 10 | 360 | 305 | 184 | 121 | -1 | -1 |
--
-- Copyright © 2013-2014 Anchor Systems, Pty Ltd and Others
--
-- The code in this file, and the program it is a part of, is
-- made available to you by its authors as open source software:
-- you can redistribute it and/or modify it under the terms of
-- the 3-clause BSD licence.
--
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE EmptyDataDecls #-}
{-# LANGUAGE ExistentialQuantification #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE TypeFamilies #-}
module TimeStore.Core
(
-- * User facing types
Store(..),
NameSpace(..),
nameSpace,
Address(..),
address,
time,
payload,
Time(..),
-- * Internal types
Bucket(..),
ObjectName(..),
Nameable(..),
LockName(..),
Point(..),
Epoch(..),
LatestFile(..),
Simple,
Extended,
SimpleBucketLocation(..),
ExtendeBucketLocation(..),
-- * Utility
placeBucket,
-- * Exceptions
InvalidPayload(..),
StoreFailure(..),
) where
import Control.Applicative
import Control.Concurrent
import Control.Concurrent.Async
import Control.Exception
import Control.Lens (makeLenses)
import Data.Bits
import Data.ByteString (ByteString)
import qualified Data.ByteString.Char8 as S
import Data.String (IsString)
import Data.Traversable (for, traverse)
import Data.Typeable
import Data.Word (Word64)
import Foreign.Ptr
import Foreign.Storable
import System.Posix.Signals
import Text.Printf
-- | A concrete implementation of a storage backend for a time store.
--
-- In production, this should be Ceph, but in development you may want to use
-- an in memory store or file backed store.
--
-- The backend has the notion of globally exclusive advisory locks, atomic
-- appends and reads over namespaces of buckets.
--
-- Minimum definition is append, write, fetch, sizes, unsafeLock
--
-- This has the bonus of clearly enumerating the back-end interactions.
class Store s where
type FetchFuture s
type SizeFuture s
-- | Get the rollover threshould for a given store and namespace. This is
-- the minumum size that a bucket should be in order for us to select a new
-- epoch. Default is 4MB.
rolloverThreshold :: s -> NameSpace -> Word64
rolloverThreshold _ _ = 2 ^ (20 :: Word64) * 4
-- | Append to a series of buckets, each append is atomic
append :: s -> NameSpace -> [(ObjectName,ByteString)] -> IO ()
-- | Overwrite a series of buckets
write :: s -> NameSpace -> [(ObjectName, ByteString)] -> IO ()
-- | Begin fetching the contents of a bucket with the provided size
fetch :: s -> NameSpace -> ObjectName -> Word64 -> IO (FetchFuture s)
-- | Retrieve the contents of a FetchFuture
reifyFetch :: s -> FetchFuture s -> IO ByteString
-- | Fetch a series of buckets in parallel
fetchs :: s -> NameSpace -> [ObjectName] -> IO [Maybe ByteString]
fetchs s ns objs = do
-- Maybe fetch the sizes for our objects
m_szs <- sizes s ns objs
-- For those that worked, begin fetching the contents.
m_fetches <- for (zip objs m_szs) $ \(obj, m_sz) ->
traverse (fetch s ns obj) m_sz
-- Now try to reify the contents for those that have any
(traverse . traverse) (reifyFetch s) m_fetches
-- | Begin getting the size of a bucket
size :: s -> NameSpace -> ObjectName -> IO (SizeFuture s)
-- | Retrieve the size of a SizeFuture, Nothing if the bucket didn't exist.
reifySize :: s -> SizeFuture s -> IO (Maybe Word64)
-- | Fetch a series of sizes in parallel
sizes :: s -> NameSpace -> [ObjectName] -> IO [Maybe Word64]
sizes s ns objs = traverse (size s ns) objs >>= traverse (reifySize s)
-- | Take an exclusive lock with the given expiry. If a lock remains after
-- this expiry then there are no guarantees that we can recover from a
-- deadlock.
unsafeExclusiveLock :: s -> NameSpace -> Double -> LockName -> IO a -> IO a
-- | A shared lock. Many may hold this lock until an exclusive lock is
-- taken.
unsafeSharedLock :: s -> NameSpace -> Double -> LockName -> IO a -> IO a
-- | Safely acquire a lock, if your action takes longer than a (arbitrary)
-- timeout, then we will be forced to abort() so that nothing is broken.
withExclusiveLock :: s -> NameSpace -> LockName -> IO a -> IO a
withExclusiveLock s ns ln f =
unsafeExclusiveLock s ns (succ lockTimeout) ln (watchDog "withExclusiveLock" f)
-- | Safely acquire shared lock.
withSharedLock :: s -> NameSpace -> LockName -> IO a -> IO a
withSharedLock s ns ln f =
unsafeSharedLock s ns (succ lockTimeout) ln (watchDog "withExclusiveLock" f)
-- | Run the action for at most lock timeout time, then
watchDog :: String -> IO a -> IO a
watchDog msg f = msg `seq` do
r <- race (threadDelay (ceiling lockTimeout * 1000000)) f
case r of
Left () -> do
putStrLn $ msg ++ ": Aborting due to lock timeout"
raiseSignal sigABRT
error $ msg ++ ": highly improbable"
Right v -> return v
-- | In order to recover from a possible deadlock, we request that any locks
-- are broken after this timeout.
--
-- As a result we *must* abort any operation that takes longer than this.
lockTimeout :: Double
lockTimeout = 120 -- seconds
-- | An ObjectName can be used to retrieve an object's data from the backend.
-- It corresponds to a part of an object ID in ceph. The other part being the
-- namespace.
class Nameable o where
name :: o -> ObjectName
-- Phantom types for extra safety
data Simple
data Extended
-- Uninhabited wrapper for finding the location of a latest file.
data LatestFile a = LatestFile
-- This is where we store an incrementing "pointer" to the latest
-- (chronologically) point we have ever seen.
instance Nameable (LatestFile Simple) where
name _ = "simple_latest"
instance Nameable (LatestFile Extended) where
name _ = "extended_latest"
-- | An ObjectName represents a key for a store that can to be associated with
-- data. They are unique within a NameSpace.
newtype ObjectName = ObjectName { unObjectName :: ByteString }
deriving (IsString, Show, Eq)
-- | The location of a bucket is calculated using the Epoch and Bucket. The
-- bucket is calculated by (address mod max_buckets)
newtype SimpleBucketLocation = SimpleBucketLocation (Epoch,Bucket)
newtype ExtendeBucketLocation = ExtendedBucketLocation (Epoch,Bucket)
instance Nameable SimpleBucketLocation where
name (SimpleBucketLocation (e,b)) = bucketLocation e b "simple"
instance Nameable ExtendeBucketLocation where
name (ExtendedBucketLocation (e,b)) = bucketLocation e b "extended"
bucketLocation :: Epoch -> Bucket -> String -> ObjectName
bucketLocation (Epoch epoch) (Bucket bucket) kind =
ObjectName . S.pack $ printf "%020d_%020d_%s"
bucket
epoch
kind
newtype Bucket
= Bucket { unBucket :: Word64 }
deriving (Eq, Ord, Num, Show, Enum, Real, Integral, Read)
newtype LockName
= LockName { unLockName :: ByteString }
deriving (Eq, Ord, IsString, Show)
newtype NameSpace
= NameSpace { unNameSpace :: ByteString }
deriving (Eq, Ord, Show)
instance Read NameSpace where
readsPrec _ =
pure . (,"") . either error id . nameSpace . S.pack
nameSpace :: ByteString -> Either String NameSpace
nameSpace bs
| S.null bs = Left "NameSpace may not be empty"
| S.elem '_' bs = Left "NameSpace may not include _"
| otherwise = Right . NameSpace $ bs
newtype Epoch = Epoch { unEpoch :: Word64 }
deriving (Eq, Ord, Num, Show)
newtype Address = Address {
unAddress :: Word64
}
deriving (Eq, Ord, Num, Bounded, Bits, Show, Storable, Enum, Real, Integral)
newtype Time = Time {
unTime :: Word64
}
deriving (Eq, Num, Bounded, Ord, Show, Storable, Enum)
data Point
= Point { _address :: !Address
, _time :: !Time
, _payload :: !Word64
} deriving (Show, Eq)
makeLenses ''Point
instance Ord Point where
-- Compare time first, then address. This way we can de-deplicate by
-- comparing adjacent values.
compare (Point a t _) (Point a' t' _) =
case compare t t' of
EQ -> compare a a'
c -> c
instance Storable Point where
sizeOf _ = 24
alignment _ = 8
peek ptr =
Point <$> peek (castPtr ptr)
<*> peek (ptr `plusPtr` 8)
<*> peek (ptr `plusPtr` 16)
poke ptr (Point a t p) = do
poke (castPtr ptr) a
poke (ptr `plusPtr` 8 ) t
poke (ptr `plusPtr` 16 ) p
-- | Given a maximum number of buckets to hash over, map an address to the
-- corresponding bucket within the epoch.
placeBucket :: Bucket -> Address -> Bucket
placeBucket (Bucket max_buckets) (Address addr) =
Bucket $ (addr `clearBit` 0) `mod` max_buckets
data InvalidPayload
= forall e. Exception e => InvalidPayload e
deriving (Typeable)
data StoreFailure
= forall e. Exception e => StoreFailure e
deriving (Typeable)
instance Exception InvalidPayload
instance Exception StoreFailure
deriving instance Show InvalidPayload
deriving instance Show StoreFailure
| anchor/rados-timestore | lib/TimeStore/Core.hs | bsd-3-clause | 9,491 | 0 | 14 | 2,326 | 2,072 | 1,143 | 929 | -1 | -1 |
module MtAnnotate
(
mtAnnotateStatement
) where
import qualified Data.Map as M
import qualified Database.HsSqlPpp.Parse as Pa
import MtTypes
mtAnnotateStatement :: MtSchemaSpec -> Pa.Statement -> Pa.Statement
mtAnnotateStatement spec (Pa.QueryStatement a q) = Pa.QueryStatement a (annotateQuery spec q [])
mtAnnotateStatement spec (Pa.CreateView a n c q) = Pa.CreateView a n c (annotateQuery spec q [])
mtAnnotateStatement _ statement = statement
-- make sure that every attribute of a specific table appears with its table name
-- assumes that attributes not found within the schema are from global tables
-- for the case it is used in subqueries, it also take the table refs from the outer queries into account
annotateQuery :: MtSchemaSpec -> Pa.QueryExpr -> Pa.TableRefList -> Pa.QueryExpr
annotateQuery spec (Pa.Select ann selDistinct selSelectList selTref selWhere
selGroupBy selHaving selOrderBy selLimit selOffset selOption) trefs =
let allTrefs = selTref ++ trefs -- ordering matters here as the first value that fits is taken
newSelectList = annotateSelectList spec selTref selSelectList (null trefs)
newTrefs = annotateTrefList spec selTref
newWhere = annotateMaybeScalarExpr spec allTrefs selWhere
newGroupBy = map (annotateScalarExpr spec selTref) selGroupBy
newHaving = annotateMaybeScalarExpr spec selTref selHaving
newOrderBy = annotateDirectionList spec selTref selOrderBy
in Pa.Select ann selDistinct newSelectList newTrefs newWhere
newGroupBy newHaving newOrderBy selLimit selOffset selOption
-- default case handles anything we do not handle so far
annotateQuery _ query _ = query
annotateTrefList :: MtSchemaSpec -> Pa.TableRefList -> Pa.TableRefList
annotateTrefList spec (Pa.SubTref ann sel:trefs) = Pa.SubTref ann (annotateQuery spec sel []) : annotateTrefList spec trefs
annotateTrefList spec (Pa.TableAlias ann tb tref:trefs) = Pa.TableAlias ann tb (head (annotateTrefList spec [tref])) : annotateTrefList spec trefs
annotateTrefList spec (Pa.JoinTref ann tref0 n t h tref1 (Just (Pa.JoinOn a expr)):trefs) = Pa.JoinTref ann
(head (annotateTrefList spec [tref0]))
n t h
(head (annotateTrefList spec [tref1]))
(Just (Pa.JoinOn a (annotateScalarExpr spec (tref0:[tref1]) expr))) : annotateTrefList spec trefs
annotateTrefList spec (Pa.FullAlias ann tb cols tref:trefs) = Pa.FullAlias ann tb cols
(head (annotateTrefList spec [tref])) : annotateTrefList spec trefs
-- default case, recursively call annotation call on single item
annotateTrefList spec (tref:trefs) = tref:annotateTrefList spec trefs
annotateTrefList _ [] = []
annotateSelectList :: MtSchemaSpec -> Pa.TableRefList -> Pa.SelectList -> Bool -> Pa.SelectList
annotateSelectList spec trefs (Pa.SelectList ann items) b = Pa.SelectList ann (annotateSelectItems spec trefs items b)
annotateSelectItems :: MtSchemaSpec -> Pa.TableRefList -> [Pa.SelectItem] -> Bool -> [Pa.SelectItem]
-- replaces Star Expressions with an enumeration of all attributes instead (* would also display tenant key, which is something we do not want)
-- if it is outermost query (which is indicated by the bool)
annotateSelectItems spec [Pa.Tref tAnn (Pa.Name nameAnn [Pa.Nmc tname])] [Pa.SelExp selAnn (Pa.Star starAnn)] True =
let tableSpec = M.lookup tname spec
generate (Just (FromMtSpecificTable tab)) = map (\key -> Pa.SelExp selAnn (Pa.Identifier starAnn (Pa.Name starAnn [Pa.Nmc key]))) (M.keys tab)
generate _ = [Pa.SelExp selAnn (Pa.Star starAnn)]
in annotateSelectItems spec [Pa.Tref tAnn (Pa.Name nameAnn [Pa.Nmc tname])] (generate tableSpec) True
-- default case, recursively call annotation call on single item
annotateSelectItems spec trefs (item:items) b = annotateSelectItem spec trefs item : annotateSelectItems spec trefs items b
annotateSelectItems _ _ [] _ = []
annotateSelectItem :: MtSchemaSpec -> Pa.TableRefList -> Pa.SelectItem -> Pa.SelectItem
annotateSelectItem spec trefs (Pa.SelExp ann scalExp) = Pa.SelExp ann (annotateScalarExpr spec trefs scalExp)
annotateSelectItem spec trefs (Pa.SelectItem ann scalExp newName) = Pa.SelectItem ann (annotateScalarExpr spec trefs scalExp) newName
annotateMaybeScalarExpr :: MtSchemaSpec -> Pa.TableRefList -> Maybe Pa.ScalarExpr -> Maybe Pa.ScalarExpr
annotateMaybeScalarExpr spec trefs (Just expr) = Just (annotateScalarExpr spec trefs expr)
annotateMaybeScalarExpr _ _ Nothing = Nothing
annotateDirectionList :: MtSchemaSpec -> Pa.TableRefList -> Pa.ScalarExprDirectionPairList -> Pa.ScalarExprDirectionPairList
annotateDirectionList spec trefs ((expr, dir, no):list) = (annotateScalarExpr spec trefs expr, dir, no) : annotateDirectionList spec trefs list
annotateDirectionList _ _ [] = []
annotateScalarExpr :: MtSchemaSpec -> Pa.TableRefList -> Pa.ScalarExpr -> Pa.ScalarExpr
annotateScalarExpr spec trefs (Pa.PrefixOp ann opName arg) = Pa.PrefixOp ann opName (annotateScalarExpr spec trefs arg)
annotateScalarExpr spec trefs (Pa.PostfixOp ann opName arg) = Pa.PostfixOp ann opName (annotateScalarExpr spec trefs arg)
annotateScalarExpr spec trefs (Pa.BinaryOp ann opName arg0 arg1) = Pa.BinaryOp ann opName
(annotateScalarExpr spec trefs arg0) (annotateScalarExpr spec trefs arg1)
annotateScalarExpr spec trefs (Pa.SpecialOp ann opName args) = Pa.SpecialOp ann opName (map (annotateScalarExpr spec trefs) args)
annotateScalarExpr spec trefs (Pa.App ann funName args) = Pa.App ann funName (map (annotateScalarExpr spec trefs) args)
annotateScalarExpr spec trefs (Pa.Parens ann expr) = Pa.Parens ann (annotateScalarExpr spec trefs expr)
annotateScalarExpr spec trefs (Pa.InPredicate ann expr i list) =
let annotateInList (Pa.InList a elist) = Pa.InList a (map (annotateScalarExpr spec trefs) elist)
annotateInList (Pa.InQueryExpr a sel) = Pa.InQueryExpr a (annotateQuery spec sel trefs)
in Pa.InPredicate ann (annotateScalarExpr spec trefs expr) i (annotateInList list)
annotateScalarExpr spec trefs (Pa.Exists ann sel) = Pa.Exists ann (annotateQuery spec sel trefs)
annotateScalarExpr spec trefs (Pa.ScalarSubQuery ann sel) = Pa.ScalarSubQuery ann (annotateQuery spec sel trefs)
annotateScalarExpr spec trefs (Pa.Case ann cases els) = Pa.Case ann
(map (\(explist, e) -> (map (annotateScalarExpr spec trefs) explist, annotateScalarExpr spec trefs e)) cases)
(annotateMaybeScalarExpr spec trefs els)
annotateScalarExpr spec (Pa.Tref _ (Pa.Name _ [Pa.Nmc tname]):trefs) (Pa.Identifier iAnn (Pa.Name a (Pa.Nmc attName:nameComps)))
| not (null nameComps) = Pa.Identifier iAnn (Pa.Name a (Pa.Nmc attName : nameComps))
| otherwise =
let tableSpec = M.lookup tname spec
containsAttribute (Just (FromMtSpecificTable attrMap)) aName = M.member aName attrMap
containsAttribute _ _ = False
contains = containsAttribute tableSpec attName
propagate False = annotateScalarExpr spec trefs (Pa.Identifier iAnn (Pa.Name a [Pa.Nmc attName]))
propagate True = Pa.Identifier iAnn (Pa.Name a [Pa.Nmc tname,Pa.Nmc attName])
in propagate contains
annotateScalarExpr spec (Pa.JoinTref _ tref0 _ _ _ tref1 _ : trefs) expr =
annotateScalarExpr spec (tref0:tref1:trefs) expr
-- for any other trefs, we still need to make sure that the rest of the trefs gets checked as well
annotateScalarExpr spec (_:trefs) expr = annotateScalarExpr spec trefs expr
-- default case handles anything we do not handle so far
annotateScalarExpr _ _ expr = expr
| lucasbraun/mt-rewrite | src/MtAnnotate.hs | bsd-3-clause | 7,601 | 0 | 19 | 1,302 | 2,371 | 1,187 | 1,184 | 85 | 4 |
import Text.Parsec.Char
import Text.Parsec.Combinator
import Text.Parsec
import qualified Text.Parsec.Token as P
import Text.Parsec.Language (emptyDef)
import Control.Applicative ((<$>))
import Control.Monad (void, fail, unless)
import Data.Map
import Data.Maybe
type Program = [Function]
data Function = Function { funcName :: String
, funcArgs :: [String]
, funcInstrs :: Instructions
, funcLabels :: Labels
}
deriving Show
type Instructions = [Instruction]
data Instruction = Instruction { instrName :: String
, instrArgs :: [Atom]
}
deriving Show
type Labels = Map String Integer
data Atom = AtomConstant Integer
| AtomVariable String
deriving Show
data MiVMParserState = MiVMParserState { stateInstrs :: Instructions
, stateLabels :: Labels
, stateLabelPos :: Integer
}
type MiVMParser a = Parsec String MiVMParserState a
emptyMiVMParserState = MiVMParserState { stateInstrs = []
, stateLabels = empty
, stateLabelPos = 0
}
lexer = P.makeTokenParser emptyDef { P.commentLine = "--"
, P.nestedComments = False
, P.opStart = unexpected "no operators"
}
colon = P.colon lexer
commaSep = P.commaSep lexer
dot = P.dot lexer
identifier = P.identifier lexer
integer = P.integer lexer
parens = P.parens lexer
symbol = P.symbol lexer
atom = P.lexeme lexer ((AtomConstant <$> integer)
<|> (dot >> AtomVariable <$> identifier))
parseInstr :: MiVMParser ()
parseInstr = do
let iii name argc = do i <- symbol name
a <- commaSep atom
let argc' = length a
unless (argc' == argc) (fail $ name ++ "wrong argument count "
++ show argc' ++ ", expected " ++ show argc)
return $ Instruction i a
-- TODO: generate from opcodes.csv?
i <- choice [ iii "push" 1
, iii "pop" 0
, iii "load" 1
, iii "store" 1
, iii "halt" 0
, iii "add" 0
, iii "mul" 0
, iii "inc" 0
, iii "dec" 1
, iii "jmp" 1
, iii "jmpz" 1
, iii "jmpnz" 0
, iii "lt" 0
, iii "eq" 0
]
-- TODO: check variable and label validity
modifyState (\s -> let is = stateInstrs s
lp = stateLabelPos s
in s { stateInstrs = is ++ [i]
, stateLabelPos = lp + 1
}
)
parseLabel :: MiVMParser ()
parseLabel = do
l <- identifier
colon
modifyState (\s -> let ls = stateLabels s
lp = stateLabelPos s
in s { stateLabels = insert l lp ls }
)
parseFunction :: MiVMParser Function
parseFunction = do
symbol "fun"
fName <- identifier
fArgs <- parens (commaSep identifier)
colon
setState emptyMiVMParserState
many1 $ choice [ try parseLabel
, try parseInstr
]
s <- getState
return Function { funcName = fName
, funcArgs = fArgs
, funcInstrs = stateInstrs s
, funcLabels = stateLabels s
}
parseProgram :: MiVMParser Program
parseProgram = do
p <- many1 parseFunction
eof
return p
main = do
input <- readFile "test1.mivms"
print $ runParser parseProgram emptyMiVMParserState "MiVM" input
| mmartin/mivm | ir/Main.hs | bsd-3-clause | 4,218 | 0 | 18 | 1,970 | 961 | 506 | 455 | 97 | 1 |
{-# LANGUAGE DeriveGeneric, OverloadedStrings, GeneralizedNewtypeDeriving #-}
module Data.RDF.Types (
-- * RDF triples, nodes and literals
LValue(PlainL,PlainLL,TypedL),
Node(UNode,BNode,BNodeGen,LNode), Subject, Predicate, Object,
Triple(Triple), Triples, View(view),
-- * Constructor functions
plainL,plainLL,typedL,
unode,bnode,lnode,triple,unodeValidate,uriValidate,
-- * Node query function
isUNode,isLNode,isBNode,
-- * Miscellaneous
resolveQName, absolutizeUrl, isAbsoluteUri, mkAbsoluteUrl,escapeRDFSyntax,fileSchemeToFilePath,
-- * RDF Type
RDF(baseUrl,prefixMappings,addPrefixMappings,empty,mkRdf,triplesOf,uniqTriplesOf,select,query),
-- * Parsing RDF
RdfParser(parseString,parseFile,parseURL),
-- * Serializing RDF
RdfSerializer(hWriteRdf,writeRdf,hWriteH,writeH,hWriteTs,hWriteT,writeT, writeTs,hWriteN, writeN),
-- * Namespaces and Prefixes
Namespace(PrefixedNS,PlainNS),
PrefixMappings(PrefixMappings),PrefixMapping(PrefixMapping),
-- * Supporting types
BaseUrl(BaseUrl), NodeSelector, ParseFailure(ParseFailure)
) where
import Prelude hiding (pred)
import qualified Data.Text as T
import System.IO
import Text.Printf
import Data.Binary
import Data.Map(Map)
import Data.Maybe (fromJust)
import GHC.Generics (Generic)
import Data.Hashable(Hashable)
import qualified Data.List as List
import qualified Data.Map as Map
import qualified Network.URI as Network (uriPath,parseURI)
import Control.DeepSeq (NFData,rnf)
import Text.Parsec
import Text.Parsec.Text
import Network.URI
import Codec.Binary.UTF8.String
-------------------
-- LValue and constructor functions
-- |The actual value of an RDF literal, represented as the 'LValue'
-- parameter of an 'LNode'.
data LValue =
-- Constructors are not exported, because we need to have more
-- control over the format of the literal text that we store.
-- |A plain (untyped) literal value in an unspecified language.
PlainL !T.Text
-- |A plain (untyped) literal value with a language specifier.
| PlainLL !T.Text !T.Text
-- |A typed literal value consisting of the literal value and
-- the URI of the datatype of the value, respectively.
| TypedL !T.Text !T.Text
deriving (Generic,Show)
instance Binary LValue
instance NFData LValue where
rnf (PlainL t) = rnf t
rnf (PlainLL t1 t2) = rnf t1 `seq` rnf t2
rnf (TypedL t1 t2) = rnf t1 `seq` rnf t2
-- |Return a PlainL LValue for the given string value.
{-# INLINE plainL #-}
plainL :: T.Text -> LValue
plainL = PlainL
-- |Return a PlainLL LValue for the given string value and language,
-- respectively.
{-# INLINE plainLL #-}
plainLL :: T.Text -> T.Text -> LValue
plainLL = PlainLL
-- |Return a TypedL LValue for the given string value and datatype URI,
-- respectively.
{-# INLINE typedL #-}
typedL :: T.Text -> T.Text -> LValue
typedL val dtype = TypedL (canonicalize dtype val) dtype
-------------------
-- Node and constructor functions
-- |An RDF node, which may be either a URIRef node ('UNode'), a blank
-- node ('BNode'), or a literal node ('LNode').
data Node =
-- |An RDF URI reference. URIs conform to the RFC3986 standard. See
-- <http://www.w3.org/TR/rdf-concepts/#section-Graph-URIref> for more
-- information.
UNode !T.Text
-- |An RDF blank node. See
-- <http://www.w3.org/TR/rdf-concepts/#section-blank-nodes> for more
-- information.
| BNode !T.Text
-- |An RDF blank node with an auto-generated identifier, as used in
-- Turtle.
| BNodeGen !Int
-- |An RDF literal. See
-- <http://www.w3.org/TR/rdf-concepts/#section-Graph-Literal> for more
-- information.
| LNode !LValue
deriving (Generic,Show)
instance Binary Node
instance NFData Node where
rnf (UNode t) = rnf t
rnf (BNode b) = rnf b
rnf (BNodeGen bgen) = rnf bgen
rnf (LNode lvalue) = rnf lvalue
-- |An alias for 'Node', defined for convenience and readability purposes.
type Subject = Node
-- |An alias for 'Node', defined for convenience and readability purposes.
type Predicate = Node
-- |An alias for 'Node', defined for convenience and readability purposes.
type Object = Node
-- |Return a URIRef node for the given URI.
{-# INLINE unode #-}
unode :: T.Text -> Node
unode = UNode
-- For background on 'unodeValidate', see:
-- http://stackoverflow.com/questions/33250184/unescaping-unicode-literals-found-in-haskell-strings
--
-- Escaped literals are defined in the Turtle spec, and is
-- inherited by the NTriples and XML specification.
-- http://www.w3.org/TR/turtle/#sec-escapes
-- |Validate a URI and return it in a @Just UNode@ if it is
-- valid, otherwise @Nothing@ is returned. Performs the following:
--
-- 1. unescape unicode RDF literals
-- 2. checks validity of this unescaped URI using 'isURI' from 'Network.URI'
-- 3. if the unescaped URI is valid then 'Node' constructed with 'UNode'
unodeValidate :: T.Text -> Maybe Node
unodeValidate t = case isRdfURI t of
Left _err -> Nothing
Right uri -> Just (UNode uri)
isRdfURI :: T.Text -> Either ParseError T.Text
isRdfURI t = parse (isRdfURIParser <* eof) ("Invalid URI: " ++ T.unpack t) t
-- [18] IRIREF from Turtle spec
isRdfURIParser :: GenParser () T.Text
isRdfURIParser = T.concat <$> many (T.singleton <$> noneOf (['\x00'..'\x20'] ++ [' ','<','>','"','{','}','|','^','`','\\']) <|> nt_uchar)
-- [10] UCHAR
nt_uchar :: GenParser () T.Text
nt_uchar =
(try (char '\\' >> char 'u' >> count 4 hexDigit >>= \cs -> return $ T.pack (uEscapedToXEscaped cs)) <|>
try (char '\\' >> char 'U' >> count 8 hexDigit >>= \cs -> return $ T.pack (uEscapedToXEscaped cs)))
uEscapedToXEscaped :: String -> String
uEscapedToXEscaped ss =
let str = ['\\','x'] ++ ss
in read ("\"" ++ str ++ "\"")
-- |Validate a Text URI and return it in a @Just Text@ if it is
-- valid, otherwise @Nothing@ is returned. See 'unodeValidate'.
uriValidate :: T.Text -> Maybe T.Text
uriValidate t = case isRdfURI t of
Left _err -> Nothing
Right uri -> Just uri
escapeRDFSyntax :: T.Text -> T.Text
escapeRDFSyntax t = T.pack uri
where
Right uri = parse unicodeEscParser "" (T.unpack t)
unicodeEscParser :: Stream s m Char => ParsecT s u m String
unicodeEscParser = do
ss <- many (
try (do { _ <- char '\\'
; _ <- char 'U'
; pos1 <- hexDigit
; pos2 <- hexDigit
; pos3 <- hexDigit
; pos4 <- hexDigit
; pos5 <- hexDigit
; pos6 <- hexDigit
; pos7 <- hexDigit
; pos8 <- hexDigit
; let str = ['\\','x',pos1,pos2,pos3,pos4,pos5,pos6,pos7,pos8]
; return (read ("\"" ++ str ++ "\"") :: String)})
<|>
try (do { _ <- char '\\'
; _ <- char 'u'
; pos1 <- hexDigit
; pos2 <- hexDigit
; pos3 <- hexDigit
; pos4 <- hexDigit
; let str = ['\\','x',pos1,pos2,pos3,pos4]
; return (read ("\"" ++ str ++ "\"") :: String)})
<|>
(anyChar >>= \c -> return [c]))
return (concat ss :: String)
-- |Return a blank node using the given string identifier.
{-# INLINE bnode #-}
bnode :: T.Text -> Node
bnode = BNode
-- |Return a literal node using the given LValue.
{-# INLINE lnode #-}
lnode :: LValue -> Node
lnode = LNode
-------------------
-- Triple and constructor functions
-- |An RDF triple is a statement consisting of a subject, predicate,
-- and object, respectively.
--
-- See <http://www.w3.org/TR/rdf-concepts/#section-triples> for
-- more information.
data Triple = Triple !Node !Node !Node
deriving (Generic,Show)
instance Binary Triple
instance NFData Triple where
rnf (Triple s p o) = rnf s `seq` rnf p `seq` rnf o
-- |A list of triples. This is defined for convenience and readability.
type Triples = [Triple]
-- |A smart constructor function for 'Triple' that verifies the node arguments
-- are of the correct type and creates the new 'Triple' if so or calls 'error'.
-- /subj/ must be a 'UNode' or 'BNode', and /pred/ must be a 'UNode'.
triple :: Subject -> Predicate -> Object -> Triple
triple subj pred obj
| isLNode subj = error $ "subject must be UNode or BNode: " ++ show subj
| isLNode pred = error $ "predicate must be UNode, not LNode: " ++ show pred
| isBNode pred = error $ "predicate must be UNode, not BNode: " ++ show pred
| otherwise = Triple subj pred obj
-- |Answer if given node is a URI Ref node.
{-# INLINE isUNode #-}
isUNode :: Node -> Bool
isUNode (UNode _) = True
isUNode _ = False
-- |Answer if given node is a blank node.
{-# INLINE isBNode #-}
isBNode :: Node -> Bool
isBNode (BNode _) = True
isBNode (BNodeGen _) = True
isBNode _ = False
-- |Answer if given node is a literal node.
{-# INLINE isLNode #-}
isLNode :: Node -> Bool
isLNode (LNode _) = True
isLNode _ = False
{-# INLINE isAbsoluteUri #-}
isAbsoluteUri :: T.Text -> Bool
isAbsoluteUri = not
. uriIsRelative
. fromJust
. parseURIReference
. escapeURIString isUnescapedInURI
. encodeString
. T.unpack
-- |A type class for ADTs that expose views to clients.
class View a b where
view :: a -> b
-- |An RDF value is a set of (unique) RDF triples, together with the
-- operations defined upon them.
--
-- For information about the efficiency of the functions, see the
-- documentation for the particular RDF instance.
--
-- For more information about the concept of an RDF graph, see
-- the following: <http://www.w3.org/TR/rdf-concepts/#section-rdf-graph>.
class RDF rdf where
-- |Return the base URL of this RDF, if any.
baseUrl :: rdf -> Maybe BaseUrl
-- |Return the prefix mappings defined for this RDF, if any.
prefixMappings :: rdf -> PrefixMappings
-- |Return an RDF with the specified prefix mappings merged with
-- the existing mappings. If the Bool arg is True, then a new mapping
-- for an existing prefix will replace the old mapping; otherwise,
-- the new mapping is ignored.
addPrefixMappings :: rdf -> PrefixMappings -> Bool -> rdf
-- |Return an empty RDF.
empty :: rdf
-- |Return a RDF containing all the given triples. Handling of duplicates
-- in the input depend on the particular RDF implementation.
mkRdf :: Triples -> Maybe BaseUrl -> PrefixMappings -> rdf
-- |Return all triples in the RDF, as a list.
--
-- Note that this function returns a list of triples in the RDF as they
-- were added, without removing duplicates and without expanding namespaces.
triplesOf :: rdf -> Triples
-- |Return unique triples in the RDF, as a list.
--
-- This function performs namespace expansion and removal of duplicates.
uniqTriplesOf :: rdf -> Triples
-- |Select the triples in the RDF that match the given selectors.
--
-- The three NodeSelector parameters are optional functions that match
-- the respective subject, predicate, and object of a triple. The triples
-- returned are those in the given graph for which the first selector
-- returns true when called on the subject, the second selector returns
-- true when called on the predicate, and the third selector returns true
-- when called on the ojbect. A 'Nothing' parameter is equivalent to a
-- function that always returns true for the appropriate node; but
-- implementations may be able to much more efficiently answer a select
-- that involves a 'Nothing' parameter rather than an @(id True)@ parameter.
--
-- The following call illustrates the use of select, and would result in
-- the selection of all and only the triples that have a blank node
-- as subject and a literal node as object:
--
-- > select gr (Just isBNode) Nothing (Just isLNode)
--
-- Note: this function may be very slow; see the documentation for the
-- particular RDF implementation for more information.
select :: rdf -> NodeSelector -> NodeSelector -> NodeSelector -> Triples
-- |Return the triples in the RDF that match the given pattern, where
-- the pattern (3 Maybe Node parameters) is interpreted as a triple pattern.
--
-- The @Maybe Node@ params are interpreted as the subject, predicate, and
-- object of a triple, respectively. @Just n@ is true iff the triple has
-- a node equal to @n@ in the appropriate location; @Nothing@ is always
-- true, regardless of the node in the appropriate location.
--
-- For example, @ query rdf (Just n1) Nothing (Just n2) @ would return all
-- and only the triples that have @n1@ as subject and @n2@ as object,
-- regardless of the predicate of the triple.
query :: rdf -> Maybe Node -> Maybe Node -> Maybe Node -> Triples
-- |An RdfParser is a parser that knows how to parse 1 format of RDF and
-- can parse an RDF document of that type from a string, a file, or a URL.
-- Required configuration options will vary from instance to instance.
class RdfParser p where
-- |Parse RDF from the given text, yielding a failure with error message or
-- the resultant RDF.
parseString :: forall rdf. (RDF rdf) => p -> T.Text -> Either ParseFailure rdf
-- |Parse RDF from the local file with the given path, yielding a failure with error
-- message or the resultant RDF in the IO monad.
parseFile :: forall rdf. (RDF rdf) => p -> String -> IO (Either ParseFailure rdf)
-- |Parse RDF from the remote file with the given HTTP URL (https is not supported),
-- yielding a failure with error message or the resultant graph in the IO monad.
parseURL :: forall rdf. (RDF rdf) => p -> String -> IO (Either ParseFailure rdf)
-- |An RdfSerializer is a serializer of RDF to some particular output format, such as
-- NTriples or Turtle.
class RdfSerializer s where
-- |Write the RDF to a file handle using whatever configuration is specified by
-- the first argument.
hWriteRdf :: forall rdf. (RDF rdf) => s -> Handle -> rdf -> IO ()
-- |Write the RDF to stdout; equivalent to @'hWriteRdf' stdout@.
writeRdf :: forall rdf. (RDF rdf) => s -> rdf -> IO ()
-- |Write to the file handle whatever header information is required based on
-- the output format. For example, if serializing to Turtle, this method would
-- write the necessary \@prefix declarations and possibly a \@baseUrl declaration,
-- whereas for NTriples, there is no header section at all, so this would be a no-op.
hWriteH :: forall rdf. (RDF rdf) => s -> Handle -> rdf -> IO ()
-- |Write header information to stdout; equivalent to @'hWriteRdf' stdout@.
writeH :: forall rdf. (RDF rdf) => s -> rdf -> IO ()
-- |Write some triples to a file handle using whatever configuration is specified
-- by the first argument.
--
-- WARNING: if the serialization format has header-level information
-- that should be output (e.g., \@prefix declarations for Turtle), then you should
-- use 'hWriteG' instead of this method unless you're sure this is safe to use, since
-- otherwise the resultant document will be missing the header information and
-- will not be valid.
hWriteTs :: s -> Handle -> Triples -> IO ()
-- |Write some triples to stdout; equivalent to @'hWriteTs' stdout@.
writeTs :: s -> Triples -> IO ()
-- |Write a single triple to the file handle using whatever configuration is
-- specified by the first argument. The same WARNING applies as to 'hWriteTs'.
hWriteT :: s -> Handle -> Triple -> IO ()
-- |Write a single triple to stdout; equivalent to @'hWriteT' stdout@.
writeT :: s -> Triple -> IO ()
-- |Write a single node to the file handle using whatever configuration is
-- specified by the first argument. The same WARNING applies as to 'hWriteTs'.
hWriteN :: s -> Handle -> Node -> IO ()
-- |Write a single node to sdout; equivalent to @'hWriteN' stdout@.
writeN :: s -> Node -> IO ()
-- |The base URL of an RDF.
newtype BaseUrl = BaseUrl T.Text
deriving (Eq, Ord, Show, NFData, Generic)
instance Binary BaseUrl
-- |A 'NodeSelector' is either a function that returns 'True'
-- or 'False' for a node, or Nothing, which indicates that all
-- nodes would return 'True'.
--
-- The selector is said to select, or match, the nodes for
-- which it returns 'True'.
--
-- When used in conjunction with the 'select' method of 'Graph', three
-- node selectors are used to match a triple.
type NodeSelector = Maybe (Node -> Bool)
-- |Represents a failure in parsing an N-Triples document, including
-- an error message with information about the cause for the failure.
newtype ParseFailure = ParseFailure String
deriving (Eq, Show)
-- |A node is equal to another node if they are both the same type
-- of node and if the field values are equal.
instance Eq Node where
(UNode bs1) == (UNode bs2) = bs1 == bs2
(BNode bs1) == (BNode bs2) = bs1 == bs2
(BNodeGen i1) == (BNodeGen i2) = i1 == i2
(LNode l1) == (LNode l2) = l1 == l2
_ == _ = False
-- |Node ordering is defined first by type, with Unode < BNode < BNodeGen
-- < LNode PlainL < LNode PlainLL < LNode TypedL, and secondly by
-- the natural ordering of the node value.
--
-- E.g., a '(UNode _)' is LT any other type of node, and a
-- '(LNode (TypedL _ _))' is GT any other type of node, and the ordering
-- of '(BNodeGen 44)' and '(BNodeGen 3)' is that of the values, or
-- 'compare 44 3', GT.
instance Ord Node where
compare = compareNode
compareNode :: Node -> Node -> Ordering
compareNode (UNode bs1) (UNode bs2) = compare bs1 bs2
compareNode (UNode _) _ = LT
compareNode (BNode bs1) (BNode bs2) = compare bs1 bs2
compareNode (BNode _) (UNode _) = GT
compareNode (BNode _) _ = LT
compareNode (BNodeGen i1) (BNodeGen i2) = compare i1 i2
compareNode (BNodeGen _) (LNode _) = LT
compareNode (BNodeGen _) _ = GT
compareNode (LNode (PlainL bs1)) (LNode (PlainL bs2)) = compare bs1 bs2
compareNode (LNode (PlainL _)) (LNode _) = LT
compareNode (LNode (PlainLL bs1 bs1')) (LNode (PlainLL bs2 bs2')) =
case compare bs1' bs2' of
EQ -> compare bs1 bs2
LT -> LT
GT -> GT
compareNode (LNode (PlainLL _ _)) (LNode (PlainL _)) = GT
compareNode (LNode (PlainLL _ _)) (LNode _) = LT
compareNode (LNode (TypedL bsType1 bs1)) (LNode (TypedL bsType2 bs2)) =
case compare bs1 bs2 of
EQ -> compare bsType1 bsType2
LT -> LT
GT -> GT
compareNode (LNode (TypedL _ _)) (LNode _) = GT
compareNode (LNode _) _ = GT
instance Hashable Node
-- |Two triples are equal iff their respective subjects, predicates, and objects
-- are equal.
instance Eq Triple where
(Triple s1 p1 o1) == (Triple s2 p2 o2) = s1 == s2 && p1 == p2 && o1 == o2
-- |The ordering of triples is based on that of the subject, predicate, and object
-- of the triple, in that order.
instance Ord Triple where
(Triple s1 p1 o1) `compare` (Triple s2 p2 o2) =
case compareNode s1 s2 of
EQ -> case compareNode p1 p2 of
EQ -> compareNode o1 o2
LT -> LT
GT -> GT
GT -> GT
LT -> LT
-- |Two 'LValue' values are equal iff they are of the same type and all fields are
-- equal.
instance Eq LValue where
(PlainL bs1) == (PlainL bs2) = bs1 == bs2
(PlainLL bs1 bs1') == (PlainLL bs2 bs2') = bs1' == bs2' && bs1 == bs2
(TypedL bsType1 bs1) == (TypedL bsType2 bs2) = bsType1 == bsType2 && bs1 == bs2
_ == _ = False
-- |Ordering of 'LValue' values is as follows: (PlainL _) < (PlainLL _ _)
-- < (TypedL _ _), and values of the same type are ordered by field values,
-- with '(PlainLL literalValue language)' being ordered by language first and
-- literal value second, and '(TypedL literalValue datatypeUri)' being ordered
-- by datatype first and literal value second.
instance Ord LValue where
compare = compareLValue
{-# INLINE compareLValue #-}
compareLValue :: LValue -> LValue -> Ordering
compareLValue (PlainL bs1) (PlainL bs2) = compare bs1 bs2
compareLValue (PlainL _) _ = LT
compareLValue _ (PlainL _) = GT
compareLValue (PlainLL bs1 bs1') (PlainLL bs2 bs2') =
case compare bs1' bs2' of
EQ -> compare bs1 bs2
GT -> GT
LT -> LT
compareLValue (PlainLL _ _) _ = LT
compareLValue _ (PlainLL _ _) = GT
compareLValue (TypedL l1 t1) (TypedL l2 t2) =
case compare t1 t2 of
EQ -> compare l1 l2
GT -> GT
LT -> LT
instance Hashable LValue
------------------------
-- Prefix mappings
-- |Represents a namespace as either a prefix and uri, respectively,
-- or just a uri.
data Namespace = PrefixedNS T.Text T.Text -- prefix and ns uri
| PlainNS T.Text -- ns uri alone
instance Eq Namespace where
(PrefixedNS _ u1) == (PrefixedNS _ u2) = u1 == u2
(PlainNS u1) == (PlainNS u2) = u1 == u2
(PrefixedNS _ u1) == (PlainNS u2) = u1 == u2
(PlainNS u1) == (PrefixedNS _ u2) = u1 == u2
instance Show Namespace where
show (PlainNS uri) = T.unpack uri
show (PrefixedNS prefix uri) = printf "(PrefixNS %s %s)" (T.unpack prefix) (T.unpack uri)
-- |An alias for a map from prefix to namespace URI.
newtype PrefixMappings = PrefixMappings (Map T.Text T.Text)
deriving (Eq, Ord,NFData, Generic)
instance Binary PrefixMappings
instance Show PrefixMappings where
-- This is really inefficient, but it's not used much so not what
-- worth optimizing yet.
show (PrefixMappings pmap) = printf "PrefixMappings [%s]" mappingsStr
where showPM = show . PrefixMapping
mappingsStr = List.intercalate ", " (map showPM (Map.toList pmap))
-- |A mapping of a prefix to the URI for that prefix.
newtype PrefixMapping = PrefixMapping (T.Text, T.Text)
deriving (Eq, Ord)
instance Show PrefixMapping where
show (PrefixMapping (prefix, uri)) = printf "PrefixMapping (%s, %s)" (show prefix) (show uri)
-----------------
-- Miscellaneous helper functions used throughout the project
-- Resolve a prefix using the given prefix mappings and base URL. If the prefix is
-- empty, then the base URL will be used if there is a base URL and if the map
-- does not contain an entry for the empty prefix.
resolveQName :: Maybe BaseUrl -> T.Text -> PrefixMappings -> Maybe T.Text
resolveQName mbaseUrl prefix (PrefixMappings pms') =
case (mbaseUrl, T.null prefix) of
(Just (BaseUrl base), True) -> Just $ Map.findWithDefault base T.empty pms'
(_, _ ) -> Map.lookup prefix pms'
{- alternative implementation from Text.RDF.RDF4H.ParserUtils
--
-- Resolve a prefix using the given prefix mappings and base URL. If the prefix is
-- empty, then the base URL will be used if there is a base URL and if the map
-- does not contain an entry for the empty prefix.
resolveQName :: Maybe BaseUrl -> T.Text -> PrefixMappings -> T.Text
resolveQName mbaseUrl prefix (PrefixMappings pms') =
case (mbaseUrl, T.null prefix) of
(Just (BaseUrl base), True) -> Map.findWithDefault base T.empty pms'
(Nothing, True) -> err1
(_, _ ) -> Map.findWithDefault err2 prefix pms'
where
err1 = error "Cannot resolve empty QName prefix to a Base URL."
err2 = error ("Cannot resolve QName prefix: " ++ T.unpack prefix)
-}
-- Resolve a URL fragment found on the right side of a prefix mapping
-- by converting it to an absolute URL if possible.
absolutizeUrl :: Maybe BaseUrl -> Maybe T.Text -> T.Text -> T.Text
absolutizeUrl mbUrl mdUrl urlFrag =
if isAbsoluteUri urlFrag then urlFrag else
(case (mbUrl, mdUrl) of
(Nothing, Nothing) -> urlFrag
(Just (BaseUrl bUrl), Nothing) -> bUrl `T.append` urlFrag
(Nothing, Just dUrl) -> if isHash urlFrag then
dUrl `T.append` urlFrag else urlFrag
(Just (BaseUrl bUrl), Just dUrl) -> (if isHash urlFrag then dUrl
else bUrl)
`T.append` urlFrag)
where
isHash bs' = bs' == "#"
{- alternative implementation from Text.RDF.RDF4H.ParserUtils
--
-- Resolve a URL fragment found on the right side of a prefix mapping by converting it to an absolute URL if possible.
absolutizeUrl :: Maybe BaseUrl -> Maybe T.Text -> T.Text -> T.Text
absolutizeUrl mbUrl mdUrl urlFrag =
if isAbsoluteUri urlFrag then urlFrag else
(case (mbUrl, mdUrl) of
(Nothing, Nothing) -> urlFrag
(Just (BaseUrl bUrl), Nothing) -> bUrl `T.append` urlFrag
(Nothing, Just dUrl) -> if isHash urlFrag then
dUrl `T.append` urlFrag else urlFrag
(Just (BaseUrl bUrl), Just dUrl) -> (if isHash urlFrag then dUrl
else bUrl)
`T.append` urlFrag)
where
isHash bs' = T.length bs' == 1 && T.head bs' == '#'
-}
{-# INLINE mkAbsoluteUrl #-}
-- Make an absolute URL by returning as is if already an absolute URL and otherwise
-- appending the URL to the given base URL.
mkAbsoluteUrl :: T.Text -> T.Text -> T.Text
mkAbsoluteUrl base url =
if isAbsoluteUri url then url else base `T.append` url
-----------------
-- Internal canonicalize functions, don't export
-- |Canonicalize the given 'T.Text' value using the 'T.Text'
-- as the datatype URI.
{-# NOINLINE canonicalize #-}
canonicalize :: T.Text -> T.Text -> T.Text
canonicalize typeTxt litValue =
case Map.lookup typeTxt canonicalizerTable of
Nothing -> litValue
Just fn -> fn litValue
-- A table of mappings from a 'T.Text' URI
-- to a function that canonicalizes a T.Text
-- assumed to be of that type.
{-# NOINLINE canonicalizerTable #-}
canonicalizerTable :: Map T.Text (T.Text -> T.Text)
canonicalizerTable =
Map.fromList [(integerUri, _integerStr), (doubleUri, _doubleStr),
(decimalUri, _decimalStr)]
where
integerUri = "http://www.w3.org/2001/XMLSchema#integer"
decimalUri = "http://www.w3.org/2001/XMLSchema#decimal"
doubleUri = "http://www.w3.org/2001/XMLSchema#double"
_integerStr, _decimalStr, _doubleStr :: T.Text -> T.Text
_integerStr = T.dropWhile (== '0')
-- exponent: [eE] ('-' | '+')? [0-9]+
-- ('-' | '+') ? ( [0-9]+ '.' [0-9]* exponent | '.' ([0-9])+ exponent | ([0-9])+ exponent )
_doubleStr s = T.pack $ show (read $ T.unpack s :: Double)
-- ('-' | '+')? ( [0-9]+ '.' [0-9]* | '.' ([0-9])+ | ([0-9])+ )
_decimalStr s = -- haskell double parser doesn't handle '1.'..,
case T.last s of -- so we add a zero if that's the case and then parse
'.' -> f (s `T.snoc` '0')
_ -> f s
where f s' = T.pack $ show (read $ T.unpack s' :: Double)
-- | Removes "file://" schema from URIs in 'UNode' nodes
fileSchemeToFilePath :: Node -> Maybe T.Text
fileSchemeToFilePath (UNode fileScheme) =
if T.pack "file://" `T.isPrefixOf` fileScheme
then fmap (T.pack . Network.uriPath) (Network.parseURI (T.unpack fileScheme))
else Nothing
fileSchemeToFilePath _ = Nothing
| jutaro/rdf4h | src/Data/RDF/Types.hs | bsd-3-clause | 28,112 | 0 | 23 | 7,288 | 5,109 | 2,786 | 2,323 | -1 | -1 |
module GHCJS.Require
where
import Control.Concurrent
import Control.Monad
import Data.JSString
import Data.String
import GHCJS.Foreign
import GHCJS.Foreign.Callback
import GHCJS.Marshal
import GHCJS.Types
import JavaScript.Array
import JavaScript.Object
import JavaScript.EventEmitter
import Data.Coerce
import System.IO.Unsafe
defaultMain = do
emitter <- getRequireEmitter
on2 emitter "ghcjs-require:runexport" $ \name cb -> do
Just str <- fromJSVal name :: IO (Maybe JSString)
maction <- getExport (unpack str)
mvl <- case maction of
Just action -> action
Nothing -> return Nothing
case mvl of
Just vl -> call2 cb nullRef vl
Nothing -> call1 cb nullRef
emit0 emitter "ghcjs-require:loaded"
foreign import javascript unsafe "$1()"
call0 :: JSVal -> IO ()
foreign import javascript unsafe "$1($2)"
call1 :: JSVal -> JSVal -> IO ()
foreign import javascript unsafe "$1($2, $3)"
call2 :: JSVal -> JSVal -> JSVal -> IO ()
exports = unsafePerformIO (newMVar [])
{-# NOINLINE exports #-}
getExport :: String -> IO (Maybe (IO (Maybe JSVal)))
getExport name = lookup name <$> readMVar exports
registerExport :: String -> IO (Maybe JSVal) -> IO ()
registerExport name action = modifyMVar_ exports $ \e ->
return $ (name, action):e
require :: String -> IO JSVal
require = js_require . fromString
export :: String -> IO (Maybe JSVal) -> IO ()
export name action = do
let name' = fromString name
registerExport name $ action
callback <- asyncCallback (void action)
js_export name' callback
export0 name action = export name $ do
action
return Nothing
getRequireEmitter :: IO EventEmitter
getRequireEmitter = emitter <$> js_getRequireEmitter
foreign import javascript unsafe "$r = require($1)"
js_require :: JSString -> IO JSVal
-- foreign import javascript unsafe "global.startAction"
-- js_startAction :: IO JSString
-- foreign import javascript unsafe "global.finishAction"
-- js_finishAction0 :: JSString -> IO ()
foreign import javascript unsafe "global.exports[$1] = $2"
js_export :: JSString -> Callback a -> IO ()
foreign import javascript unsafe "global.emitter"
js_getRequireEmitter :: IO Object
| beijaflor-io/ghcjs-commonjs | old-examples/ghcjs-loader-test/GHCJS/Require.hs | mit | 2,375 | 18 | 16 | 583 | 647 | 322 | 325 | 58 | 3 |
-- Copyright (c) Microsoft. All rights reserved.
-- Licensed under the MIT license. See LICENSE file in the project root for full license information.
{-# LANGUAGE QuasiQuotes, OverloadedStrings #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
{-|
Copyright : (c) Microsoft
License : MIT
Maintainer : adamsap@microsoft.com
Stability : provisional
Portability : portable
Helper functions for creating common text structures useful in code generation.
These functions operate on 'Text' objects.
-}
module Language.Bond.Codegen.Util
( commonHeader
, newlineSep
, commaLineSep
, newlineSepEnd
, newlineBeginSep
, doubleLineSep
, doubleLineSepEnd
) where
import Data.Int (Int64)
import Data.Word
import Prelude
import Data.Text.Lazy (Text, justifyRight)
import Text.Shakespeare.Text
import Paths_bond (version)
import Data.Version (showVersion)
import Language.Bond.Util
instance ToText Word16 where
toText = toText . show
instance ToText Double where
toText = toText . show
instance ToText Integer where
toText = toText . show
indent :: Int64 -> Text
indent n = justifyRight (4 * n) ' ' ""
commaLine :: Int64 -> Text
commaLine n = [lt|,
#{indent n}|]
newLine :: Int64 -> Text
newLine n = [lt|
#{indent n}|]
doubleLine :: Int64 -> Text
doubleLine n = [lt|
#{indent n}|]
newlineSep, commaLineSep, newlineSepEnd, newlineBeginSep, doubleLineSep, doubleLineSepEnd
:: Int64 -> (a -> Text) -> [a] -> Text
-- | Separates elements of a list with new lines. Starts new lines at the
-- specified indentation level.
newlineSep = sepBy . newLine
-- | Separates elements of a list with comma followed by a new line. Starts
-- new lines at the specified indentation level.
commaLineSep = sepBy . commaLine
-- | Separates elements of a list with new lines, ending with a new line.
-- Starts new lines at the specified indentation level.
newlineSepEnd = sepEndBy . newLine
-- | Separates elements of a list with new lines, beginning with a new line.
-- Starts new lines at the specified indentation level.
newlineBeginSep = sepBeginBy . newLine
-- | Separates elements of a list with two new lines. Starts new lines at
-- the specified indentation level.
doubleLineSep = sepBy . doubleLine
-- | Separates elements of a list with two new lines, ending with two new
-- lines. Starts new lines at the specified indentation level.
doubleLineSepEnd = sepEndBy . doubleLine
-- | Returns common header for generated files using specified single-line
-- comment lead character(s) and a file name.
commonHeader :: ToText a => a -> a -> Text
commonHeader c file = [lt|
#{c}------------------------------------------------------------------------------
#{c} This code was generated by a tool.
#{c}
#{c} Tool : Bond Compiler #{showVersion version}
#{c} File : #{file}
#{c}
#{c} Changes to this file may cause incorrect behavior and will be lost when
#{c} the code is regenerated.
#{c} <auto-generated />
#{c}------------------------------------------------------------------------------
|]
| alfpark/bond | compiler/src/Language/Bond/Codegen/Util.hs | mit | 3,036 | 0 | 8 | 529 | 382 | 235 | 147 | 28 | 1 |
{-# LANGUAGE Rank2Types #-}
{-# LANGUAGE RecordWildCards #-}
-- | Propagation of runtime configuration.
module Pos.Chain.Update.Configuration
( UpdateConfiguration(..)
, HasUpdateConfiguration
, updateConfiguration
, withUpdateConfiguration
, ourAppName
, ourSystemTag
, lastKnownBlockVersion
, curSoftwareVersion
, currentSystemTag
, ccApplicationName_L
, ccLastKnownBlockVersion_L
, ccApplicationVersion_L
, ccSystemTag_L
) where
import Universum
import Control.Lens (makeLensesWith)
import Data.Aeson (FromJSON (..), ToJSON (..), object, withObject,
(.:), (.:?), (.=))
import Data.Maybe (fromMaybe)
import Data.Reflection (Given (..), give)
import Distribution.System (buildArch, buildOS)
import Pos.Chain.Update.ApplicationName
(ApplicationName (ApplicationName))
import Pos.Chain.Update.BlockVersion (BlockVersion (..))
import Pos.Chain.Update.SoftwareVersion (SoftwareVersion (..))
import Pos.Chain.Update.SystemTag (SystemTag (..), archHelper,
osHelper)
import Pos.Util (postfixLFields)
----------------------------------------------------------------------------
-- Config itself
----------------------------------------------------------------------------
type HasUpdateConfiguration = Given UpdateConfiguration
withUpdateConfiguration :: UpdateConfiguration -> (HasUpdateConfiguration => r) -> r
withUpdateConfiguration = give
updateConfiguration :: HasUpdateConfiguration => UpdateConfiguration
updateConfiguration = given
data UpdateConfiguration = UpdateConfiguration
{
-- | Name of this application.
ccApplicationName :: !ApplicationName
-- | Last known block version
, ccLastKnownBlockVersion :: !BlockVersion
-- | Application version
, ccApplicationVersion :: !Word32
-- | System tag.
, ccSystemTag :: !SystemTag
}
deriving (Eq, Generic, Show)
makeLensesWith postfixLFields ''UpdateConfiguration
instance ToJSON UpdateConfiguration where
toJSON (UpdateConfiguration (ApplicationName appname) lkbv appver (SystemTag systag)) = object [
"applicationName" .= appname
, "lastKnownBlockVersion" .= lkbv
, "applicationVersion" .= appver
, "systemTag" .= systag
]
instance FromJSON UpdateConfiguration where
parseJSON = withObject "UpdateConfiguration" $ \o -> do
ccApplicationName <- o .: "applicationName"
ccLastKnownBlockVersion <- o .: "lastKnownBlockVersion"
ccApplicationVersion <- o .: "applicationVersion"
ccSystemTag <- fromMaybe currentSystemTag <$> o .:? "systemTag"
pure UpdateConfiguration {..}
----------------------------------------------------------------------------
-- Various constants
----------------------------------------------------------------------------
-- | Name of our application.
ourAppName :: UpdateConfiguration -> ApplicationName
ourAppName = ccApplicationName
-- | Last block version application is aware of.
lastKnownBlockVersion :: UpdateConfiguration -> BlockVersion
lastKnownBlockVersion = ccLastKnownBlockVersion
-- | Version of application (code running)
curSoftwareVersion :: UpdateConfiguration -> SoftwareVersion
curSoftwareVersion uc = SoftwareVersion (ourAppName uc) (ccApplicationVersion uc)
-- | @SystemTag@ corresponding to the operating system/architecture pair the program was
-- compiled in.
-- The @Distribution.System@ module
-- (https://hackage.haskell.org/package/Cabal-2.0.1.1/docs/Distribution-System.html)
-- from @Cabal@ was used to access to a build's host machine @OS@ and @Arch@itecture
-- information.
currentSystemTag :: SystemTag
currentSystemTag = SystemTag (toText (osHelper buildOS ++ archHelper buildArch))
ourSystemTag :: UpdateConfiguration -> SystemTag
ourSystemTag = ccSystemTag
| input-output-hk/pos-haskell-prototype | chain/src/Pos/Chain/Update/Configuration.hs | mit | 4,038 | 0 | 13 | 828 | 628 | 370 | 258 | -1 | -1 |
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE Safe #-}
{-# LANGUAGE UndecidableInstances #-}
module Network.Tox.Timed where
import Control.Monad.RWS (RWST)
import Control.Monad.Random (RandT)
import Control.Monad.Reader (ReaderT)
import Control.Monad.State (StateT)
import Control.Monad.Trans (lift)
import Control.Monad.Writer (WriterT)
import Network.Tox.Time (Timestamp)
class Monad m => Timed m where
askTime :: m Timestamp
instance Timed m => Timed (ReaderT r m) where
askTime = lift askTime
instance (Monoid w, Timed m) => Timed (WriterT w m) where
askTime = lift askTime
instance Timed m => Timed (StateT s m) where
askTime = lift askTime
instance (Monoid w, Timed m) => Timed (RWST r w s m) where
askTime = lift askTime
instance Timed m => Timed (RandT s m) where
askTime = lift askTime
| iphydf/hs-toxcore | src/Network/Tox/Timed.hs | gpl-3.0 | 954 | 0 | 7 | 240 | 287 | 156 | 131 | 24 | 0 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- |
-- Module : Network.AWS.ImportExport.Types.Product
-- 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)
--
module Network.AWS.ImportExport.Types.Product where
import Network.AWS.ImportExport.Types.Sum
import Network.AWS.Prelude
-- | A discrete item that contains the description and URL of an artifact
-- (such as a PDF).
--
-- /See:/ 'artifact' smart constructor.
data Artifact = Artifact'
{ _aURL :: !(Maybe Text)
, _aDescription :: !(Maybe Text)
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'Artifact' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'aURL'
--
-- * 'aDescription'
artifact
:: Artifact
artifact =
Artifact'
{ _aURL = Nothing
, _aDescription = Nothing
}
-- | Undocumented member.
aURL :: Lens' Artifact (Maybe Text)
aURL = lens _aURL (\ s a -> s{_aURL = a});
-- | Undocumented member.
aDescription :: Lens' Artifact (Maybe Text)
aDescription = lens _aDescription (\ s a -> s{_aDescription = a});
instance FromXML Artifact where
parseXML x
= Artifact' <$>
(x .@? "URL") <*> (x .@? "Description")
-- | Representation of a job returned by the ListJobs operation.
--
-- /See:/ 'job' smart constructor.
data Job = Job'
{ _jobJobType :: !JobType
, _jobJobId :: !Text
, _jobIsCanceled :: !Bool
, _jobCreationDate :: !ISO8601
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'Job' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'jobJobType'
--
-- * 'jobJobId'
--
-- * 'jobIsCanceled'
--
-- * 'jobCreationDate'
job
:: JobType -- ^ 'jobJobType'
-> Text -- ^ 'jobJobId'
-> Bool -- ^ 'jobIsCanceled'
-> UTCTime -- ^ 'jobCreationDate'
-> Job
job pJobType_ pJobId_ pIsCanceled_ pCreationDate_ =
Job'
{ _jobJobType = pJobType_
, _jobJobId = pJobId_
, _jobIsCanceled = pIsCanceled_
, _jobCreationDate = _Time # pCreationDate_
}
-- | Undocumented member.
jobJobType :: Lens' Job JobType
jobJobType = lens _jobJobType (\ s a -> s{_jobJobType = a});
-- | Undocumented member.
jobJobId :: Lens' Job Text
jobJobId = lens _jobJobId (\ s a -> s{_jobJobId = a});
-- | Undocumented member.
jobIsCanceled :: Lens' Job Bool
jobIsCanceled = lens _jobIsCanceled (\ s a -> s{_jobIsCanceled = a});
-- | Undocumented member.
jobCreationDate :: Lens' Job UTCTime
jobCreationDate = lens _jobCreationDate (\ s a -> s{_jobCreationDate = a}) . _Time;
instance FromXML Job where
parseXML x
= Job' <$>
(x .@ "JobType") <*> (x .@ "JobId") <*>
(x .@ "IsCanceled")
<*> (x .@ "CreationDate")
| fmapfmapfmap/amazonka | amazonka-importexport/gen/Network/AWS/ImportExport/Types/Product.hs | mpl-2.0 | 3,278 | 0 | 11 | 742 | 635 | 378 | 257 | 70 | 1 |
{-# OPTIONS -fglasgow-exts #-}
-----------------------------------------------------------------------------
{-| Program : dem_01.hs
Copyright : (c) David Harley 2010
Project : qtHaskell
Version : 1.1.4
Modified : 2010-09-02 17:02:47
Warning : this file is machine generated - do not modify.
--}
-----------------------------------------------------------------------------
module Main where
import Qth.ClassTypes.Core
import Qth.Core.Size
import Qth.Core.Rect
import Qtc.Classes.Qccs
import Qtc.Classes.Qccs_h
import Qtc.Classes.Core
import Qtc.Classes.Gui
import Qtc.Classes.Base
import Qtc.Enums.Classes.Core
import Qtc.Enums.Base
import Qtc.ClassTypes.Core
import Qtc.Core.Base
import Qtc.Enums.Core.Qt
import Qtc.Core.QCoreApplication
import Qtc.Core.QIODevice
import Qtc.Enums.Core.QIODevice
import Qtc.Core.QFile
import Qtc.Core.QTextStream
import Qtc.ClassTypes.Gui
import Qtc.Gui.Base
import Qtc.Gui.QApplication
import Qtc.Gui.QWidget
import Qtc.ClassTypes.Tools
import Qtc.Tools.QUiLoader
import Qtc.Tools.QUiLoader_h
import Qtc.Gui.QMainWindow
import Qtc.Gui.QAction
import Qtc.Gui.QTextEdit
import Qtc.Gui.QFileDialog
import Qtc.Core.QDir
import Qtc.Gui.QImage
import Qtc.Gui.QPixmap
import Qtc.Gui.QLabel
import Qtc.Gui.QScrollArea
import Qtc.Gui.QAbstractScrollArea
import Qtc.Gui.QScrollBar
import Qtc.Gui.QAbstractSlider
import Qtc.Enums.Gui.QPalette
import Qtc.Enums.Gui.QSizePolicy
import Qtc.Core.QRect
import Qtc.Core.QSize
import Qtc.Core.QFileInfo
import Data.IORef
import Data.Array.IO
import Data.Array.MArray
import Data.Array.Unboxed
import Data.List
import Numeric
import System.CPUTime
type MainWindow = QMainWindowSc (CMainWindow)
data CMainWindow = CMainWindow
mainWindow :: IO (MainWindow)
mainWindow = qSubClass (qMainWindow ())
type MdiGC = QMainWindowSc (CMdiGC)
data CMdiGC = CMdiGC
mdiGC :: MainWindow -> IO (MdiGC)
mdiGC mw = qSubClass (qMainWindow mw)
main :: IO ()
main
= do
app <- qApplication ()
rok <- registerResource "dem_01.rcc"
loader <- qUiLoader ()
mw <- mainWindow
gcList <- newIORef []
setHandler loader "(QWidget*)createWidget(const QString&,QWidget*,const QString&)" $ myCreateWidget mw
uiFile <- qFile ":/dem_01.ui"
open uiFile fReadOnly
ui <- load loader uiFile
close uiFile ()
ui_init mw gcList ui
qshow ui ()
ok <- qApplicationExec ()
return ()
myCreateWidget :: MainWindow -> QUiLoader () -> String -> QWidget a -> String -> IO (QWidget ())
myCreateWidget mw this cname this_parent name
= do
case (cname) of
_ | cname == "QMainWindow"
-> do
setParent mw this_parent
tp <- qObjectParentSc mw
setObjectName tp name
return (objectCast tp)
_
-> createWidget_h this (cname, this_parent, name)
ui_init :: MainWindow -> IORef [MdiGC] -> QWidget () -> IO ()
ui_init mw gcList ui
= do
ui_c <- findChild ui ("<QTextEdit*>", "centralwidget")
ui_s <- findChild ui ("<QAction*>", "action_Shape_from_Shading")
ui_l <- findChild ui ("<QAction*>", "action_Load_Image")
connectSlot ui_s "triggered()" mw "sfs()" sfs
connectSlot ui_l "triggered()" mw "load_image()" (load_image ui_c gcList)
return ()
load_image :: QTextEdit () -> IORef [MdiGC] -> MainWindow -> IO ()
load_image te gcList this
= do
hp <- qDirHomePath ()
let hpi = hp ++ "/tq/dem_01/bmp"
fileName <- qFileDialogGetOpenFileName (this, "Load Image", hpi, "Bitmap Files (*.bmp)")
if (fileName /= "")
then
do
insertPlainText te "Image File Name: "
insertPlainText te =<< qDirToNativeSeparators fileName
insertPlainText te "\n"
(ngc, gcv) <- new_gc te this gcList
lok <- loadFile_gc te this gcList ngc gcv fileName False
if (lok)
then qshow (ui gcv) ()
else return ()
else
return ()
return ()
sfs :: MainWindow -> IO ()
sfs this
= return ()
new_gc :: QTextEdit () -> MainWindow -> IORef [MdiGC] -> IO (MdiGC, GCv)
new_gc te this gcList
= do
loader <- qUiLoader ()
ngc <- mdiGC this
setHandler loader "(QWidget*)createWidget(const QString&,QWidget*,const QString&)" $ myCreateWidget_gc ngc
uiFile <- qFile ":/dem_01_mdigc_mw.ui"
open uiFile fReadOnly
nui <- load loader uiFile
close uiFile ()
gcv <- ui_init_gc te this ngc gcList nui
return (ngc, gcv)
loadFile_gc :: QTextEdit () -> MainWindow -> IORef [MdiGC] -> MdiGC -> GCv -> String -> Bool -> IO (Bool)
loadFile_gc te this gcList cm gcv fn dem
= do
tfi <- qFileInfo fn
tdr <- dir tfi ()
tpth <- path tdr ()
tbfn <- baseName tfi ()
tsuf <- suffix tfi ()
modifyIORef (pth gcv) (\_ -> tpth)
modifyIORef (bfn gcv) (\_ -> tbfn)
modifyIORef (suf gcv) (\_ -> tsuf)
ti <- qImage ()
if (not dem)
then
do
lok <- load ti fn
if (lok)
then
do
tp <- qPixmapFromImage ti
tg <- allGray ti ()
insertPlainText te "allGray: "
if (tg)
then
insertPlainText te "true"
else
insertPlainText te "false"
insertPlainText te ", numColors: "
tn <- numColors ti ()
insertPlainText te $ show tn
insertPlainText te "\n"
lfgc_s1 ti tp gcv cm fn
return True
else
return False
else
return False
lfgc_s1 ti tp gcv cm fn
= do
modifyIORef (gc_image gcv) (\_ -> ti)
modifyIORef (gc_pixmap gcv) (\_ -> tp)
setCurrentFile cm gcv fn
w <- qwidth ti ()
h <- qheight ti ()
let r = rect 0 0 w h
setGeometry (label gcv) r
setPixmap (label gcv) tp
modifyIORef (scaleFactor gcv) (\_ -> 1.0)
setEnabled (a_fw gcv) True
updateActions gcv
ic <- isChecked (a_fw gcv) ()
if (not ic)
then adjustSize (label gcv) ()
else return ()
updateActions :: GCv -> IO ()
updateActions gcv
= do
ic <- isChecked (a_fw gcv) ()
setEnabled (a_zi gcv) (not ic)
setEnabled (a_zo gcv) (not ic)
setEnabled (a_ns gcv) (not ic)
setCurrentFile :: MdiGC -> GCv -> String -> IO ()
setCurrentFile cm gcv fn
= do
tfi <- qFileInfo fn
cf <- canonicalFilePath tfi ()
modifyIORef (curFile gcv) (\_ -> cf)
tuf <- userFriendlyCurrentFile gcv
setWindowTitle cm $ tuf ++ "[*]"
userFriendlyCurrentFile :: GCv -> IO String
userFriendlyCurrentFile gcv
= do
cf <- readIORef $ curFile gcv
strippedName cf
strippedName :: String -> IO String
strippedName ffn
= do
fi <- qFileInfo ffn
fileName fi ()
myCreateWidget_gc :: MdiGC -> QUiLoader () -> String -> QWidget a -> String -> IO (QWidget ())
myCreateWidget_gc cm this cname this_parent name
= do
case (cname) of
_ | cname == "QMainWindow"
-> do
setParent cm this_parent
tp <- qObjectParent cm
setObjectName tp name
return (objectCast tp)
_
-> createWidget_h this (cname, this_parent, name)
data GCv = GCv {ui :: QWidget (),
a_zi,
a_zo,
a_ns,
a_fw :: QAction (),
label :: QLabel (),
scrollArea :: QScrollArea (),
scaleFactor :: IORef Double,
gc_image :: IORef (QImage ()),
gc_pixmap :: IORef (QPixmap ()),
curFile :: IORef String,
pth :: IORef String,
bfn :: IORef String,
suf :: IORef String
}
ui_init_gc :: QTextEdit () -> MainWindow -> MdiGC -> IORef [MdiGC] -> QWidget () -> IO (GCv)
ui_init_gc te mw cm gcList ui
= do
label <- qLabel ()
setObjectName label "label"
setSizePolicy label (eIgnored, eIgnored)
setScaledContents label True
scrollArea <- qScrollArea cm
setBackgroundRole scrollArea eDark
setWidget scrollArea label
setCentralWidget cm scrollArea
ui_si <- findChild ui ("<QAction*>", "action_Save_Image")
ui_V1 <- findChild ui ("<QAction*>", "action_V1")
ui_V2 <- findChild ui ("<QAction*>", "action_V2")
ui_V3 <- findChild ui ("<QAction*>", "action_V3")
ui_zi <- findChild ui ("<QAction*>", "action_Zoom_In")
ui_zo <- findChild ui ("<QAction*>", "action_Zoom_Out")
ui_ns <- findChild ui ("<QAction*>", "action_Normal_Size")
ui_fw <- findChild ui ("<QAction*>", "action_Fit_to_Window")
sf <- newIORef 0.0
ti <- newIORef objectNull
tp <- newIORef objectNull
ts <- newIORef ""
td <- newIORef ""
tb <- newIORef ""
tu <- newIORef ""
let gcv = GCv ui ui_zi ui_zo ui_ns ui_fw label scrollArea sf ti tp ts td tb tu
connectSlot ui_si "triggered()" cm "save_image()" (save_image te mw gcList gcv)
connectSlot ui_V1 "triggered()" cm "v1()" (v1 te mw gcList gcv)
connectSlot ui_V2 "triggered()" cm "v2()" (v2 te mw gcList gcv)
connectSlot ui_V3 "triggered()" cm "v3()" (v3 te mw gcList gcv)
setEnabled ui_zi False
connectSlot ui_zi "triggered()" cm "zoomIn()" (zmIn gcv)
setEnabled ui_zo False
connectSlot ui_zo "triggered()" cm "zoomOut()" (zmOut gcv)
setEnabled ui_ns False
connectSlot ui_ns "triggered()" cm "normalSize()" (normalSize gcv)
setCheckable ui_fw True
connectSlot ui_fw "triggered()" cm "fitToWindow()" (fitToWindow gcv)
return (gcv)
save_image :: QTextEdit () -> MainWindow -> IORef [MdiGC] -> GCv -> MdiGC -> IO ()
save_image te mw gcList gcv cm
= do
return ()
v1 :: QTextEdit () -> MainWindow -> IORef [MdiGC] -> GCv -> MdiGC -> IO ()
v1 te mw gcList gcv cm
= do
return ()
v2 :: QTextEdit () -> MainWindow -> IORef [MdiGC] -> GCv -> MdiGC -> IO ()
v2 te mw gcList gcv cm
= do
return ()
v3 :: QTextEdit () -> MainWindow -> IORef [MdiGC] -> GCv -> MdiGC -> IO ()
v3 te mw gcList gcv cm
= do
(ngc, ngcv) <- new_gc te mw gcList
tpth <- readIORef (pth gcv)
tbfn <- readIORef (bfn gcv)
tsuf <- readIORef (suf gcv)
timg <- readIORef (gc_image gcv)
let nbfn = tbfn ++ "_V3"
nfn = tpth ++ "/" ++ nbfn ++ "." ++ tsuf
modifyIORef (pth ngcv) (\_ -> tpth)
modifyIORef (bfn ngcv) (\_ -> nbfn)
modifyIORef (suf ngcv) (\_ -> tsuf)
modifyIORef (gc_image ngcv) (\_ -> timg)
modifyIORef gcList (\cl -> ngc:cl)
do_v3 te mw gcList ngcv ngc nfn
qshow (ui ngcv) ()
return ()
data Region_ds = Region_ds {ptr :: Int, done :: Bool}
data Da1_map_ds = Da1_map_ds {avg :: Double, cnt, ctr, prt :: Int}
data Pdf_glb_ds_V3 = Pdf_glb_ds_V3 {g_act :: Bool, g_min_tsh :: Double}
data Pdf_row_ds_V3 = Pdf_row_ds_V3 {r_act :: Bool, r_rf, r_min_tsh :: Double}
data Pdf_pix_ds_V3 = Pdf_pix_ds_V3 {p_act :: Bool, p_rf, p_min_tsh :: Double}
rds_ud = -2
rds_na = -1
udf = -2
do_v3 :: QTextEdit () -> MainWindow -> IORef [MdiGC] -> GCv -> MdiGC -> String -> IO ()
do_v3 te mw gcList gcv cm fn
= do
bfn <- readIORef (bfn gcv)
image <- readIORef (gc_image gcv)
pixmap <- readIORef (gc_pixmap gcv)
setWindowTitle cm $ bfn ++ "[*]"
w <- qwidth image ()
h <- qheight image ()
let sz = w * h
apt_map <- newArray (0, (sz - 1)) False :: IO (IOUArray Int Bool)
da1_pro <- newArray (0, (sz - 1)) False :: IO (IOUArray Int Bool)
da1_reg <- newArray (0, (sz - 1)) 0 :: IO (IOUArray Int Int)
da1_reg_pro <- newArray (0, (sz - 1)) 0 :: IO (IOUArray Int Int)
ref_map <- newArray (0, (sz - 1)) 0.0 :: IO (IOUArray Int Double)
da1_ind <- newArray (0, (sz - 1)) udf :: IO (IOUArray Int Int)
pdf_glb <- newIORef (Pdf_glb_ds_V3 False 0.0)
pdf_row <- newArray (0, (h - 1)) (Pdf_row_ds_V3 False 0.0 0.0) :: IO (IOArray Int Pdf_row_ds_V3)
pdf_pix <- newArray (0, (sz - 1)) (Pdf_pix_ds_V3 False 0.0 0.0) :: IO (IOArray Int Pdf_pix_ds_V3)
da1_map <- newArray (0, (sz - 1)) (Da1_map_ds 0.0 0 0 0) :: IO (IOArray Int Da1_map_ds)
da1_ndn <- newArray (0, ((sz * 8) - 1)) (Region_ds rds_ud False) :: IO (IOArray Int Region_ds)
let pdf_nam = fn ++ "." ++ "pdf"
pdf <- qFile pdf_nam
ook <- open pdf (fReadOnly + fText)
if (ook)
then
do
ins <- qTextStream pdf
process_line_V3 te ins pdf_glb pdf_row pdf_pix w
else
return ()
cur_glb <- readIORef pdf_glb
im_pdf_row <- freeze pdf_row :: IO (Array Int Pdf_row_ds_V3)
let min_tsh
= if (g_act cur_glb)
then
g_min_tsh cur_glb
else
40
mapM_ (\i ->
do
cur_row <- readArray pdf_row i
(cur_row_rf, cur_row_min_tsh)
<- if (r_act cur_row)
then
do
let rf = r_rf cur_row
min_tsh = r_min_tsh cur_row
insertPlainText te $ "Act Row: " ++
(show i) ++ ", " ++
(show rf) ++ ", " ++
(show min_tsh) ++ "\n"
return (rf, min_tsh)
else
return (0.0, 0.0)
mapM_ (\(i, j) ->
do
let map_ptr = (i * w) + j
cur_pix <- readArray pdf_pix map_ptr
(cur_pix_rf, cur_pix_min_tsh)
<- if (p_act cur_pix)
then
do
let rf = p_rf cur_pix
min_tsh = p_min_tsh cur_pix
insertPlainText te $ "Act Pix: " ++
(show i) ++ ", " ++
(show j) ++ ", " ++
(show rf) ++ ", " ++
(show min_tsh) ++ "\n"
return (rf, min_tsh)
else
return (0.0, 0.0)
pi <- pixelIndex image (j, i)
let cur_val = fromIntegral pi
writeArray ref_map map_ptr cur_val
let apt = not $ cur_val < (min_tsh + cur_row_min_tsh + cur_pix_min_tsh)
writeArray apt_map map_ptr apt
writeArray da1_pro map_ptr False
writeArray da1_ind map_ptr map_ptr
)
[(i, j) | j <- [0..(w - 1)]]
)
[0..(h - 1)]
insertPlainText te $ "new image: \n" ++
"- width, height: " ++
(show w) ++ ", " ++
(show h) ++ "\n"
mi <- mapM (\i ->
do
mr <- mapM (\(i, j) ->
do
let map_ptr = (i * w) + j
dl <- mapM (\(i, j, map_ptr, k) ->
do
let m8k = (map_ptr * 8) + k
m8p = case k of
0 | ((i > 0) && (j > 0))
-> map_ptr - w - 1
1 | (i > 0)
-> map_ptr - w
2 | ((i > 0) && (j < (w - 1)))
-> map_ptr - w + 1
3 | (j < (w - 1))
-> map_ptr + 1
4 | ((i < (h - 1)) && (j < (w - 1)))
-> map_ptr + w + 1
5 | (i < (h - 1))
-> map_ptr + w
6 | ((i < (h - 1)) && (j > 0))
-> map_ptr + w - 1
7 | (j > 0)
-> map_ptr - 1
_
-> udf
writeArray da1_ndn m8k $ Region_ds m8p False
if (m8p /= udf)
then
do
cur_val <- readArray ref_map map_ptr
dif_val <- readArray ref_map m8p
return $ cur_val - dif_val
else
return 0.0
)
[(i, j, map_ptr, k) | k <-[0..7]]
let dlf = filter (/= 0.0) dl
cdc = length dlf
cda = if (cdc > 0) then (sum dlf) / (fromIntegral cdc) else 0.0
cdm = abs ((h `div` 2) - i) + abs ((w `div` 2) - j)
if (map_ptr < 21)
then
insertPlainText te $ "dl, dlf, cdc, cda, cdm: " ++
(show dl) ++ ", " ++
(show dlf) ++ ", " ++
(show cdc) ++ ", " ++
(show cda) ++ ", " ++
(show cdm) ++ "\n"
else
return ()
writeArray da1_map map_ptr $ Da1_map_ds cda cdc cdm 0
return cda
)
[(i, j) | j <- [0..(w - 1)]]
return (minimum mr, maximum mr)
)
[0..(h - 1)]
let uzmi = unzip mi
da1_min = minimum $ fst uzmi
da1_max = maximum $ snd uzmi
da1_dif = da1_max - da1_min
cpu_bs <- getCPUTime
da1_srt <- da1_sort te da1_map [0..(sz - 1)] 1 1
cpu_as <- getCPUTime
insertPlainText te $ "sort time: " ++ (show (cpu_as - cpu_bs)) ++ "\n"
let da1_ind = listArray (0, sz - 1) da1_srt :: UArray Int Int
da1_pro_cnt <- newIORef 0
da1_chk_cnt <- newIORef 0
da1_reg_cnt <- newIORef 0
mapM_ (\i ->
do
let da1_map_ptr = da1_ind ! i
c_pro <- readArray da1_pro da1_map_ptr
c_apt <- readArray apt_map da1_map_ptr
c_map <- readArray da1_map da1_map_ptr
c_pro_cnt <- readIORef da1_pro_cnt
c_chk_cnt <- readIORef da1_chk_cnt
c_reg_cnt <- readIORef da1_reg_cnt
if (i < 100)
then
insertPlainText te $ "i, mp, c_pro, c_apt, avg c_map: " ++
(show i) ++ ", " ++
(show da1_map_ptr) ++ ", " ++
(show c_pro) ++ ", " ++
(show c_apt) ++ ", " ++
(show (avg c_map)) ++ "\n"
else
return ()
if ((not c_pro) && c_apt && ((avg c_map) < 5))
then
do
writeArray da1_pro da1_map_ptr True
writeArray da1_reg da1_map_ptr c_reg_cnt
let ti = div i w
tj = mod i w
insertPlainText te $ "new region: " ++
(show c_reg_cnt) ++ "\n" ++
"- ind, ptr, i, j: " ++
(show i) ++ ", " ++
(show da1_map_ptr) ++ ", " ++
(show ti) ++ ", " ++
(show tj) ++ "\n"
do_region (-1) da1_map_ptr da1_map apt_map da1_pro da1_pro_cnt ref_map da1_reg da1_reg_cnt da1_ndn True
check_region da1_map_ptr da1_map da1_pro da1_pro_cnt da1_reg da1_reg_cnt da1_ndn
nc_pro_cnt <- readIORef da1_pro_cnt
if (nc_pro_cnt == 1)
then
do
writeArray da1_pro da1_map_ptr False;
modifyIORef da1_pro_cnt (\_ -> 0)
else
return ()
ncf_pro_cnt <- readIORef da1_pro_cnt
insertPlainText te $ "- pro: " ++
(show ncf_pro_cnt) ++ "\n"
if (ncf_pro_cnt == 0)
then
return ()
else
do
writeArray da1_reg_pro c_reg_cnt ncf_pro_cnt
modifyIORef da1_pro_cnt (\_ -> 0)
modifyIORef da1_chk_cnt (\_ -> 0)
modifyIORef da1_reg_cnt (\_ -> c_reg_cnt + 1)
else
return ()
)
[1..(sz - 1)]
mapM_ (\i ->
do
mapM_ (\(i, j) ->
do
let map_ptr = (i * w) + j
c_pro <- readArray da1_pro map_ptr
if (not c_pro)
then
setPixel image (j, i, 255::Int)
else
do
tr <- readArray da1_reg map_ptr
if (tr < 12)
then
setPixel image (j, i, 230::Int)
else
setPixel image (j, i, ((mod tr 20) * 10))
)
[(i, j) | j <- [0..(w - 1)]]
)
[i | i <- [0..(h - 1)]]
cpu_ar <- getCPUTime
insertPlainText te $ "regions time: " ++ (show (cpu_ar - cpu_as)) ++ "\n"
c_pmp <- qPixmapFromImage image
let gr = rect 0 0 w h
setGeometry (label gcv) gr
setPixmap (label gcv) c_pmp
modifyIORef (scaleFactor gcv) (\_ -> 1.0)
setEnabled (a_fw gcv) True
ic <- isChecked (a_fw gcv) ()
if (not ic)
then adjustSize (label gcv) ()
else return ()
undo_region :: Int -> IOArray Int Da1_map_ds -> IOUArray Int Bool -> IORef Int -> IOArray Int Region_ds -> IO ()
undo_region mp map pro pc ndn
= do
writeArray pro mp False
modifyIORef pc (\x -> x - 1)
c_map <- readArray map mp
writeArray map mp $ Da1_map_ds (avg c_map) (cnt c_map) (ctr c_map) (-1)
mapM_ (\i ->
do
c_ndn <- readArray ndn ((mp * 8) + i)
let td_ptr = ptr c_ndn
if (td_ptr /= udf)
then
do
t_map <- readArray map td_ptr
if ((prt t_map) == mp)
then
undo_region td_ptr map pro pc ndn
else
return ()
else
return ()
)
[0..7]
check_region :: Int -> IOArray Int Da1_map_ds -> IOUArray Int Bool -> IORef Int -> IOUArray Int Int -> IORef Int -> IOArray Int Region_ds -> IO ()
check_region mp map pro pc reg rc ndn
= do
cpc <- readIORef pc
crc <- readIORef rc
(trc, pn) <- check_region_sl1 0 0 (-2) mp pro reg crc ndn
if ((not pn) && (trc <= 2))
then
check_region_sl2 0 mp map pro pc ndn
else
check_region_sl3 0 mp map pro pc reg rc ndn
npc <- readIORef pc
if (cpc > npc)
then
check_region mp map pro pc reg rc ndn
else
return ()
where
check_region_sl1 8 trc _ _ _ _ _ _
= return (trc, False)
check_region_sl1 i trc ptrc mp pro reg crc ndn
= do
c_ndn <- readArray ndn ((mp * 8) + i)
let td_ptr = ptr c_ndn
(ntrc, nptrc, pn)
<- if (td_ptr /= udf)
then
do
td_pro <- readArray pro td_ptr
td_reg <- readArray reg td_ptr
if (td_pro && (td_reg == crc))
then
if ((i == (ptrc + 1)) || ((i == 7) && (ptrc == 0)))
then
return (0, 0, True)
else
return ((trc + 1), i, False)
else
return (trc, ptrc, False)
else
return (trc, ptrc, False)
if (pn)
then
return (0, True)
else
check_region_sl1 (i + 1) ntrc nptrc mp pro reg crc ndn
check_region_sl2 8 _ _ _ _ _
= return ()
check_region_sl2 i mp map pro pc ndn
= do
c_ndn <- readArray ndn ((mp * 8) + i)
let td_ptr = ptr c_ndn
dr
<- if (td_ptr /= udf)
then
do
c_map <- readArray map td_ptr
if ((prt c_map) == mp)
then
do
undo_region td_ptr map pro pc ndn
return False
else
return True
else
return True
if (dr)
then
check_region_sl2 (i + 1) mp map pro pc ndn
else
return ()
check_region_sl3 8 _ _ _ _ _ _ _
= return ()
check_region_sl3 i mp map pro pc reg rc ndn
= do
c_ndn <- readArray ndn ((mp * 8) + i)
let td_ptr = ptr c_ndn
if (td_ptr /= udf)
then
do
c_map <- readArray map td_ptr
if ((prt c_map) == mp)
then
check_region td_ptr map pro pc reg rc ndn
else
return ()
else
return ()
check_region_sl3 (i + 1) mp map pro pc reg rc ndn
do_region :: Int -> Int -> IOArray Int Da1_map_ds -> IOUArray Int Bool -> IOUArray Int Bool -> IORef Int -> IOUArray Int Double -> IOUArray Int Int -> IORef Int -> IOArray Int Region_ds -> Bool -> IO ()
do_region m mp map apt pro pc ref reg rc ndn pts
= do
modifyIORef pc (\x -> x + 1)
writeArray pro mp True
crc <- readIORef rc
writeArray reg mp crc
c_map <- readArray map mp
writeArray map mp $ Da1_map_ds (avg c_map) (cnt c_map) (ctr c_map) m
if (not pts)
then
return ()
else
do
c_ref <- readArray ref mp
trc <- do_region_sl1 0 0 mp map apt pro c_ref ndn
if (trc > 2)
then
do_region_sl2 0 mp map apt pro pc reg ref rc c_ref ndn pts
else
return ()
where
do_region_sl1 8 trc _ _ _ _ _ _
= return trc
do_region_sl1 i trc mp map apt pro c_ref ndn
= do
c_ndn <- readArray ndn ((mp * 8) + i)
let td_ptr = ptr c_ndn
ntrc
<- if (td_ptr /= udf)
then
do
td_pro <- readArray pro td_ptr
td_apt <- readArray apt td_ptr
td_map <- readArray map td_ptr
if ((not td_pro) && td_apt && ((avg td_map) < 5))
then
do
td_ref <- readArray ref td_ptr
let td_dif = abs $ td_ref - c_ref
if (td_dif >= 5)
then
return trc
else
return $ trc + 1
else
return trc
else
return trc
do_region_sl1 (i + 1) ntrc mp map apt pro c_ref ndn
do_region_sl2 8 _ _ _ _ _ _ _ _ _ _ _
= return ()
do_region_sl2 i mp map apt pro pc reg ref rc c_ref ndn pts
= do
c_ndn <- readArray ndn ((mp * 8) + i)
let td_ptr = ptr c_ndn
ntrc
<- if (td_ptr /= udf)
then
do
td_pro <- readArray pro td_ptr
td_apt <- readArray apt td_ptr
td_map <- readArray map td_ptr
if ((not td_pro) && td_apt && ((avg td_map) < 5))
then
do
td_ref <- readArray ref td_ptr
let td_dif = abs $ td_ref - c_ref
if (td_dif >= 5)
then
return ()
else
do_region mp td_ptr map apt pro pc ref reg rc ndn pts
else
return ()
else
return ()
do_region_sl2 (i + 1) mp map apt pro pc reg ref rc c_ref ndn pts
da1_sort :: QTextEdit () -> IOArray Int Da1_map_ds -> [Int] -> Int -> Int -> IO [Int]
da1_sort _ _ [] _ _ = return []
da1_sort _ _ [di] _ _ = return [di]
da1_sort te da1_map da1_ind level rl
= do
sl <- mapM (\i ->
do
cur_map <- readArray da1_map i
case level of
1 -> return $ avg cur_map
2 -> return $ fromIntegral $ cnt cur_map
3 -> return $ fromIntegral $ ctr cur_map
otherwise -> return 0.0
)
da1_ind
let zl = zip da1_ind sl
smp_avg = (sum sl) / (fromIntegral (length sl))
tp = head sl
td = abs $ smp_avg - tp
pivot = da1_pivot tp td smp_avg $ tail sl
less = fst $ unzip $ filter (\i -> (snd i) < pivot) zl
eqls = fst $ unzip $ filter (\i -> (snd i) == pivot) zl
more = fst $ unzip $ filter (\i -> (snd i) > pivot) zl
{-
insertPlainText te $ "sl 0-20, sum sl, len sl: " ++
(show (take 21 sl)) ++ ", " ++
(show (sum sl)) ++ ", " ++
(show (length sl)) ++ "\n"
insertPlainText te $ "smp_avg, tp, td, pivot, len less, len eqls, len more: " ++
(show smp_avg) ++ ", " ++
(show tp) ++ ", " ++
(show td) ++ ", " ++
(show pivot) ++ ", " ++
(show (length less)) ++ "," ++
(show (length eqls)) ++ "," ++
(show (length more)) ++ "\n"
-}
if (level < 3)
then
do
tsl <- da1_sort te da1_map less level (rl + 1)
tse <- da1_sort te da1_map eqls (level + 1) (rl + 1)
tsm <- da1_sort te da1_map more level (rl + 1)
return $ tsl ++ tse ++ tsm
else
do
tsl <- da1_sort te da1_map less 3 (rl + 1)
tsm <- da1_sort te da1_map more 3 (rl + 1)
return $ tsl ++ eqls ++ tsm
da1_pivot :: Double -> Double -> Double -> [Double] -> Double
da1_pivot tp _ _ [] = tp
da1_pivot tp td smp_avg (s:ss)
= let ttd = abs $ smp_avg - s
in
if (ttd < td)
then da1_pivot s ttd smp_avg ss
else da1_pivot tp td smp_avg ss
process_line_V3 :: QTextEdit () -> QTextStream () -> IORef Pdf_glb_ds_V3 -> IOArray Int Pdf_row_ds_V3 -> IOArray Int Pdf_pix_ds_V3 -> Int -> IO ()
process_line_V3 te ins pdf_glb pdf_row pdf_pix w
= do
ae <- atEnd ins ()
if (not ae)
then
do
line <- readLine ins ()
case (line) of
_ | isPrefixOf "Global" line
-> do
let ds1 = drop 7 line
let ls1 = takeWhile (/= ' ') ds1
lf1 <- case readFloat ls1 of
[(f, s)] -> return $ realToFrac f
_ -> return 0.0
insertPlainText te $ "PDF Global: " ++ (show lf1) ++ "\n"
modifyIORef pdf_glb (\_ -> Pdf_glb_ds_V3 True lf1)
_ | isPrefixOf "Row" line
-> do
let ds1 = drop 4 line
let ts1 = takeWhile (/= ' ') ds1
td1 <- case readDec ts1 of
[(d, s)] -> return $ d
_ -> return 0
let ds2 = drop ((length ts1) + 1) ds1
let ls2 = takeWhile (/= ' ') ds2
lf2 <- case readFloat ls2 of
[(f, s)] -> return $ realToFrac f
_ -> return 0.0
let ds3 = drop ((length ls2) + 1) ds2
let ls3 = takeWhile (/= ' ') ds3
lf3 <- case readFloat ls3 of
[(f, s)] -> return $ realToFrac f
_ -> return 0.0
insertPlainText te $ "PDF Row: " ++
(show td1) ++ "," ++
(show lf2) ++ "," ++
(show lf3) ++ "\n"
writeArray pdf_row td1 $ Pdf_row_ds_V3 True lf2 lf3
_ | isPrefixOf "Pixel" line
-> do
let ds1 = drop 6 line
let ts1 = takeWhile (/= ' ') ds1
td1 <- case readDec ts1 of
[(d, s)] -> return $ d
_ -> return 0
let ds2 = drop ((length ts1) + 1) ds1
let ts2 = takeWhile (/= ' ') ds2
td2 <- case readDec ts2 of
[(d, s)] -> return $ d
_ -> return 0
let ds3 = drop ((length ts2) + 1) ds2
let ls3 = takeWhile (/= ' ') ds3
lf3 <- case readFloat ls3 of
[(f, s)] -> return $ realToFrac f
_ -> return 0.0
let ds4 = drop ((length ls3) + 1) ds3
let ls4 = takeWhile (/= ' ') ds4
lf4 <- case readFloat ls4 of
[(f, s)] -> return $ realToFrac f
_ -> return 0.0
insertPlainText te $ "PDF Pix: " ++
(show td1) ++ "," ++
(show td2) ++ "," ++
(show lf3) ++ "," ++
(show lf4) ++ "\n"
writeArray pdf_pix (td1 + (w * td2)) $ Pdf_pix_ds_V3 True lf3 lf4
_
-> return ()
process_line_V3 te ins pdf_glb pdf_row pdf_pix w
else
return ()
zmIn :: GCv -> MdiGC -> IO ()
zmIn gcv cm
= scaleImage gcv 1.25
zmOut :: GCv -> MdiGC -> IO ()
zmOut gcv cm
= scaleImage gcv 0.8
normalSize :: GCv -> MdiGC -> IO ()
normalSize gcv cm
= do
adjustSize (label gcv) ()
modifyIORef (scaleFactor gcv) (\_ -> 1.0)
fitToWindow :: GCv -> MdiGC -> IO ()
fitToWindow gcv cm
= do
ic <- isChecked (a_fw gcv) ()
setWidgetResizable (scrollArea gcv) ic
if (not ic)
then normalSize gcv cm
else return ()
updateActions gcv
return ()
scaleImage :: GCv -> Double -> IO ()
scaleImage gcv factor
= do
let l = label gcv
f = scaleFactor gcv
a = scrollArea gcv
zi = a_zi gcv
zo = a_zo gcv
cf <- readIORef f
let nf = cf * factor
modifyIORef f (\_ -> nf)
p <- pixmap l ()
pw <- qwidth p ()
ph <- qheight p ()
let npw = (round $ (fromIntegral pw) * nf) :: Int
nph = (round $ (fromIntegral ph) * nf) :: Int
ns = size npw nph
resize l ns
h <- horizontalScrollBar a ()
v <- verticalScrollBar a ()
adjustScrollBar h nf
adjustScrollBar v nf
setEnabled zi $ nf < 3.0
setEnabled zo $ nf > 0.333
adjustScrollBar :: QScrollBar () -> Double -> IO ()
adjustScrollBar b f
= do
v <- value b ()
p <- pageStep b ()
let vf = f * (fromIntegral v)
fp = (f - 1) * ((fromIntegral p) / 2)
setValue b $ (round (vf + fp)::Int)
| keera-studios/hsQt | demos/dem_01.hs | bsd-2-clause | 32,391 | 0 | 39 | 12,093 | 11,675 | 5,715 | 5,960 | 835 | 23 |
{-# LANGUAGE GeneralizedNewtypeDeriving, PatternGuards, NoMonoPatBinds #-}
module Evaluator.FreeVars (
inFreeVars,
heapBindingFreeVars,
pureHeapBoundVars, stackBoundVars, stackFrameBoundVars, stackFrameFreeVars,
pureHeapVars, stateFreeVars, stateAllFreeVars, stateLetBounders, stateLambdaBounders, stateInternalBounders, stateUncoveredVars
) where
import Evaluator.Deeds
import Evaluator.Syntax
import Core.FreeVars
import Core.Renaming
import Utilities
import qualified Data.Map as M
import qualified Data.Set as S
inFreeVars :: (a -> FreeVars) -> In a -> FreeVars
inFreeVars thing_fvs (rn, thing) = renameFreeVars rn (thing_fvs thing)
-- | Finds the set of things "referenced" by a 'HeapBinding': this is only used to construct tag-graphs
heapBindingFreeVars :: HeapBinding -> FreeVars
heapBindingFreeVars = maybe S.empty (inFreeVars annedTermFreeVars) . heapBindingTerm
-- | Returns all the variables bound by the heap that we might have to residualise in the splitter
pureHeapBoundVars :: PureHeap -> BoundVars
pureHeapBoundVars = M.keysSet -- I think its harmless to include variables bound by phantoms in this set
-- | Returns all the variables bound by the stack that we might have to residualise in the splitter
stackBoundVars :: Stack -> BoundVars
stackBoundVars = S.unions . map (stackFrameBoundVars . tagee)
stackFrameBoundVars :: StackFrame -> BoundVars
stackFrameBoundVars = fst . stackFrameOpenFreeVars
stackFrameFreeVars :: StackFrame -> FreeVars
stackFrameFreeVars = snd . stackFrameOpenFreeVars
stackFrameOpenFreeVars :: StackFrame -> (BoundVars, FreeVars)
stackFrameOpenFreeVars kf = case kf of
Apply x' -> (S.empty, S.singleton x')
Scrutinise in_alts -> (S.empty, inFreeVars annedAltsFreeVars in_alts)
PrimApply _ in_vs in_es -> (S.empty, S.unions (map (inFreeVars annedValueFreeVars) in_vs) `S.union` S.unions (map (inFreeVars annedTermFreeVars) in_es))
Update x' -> (S.singleton x', S.empty)
-- | Computes the variables bound and free in a state
stateVars :: (Deeds, Heap, Stack, In (Anned a)) -> (HowBound -> BoundVars, FreeVars)
pureHeapVars :: PureHeap -> (HowBound -> BoundVars, FreeVars)
(stateVars, pureHeapVars) = (\(_, Heap h _, k, in_e) -> finish $ pureHeapOpenFreeVars h (stackOpenFreeVars k (inFreeVars annedFreeVars in_e)),
\h -> finish $ pureHeapOpenFreeVars h (S.empty, S.empty))
where
finish ((bvs_internal, bvs_lambda, bvs_let), fvs) = (\how -> case how of InternallyBound -> bvs_internal; LambdaBound -> bvs_lambda; LetBound -> bvs_let, fvs)
pureHeapOpenFreeVars :: PureHeap -> (BoundVars, FreeVars) -> ((BoundVars, BoundVars, BoundVars), FreeVars)
pureHeapOpenFreeVars h (bvs_internal, fvs) = (\f -> M.foldrWithKey f ((bvs_internal, S.empty, S.empty), fvs) h) $ \x' hb ((bvs_internal, bvs_lambda, bvs_let), fvs) -> (case howBound hb of
InternallyBound -> (S.insert x' bvs_internal, bvs_lambda, bvs_let)
LambdaBound -> (bvs_internal, S.insert x' bvs_lambda, bvs_let)
LetBound -> (bvs_internal, bvs_lambda, S.insert x' bvs_let),
fvs `S.union` heapBindingFreeVars hb)
stackOpenFreeVars :: Stack -> FreeVars -> (BoundVars, FreeVars)
stackOpenFreeVars k fvs = (S.unions *** (S.union fvs . S.unions)) . unzip . map (stackFrameOpenFreeVars . tagee) $ k
-- | Returns (an overapproximation of) the free variables that the state would have if it were residualised right now (i.e. variables bound by phantom bindings *are* in the free vars set)
stateFreeVars :: (Deeds, Heap, Stack, In (Anned a)) -> FreeVars
stateFreeVars s = fvs S.\\ bvs InternallyBound
where (bvs, fvs) = stateVars s
stateAllFreeVars :: (Deeds, Heap, Stack, In (Anned a)) -> FreeVars
stateAllFreeVars = snd . stateVars
stateLetBounders :: (Deeds, Heap, Stack, In (Anned a)) -> BoundVars
stateLetBounders = ($ LetBound) . fst . stateVars
stateLambdaBounders :: (Deeds, Heap, Stack, In (Anned a)) -> BoundVars
stateLambdaBounders = ($ LambdaBound) . fst . stateVars
stateInternalBounders :: (Deeds, Heap, Stack, In (Anned a)) -> BoundVars
stateInternalBounders = ($ InternallyBound) . fst . stateVars
stateUncoveredVars :: (Deeds, Heap, Stack, In (Anned a)) -> FreeVars
stateUncoveredVars s = fvs S.\\ bvs InternallyBound S.\\ bvs LetBound S.\\ bvs LambdaBound
where (bvs, fvs) = stateVars s
| batterseapower/chsc | Evaluator/FreeVars.hs | bsd-3-clause | 4,385 | 0 | 15 | 755 | 1,228 | 686 | 542 | 58 | 5 |
markup = <div>
<% getViewDataValue_u "show-me" :: View String %>
</div>
| alsonkemp/turbinado-website | App/Views/TestSession/CreateCounter.hs | bsd-3-clause | 92 | 7 | 5 | 31 | 29 | 16 | 13 | -1 | -1 |
{-# LANGUAGE OverloadedStrings #-}
module System.Taffybar.Widget.Generic.AutoSizeImage where
import qualified Control.Concurrent.MVar as MV
import Control.Monad
import Control.Monad.IO.Class
import Data.Int
import Data.Maybe
import qualified Data.Text as T
import qualified GI.Gdk as Gdk
import GI.GdkPixbuf.Objects.Pixbuf as Gdk
import qualified GI.Gtk as Gtk
import StatusNotifier.Tray (scalePixbufToSize)
import System.Log.Logger
import System.Taffybar.Util
import System.Taffybar.Widget.Util
import Text.Printf
imageLog :: Priority -> String -> IO ()
imageLog = logM "System.Taffybar.Widget.Generic.AutoSizeImage"
borderFunctions :: [Gtk.StyleContext -> [Gtk.StateFlags] -> IO Gtk.Border]
borderFunctions =
[ Gtk.styleContextGetPadding
, Gtk.styleContextGetMargin
, Gtk.styleContextGetBorder
]
data BorderInfo = BorderInfo
{ borderTop :: Int16
, borderBottom :: Int16
, borderLeft :: Int16
, borderRight :: Int16
} deriving (Show, Eq)
borderInfoZero :: BorderInfo
borderInfoZero = BorderInfo 0 0 0 0
borderWidth, borderHeight :: BorderInfo -> Int16
borderWidth borderInfo = borderLeft borderInfo + borderRight borderInfo
borderHeight borderInfo = borderTop borderInfo + borderBottom borderInfo
toBorderInfo :: (MonadIO m) => Gtk.Border -> m BorderInfo
toBorderInfo border =
BorderInfo
<$> Gtk.getBorderTop border
<*> Gtk.getBorderBottom border
<*> Gtk.getBorderLeft border
<*> Gtk.getBorderRight border
addBorderInfo :: BorderInfo -> BorderInfo -> BorderInfo
addBorderInfo
(BorderInfo t1 b1 l1 r1)
(BorderInfo t2 b2 l2 r2)
= BorderInfo (t1 + t2) (b1 + b2) (l1 + l2) (r1 + r2)
-- | Get the total size of the border (the sum of its assigned margin, border
-- and padding values) that will be drawn for a widget as a "BorderInfo" record.
getBorderInfo :: (MonadIO m, Gtk.IsWidget a) => a -> m BorderInfo
getBorderInfo widget = liftIO $ do
stateFlags <- Gtk.widgetGetStateFlags widget
styleContext <- Gtk.widgetGetStyleContext widget
let getBorderInfoFor borderFn =
borderFn styleContext stateFlags >>= toBorderInfo
combineBorderInfo lastSum fn =
addBorderInfo lastSum <$> getBorderInfoFor fn
foldM combineBorderInfo borderInfoZero borderFunctions
-- | Get the actual allocation for a "Gtk.Widget", accounting for the size of
-- its CSS assined margin, border and padding values.
getContentAllocation
:: (MonadIO m, Gtk.IsWidget a)
=> a -> BorderInfo -> m Gdk.Rectangle
getContentAllocation widget borderInfo = do
allocation <- Gtk.widgetGetAllocation widget
currentWidth <- Gdk.getRectangleWidth allocation
currentHeight <- Gdk.getRectangleHeight allocation
currentX <- Gdk.getRectangleX allocation
currentY <- Gdk.getRectangleX allocation
Gdk.setRectangleWidth allocation $ max 1 $
currentWidth - fromIntegral (borderWidth borderInfo)
Gdk.setRectangleHeight allocation $ max 1 $
currentHeight - fromIntegral (borderHeight borderInfo)
Gdk.setRectangleX allocation $
currentX + fromIntegral (borderLeft borderInfo)
Gdk.setRectangleY allocation $
currentY + fromIntegral (borderTop borderInfo)
return allocation
-- | Automatically update the "Gdk.Pixbuf" of a "Gtk.Image" using the provided
-- action whenever the "Gtk.Image" is allocated. Returns an action that forces a
-- refresh of the image through the provided action.
autoSizeImage
:: MonadIO m
=> Gtk.Image
-> (Int32 -> IO (Maybe Gdk.Pixbuf))
-> Gtk.Orientation
-> m (IO ())
autoSizeImage image getPixbuf orientation = liftIO $ do
case orientation of
Gtk.OrientationHorizontal -> Gtk.widgetSetVexpand image True
_ -> Gtk.widgetSetHexpand image True
_ <- widgetSetClassGI image "auto-size-image"
lastAllocation <- MV.newMVar 0
-- XXX: Gtk seems to report information about padding etc inconsistently,
-- which is why we look it up once, at startup. This means that we won't
-- properly react to changes to these values, which could be a pretty nasty
-- gotcha for someone down the line. :(
borderInfo <- getBorderInfo image
let setPixbuf force allocation = do
_width <- Gdk.getRectangleWidth allocation
_height <- Gdk.getRectangleHeight allocation
let width = max 1 $ _width - fromIntegral (borderWidth borderInfo)
height = max 1 $ _height - fromIntegral (borderHeight borderInfo)
size =
case orientation of
Gtk.OrientationHorizontal -> height
_ -> width
previousSize <- MV.readMVar lastAllocation
when (size /= previousSize || force) $ do
MV.modifyMVar_ lastAllocation $ const $ return size
pixbuf <- getPixbuf size
pbWidth <- fromMaybe 0 <$> traverse Gdk.getPixbufWidth pixbuf
pbHeight <- fromMaybe 0 <$> traverse Gdk.getPixbufHeight pixbuf
let pbSize = case orientation of
Gtk.OrientationHorizontal -> pbHeight
_ -> pbWidth
logLevel = if pbSize <= size then DEBUG else WARNING
imageLog logLevel $
printf "Allocating image: size %s, width %s, \
\ height %s, aw: %s, ah: %s, pbw: %s pbh: %s"
(show size)
(show width)
(show height)
(show _width)
(show _height)
(show pbWidth)
(show pbHeight)
Gtk.imageSetFromPixbuf image pixbuf
postGUIASync $ Gtk.widgetQueueResize image
_ <- Gtk.onWidgetSizeAllocate image $ setPixbuf False
return $ Gtk.widgetGetAllocation image >>= setPixbuf True
-- | Make a new "Gtk.Image" and call "autoSizeImage" on it. Automatically scale
-- the "Gdk.Pixbuf" returned from the provided getter to the appropriate size
-- using "scalePixbufToSize".
autoSizeImageNew
:: MonadIO m
=> (Int32 -> IO Gdk.Pixbuf) -> Gtk.Orientation -> m Gtk.Image
autoSizeImageNew getPixBuf orientation = do
image <- Gtk.imageNew
void $ autoSizeImage image
(\size -> Just <$> (getPixBuf size >>= scalePixbufToSize size orientation))
orientation
return image
-- | Make a new "Gtk.MenuItem" that has both a label and an icon.
imageMenuItemNew
:: MonadIO m
=> T.Text -> (Int32 -> IO (Maybe Gdk.Pixbuf)) -> m Gtk.MenuItem
imageMenuItemNew labelText pixbufGetter = do
box <- Gtk.boxNew Gtk.OrientationHorizontal 0
label <- Gtk.labelNew $ Just labelText
image <- Gtk.imageNew
void $ autoSizeImage image pixbufGetter Gtk.OrientationHorizontal
item <- Gtk.menuItemNew
Gtk.containerAdd box image
Gtk.containerAdd box label
Gtk.containerAdd item box
Gtk.widgetSetHalign box Gtk.AlignStart
Gtk.widgetSetHalign image Gtk.AlignStart
Gtk.widgetSetValign box Gtk.AlignFill
return item
| teleshoes/taffybar | src/System/Taffybar/Widget/Generic/AutoSizeImage.hs | bsd-3-clause | 6,873 | 0 | 22 | 1,562 | 1,631 | 800 | 831 | 143 | 5 |
{-# LANGUAGE GeneralizedNewtypeDeriving, CPP, OverloadedStrings #-}
module Haste.Random (Random (..), Seed, next, mkSeed, newSeed) where
import Haste.Prim.JSType
import Data.Int
import Data.Word
import Data.List (unfoldr)
import Control.Monad.IO.Class
import System.IO.Unsafe
#ifdef __HASTE__
import Haste.Foreign
#else
import qualified System.Random as SR
#endif
#ifdef __HASTE__
newtype Seed = Seed JSAny deriving (ToAny, FromAny)
nxt :: Seed -> IO Seed
nxt = ffi "(function(s){return window['md51'](s.join(','));})"
getN :: Seed -> IO Int
getN = ffi "(function(s){return s[0];})"
toSeed :: Int -> IO Seed
toSeed = ffi "(function(n){return window['md51'](n.toString());})"
createSeed :: IO Seed
createSeed = ffi "(function(){return window['md51'](jsRand().toString());})"
#else
newtype Seed = Seed (Int, SR.StdGen)
nxt :: Seed -> IO Seed
nxt (Seed (_, g)) = return . Seed $ SR.next g
getN :: Seed -> IO Int
getN (Seed (n, _)) = return n
toSeed :: Int -> IO Seed
toSeed = return . Seed . SR.next . SR.mkStdGen
createSeed :: IO Seed
createSeed = SR.newStdGen >>= return . Seed . SR.next
#endif
-- | Create a new seed from an integer.
mkSeed :: Int -> Seed
mkSeed = unsafePerformIO . toSeed
-- | Generate a new seed using Javascript's PRNG.
newSeed :: MonadIO m => m Seed
newSeed = liftIO createSeed
-- | Generate the next seed in the sequence.
next :: Seed -> Seed
next = unsafePerformIO . nxt
class Random a where
-- | Generate a pseudo random number between a lower (inclusive) and higher
-- (exclusive) bound.
randomR :: (a, a) -> Seed -> (a, Seed)
randomRs :: (a, a) -> Seed -> [a]
randomRs bounds seed = unfoldr (Just . randomR bounds) seed
instance Random Int where
randomR (low, high) s
| low <= high =
let n = unsafePerformIO $ getN s
in (n `mod` (high-low+1) + low, next s)
| otherwise =
randomR (high, low) s
instance Random Int32 where
randomR (l,h) seed =
case randomR (convert l :: Int, convert h) seed of
(n, s) -> (convert n, s)
instance Random Word where
randomR (l,h) seed =
case randomR (convert l :: Int, convert h) seed of
(n, s) -> (convert n, s)
instance Random Word32 where
randomR (l,h) seed =
case randomR (convert l :: Int, convert h) seed of
(n, s) -> (convert n, s)
instance Random Double where
randomR (low, high) seed =
(f * (high-low) + low, s)
where
(n, s) = randomR (0, 2000000001 :: Int) seed
f = convert n / 2000000000
| santolucito/haste-compiler | libraries/haste-lib/src/Haste/Random.hs | bsd-3-clause | 2,479 | 0 | 14 | 525 | 712 | 392 | 320 | 52 | 1 |
{-# LANGUAGE TemplateHaskell, TypeOperators, MultiParamTypeClasses,
FlexibleInstances, FlexibleContexts, UndecidableInstances, GADTs,
OverlappingInstances, ConstraintKinds #-}
--------------------------------------------------------------------------------
-- |
-- Module : Examples.Multi.Eval
-- Copyright : (c) 2011 Patrick Bahr, Tom Hvitved
-- License : BSD3
-- Maintainer : Tom Hvitved <hvitved@diku.dk>
-- Stability : experimental
-- Portability : non-portable (GHC Extensions)
--
-- Expression Evaluation
--
-- The example illustrates how to use generalised compositional data types
-- to implement a small expression language, with a sub language of values, and
-- an evaluation function mapping expressions to values.
--
--------------------------------------------------------------------------------
module Examples.Multi.Eval where
import Data.Comp.Multi
import Data.Comp.Multi.Derive
import Examples.Multi.Common
-- Term evaluation algebra
class Eval f v where
evalAlg :: Alg f (Term v)
$(derive [liftSum] [''Eval])
-- Lift the evaluation algebra to a catamorphism
eval :: (HFunctor f, Eval f v) => Term f :-> Term v
eval = cata evalAlg
instance (f :<: v) => Eval f v where
evalAlg = inject -- default instance
instance (Value :<: v) => Eval Op v where
evalAlg (Add x y) = iConst $ projC x + projC y
evalAlg (Mult x y) = iConst $ projC x * projC y
evalAlg (Fst x) = fst $ projP x
evalAlg (Snd x) = snd $ projP x
projC :: (Value :<: v) => Term v Int -> Int
projC v = case project v of Just (Const n) -> n
projP :: (Value :<: v) => Term v (s,t) -> (Term v s, Term v t)
projP v = case project v of Just (Pair x y) -> (x,y)
-- Example: evalEx = iConst 2
evalEx :: Term Value Int
evalEx = eval (iFst $ iPair (iConst 2) (iConst 1) :: Term Sig Int)
| spacekitteh/compdata | examples/Examples/Multi/Eval.hs | bsd-3-clause | 1,809 | 0 | 10 | 336 | 473 | 251 | 222 | 25 | 1 |
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE ExistentialQuantification #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE RecordWildCards #-}
module Distribution.Client.GlobalFlags (
GlobalFlags(..)
, defaultGlobalFlags
, RepoContext(..)
, withRepoContext
, withRepoContext'
) where
import Distribution.Client.Types
( Repo(..), RemoteRepo(..) )
import Distribution.Compat.Semigroup
import Distribution.Simple.Setup
( Flag(..), fromFlag, flagToMaybe )
import Distribution.Utils.NubList
( NubList, fromNubList )
import Distribution.Client.HttpUtils
( HttpTransport, configureTransport )
import Distribution.Verbosity
( Verbosity )
import Distribution.Simple.Utils
( info )
import Data.Maybe
( fromMaybe )
import Control.Concurrent
( MVar, newMVar, modifyMVar )
import Control.Exception
( throwIO )
import Control.Monad
( when )
import System.FilePath
( (</>) )
import Network.URI
( uriScheme, uriPath )
import Data.Map
( Map )
import qualified Data.Map as Map
import GHC.Generics ( Generic )
import qualified Hackage.Security.Client as Sec
import qualified Hackage.Security.Util.Path as Sec
import qualified Hackage.Security.Util.Pretty as Sec
import qualified Hackage.Security.Client.Repository.Cache as Sec
import qualified Hackage.Security.Client.Repository.Local as Sec.Local
import qualified Hackage.Security.Client.Repository.Remote as Sec.Remote
import qualified Distribution.Client.Security.HTTP as Sec.HTTP
-- ------------------------------------------------------------
-- * Global flags
-- ------------------------------------------------------------
-- | Flags that apply at the top level, not to any sub-command.
data GlobalFlags = GlobalFlags {
globalVersion :: Flag Bool,
globalNumericVersion :: Flag Bool,
globalConfigFile :: Flag FilePath,
globalSandboxConfigFile :: Flag FilePath,
globalConstraintsFile :: Flag FilePath,
globalRemoteRepos :: NubList RemoteRepo, -- ^ Available Hackage servers.
globalCacheDir :: Flag FilePath,
globalLocalRepos :: NubList FilePath,
globalLogsDir :: Flag FilePath,
globalWorldFile :: Flag FilePath,
globalRequireSandbox :: Flag Bool,
globalIgnoreSandbox :: Flag Bool,
globalIgnoreExpiry :: Flag Bool, -- ^ Ignore security expiry dates
globalHttpTransport :: Flag String
} deriving Generic
defaultGlobalFlags :: GlobalFlags
defaultGlobalFlags = GlobalFlags {
globalVersion = Flag False,
globalNumericVersion = Flag False,
globalConfigFile = mempty,
globalSandboxConfigFile = mempty,
globalConstraintsFile = mempty,
globalRemoteRepos = mempty,
globalCacheDir = mempty,
globalLocalRepos = mempty,
globalLogsDir = mempty,
globalWorldFile = mempty,
globalRequireSandbox = Flag False,
globalIgnoreSandbox = Flag False,
globalIgnoreExpiry = Flag False,
globalHttpTransport = mempty
}
instance Monoid GlobalFlags where
mempty = gmempty
mappend = (<>)
instance Semigroup GlobalFlags where
(<>) = gmappend
-- ------------------------------------------------------------
-- * Repo context
-- ------------------------------------------------------------
-- | Access to repositories
data RepoContext = RepoContext {
-- | All user-specified repositories
repoContextRepos :: [Repo]
-- | Get the HTTP transport
--
-- The transport will be initialized on the first call to this function.
--
-- NOTE: It is important that we don't eagerly initialize the transport.
-- Initializing the transport is not free, and especially in contexts where
-- we don't know a-priori whether or not we need the transport (for instance
-- when using cabal in "nix mode") incurring the overhead of transport
-- initialization on _every_ invocation (eg @cabal build@) is undesirable.
, repoContextGetTransport :: IO HttpTransport
-- | Get the (initialized) secure repo
--
-- (the 'Repo' type itself is stateless and must remain so, because it
-- must be serializable)
, repoContextWithSecureRepo :: forall a.
Repo
-> (forall down. Sec.Repository down -> IO a)
-> IO a
-- | Should we ignore expiry times (when checking security)?
, repoContextIgnoreExpiry :: Bool
}
-- | Wrapper around 'Repository', hiding the type argument
data SecureRepo = forall down. SecureRepo (Sec.Repository down)
withRepoContext :: Verbosity -> GlobalFlags -> (RepoContext -> IO a) -> IO a
withRepoContext verbosity globalFlags =
withRepoContext'
verbosity
(fromNubList (globalRemoteRepos globalFlags))
(fromNubList (globalLocalRepos globalFlags))
(fromFlag (globalCacheDir globalFlags))
(flagToMaybe (globalHttpTransport globalFlags))
(flagToMaybe (globalIgnoreExpiry globalFlags))
withRepoContext' :: Verbosity -> [RemoteRepo] -> [FilePath]
-> FilePath -> Maybe String -> Maybe Bool
-> (RepoContext -> IO a)
-> IO a
withRepoContext' verbosity remoteRepos localRepos
sharedCacheDir httpTransport ignoreExpiry = \callback -> do
transportRef <- newMVar Nothing
let httpLib = Sec.HTTP.transportAdapter
verbosity
(getTransport transportRef)
initSecureRepos verbosity httpLib secureRemoteRepos $ \secureRepos' ->
callback RepoContext {
repoContextRepos = allRemoteRepos
++ map RepoLocal localRepos
, repoContextGetTransport = getTransport transportRef
, repoContextWithSecureRepo = withSecureRepo secureRepos'
, repoContextIgnoreExpiry = fromMaybe False ignoreExpiry
}
where
secureRemoteRepos =
[ (remote, cacheDir) | RepoSecure remote cacheDir <- allRemoteRepos ]
allRemoteRepos =
[ (if isSecure then RepoSecure else RepoRemote) remote cacheDir
| remote <- remoteRepos
, let cacheDir = sharedCacheDir </> remoteRepoName remote
isSecure = remoteRepoSecure remote == Just True
]
getTransport :: MVar (Maybe HttpTransport) -> IO HttpTransport
getTransport transportRef =
modifyMVar transportRef $ \mTransport -> do
transport <- case mTransport of
Just tr -> return tr
Nothing -> configureTransport verbosity httpTransport
return (Just transport, transport)
withSecureRepo :: Map Repo SecureRepo
-> Repo
-> (forall down. Sec.Repository down -> IO a)
-> IO a
withSecureRepo secureRepos repo callback =
case Map.lookup repo secureRepos of
Just (SecureRepo secureRepo) -> callback secureRepo
Nothing -> throwIO $ userError "repoContextWithSecureRepo: unknown repo"
-- | Initialize the provided secure repositories
--
-- Assumed invariant: `remoteRepoSecure` should be set for all these repos.
initSecureRepos :: forall a. Verbosity
-> Sec.HTTP.HttpLib
-> [(RemoteRepo, FilePath)]
-> (Map Repo SecureRepo -> IO a)
-> IO a
initSecureRepos verbosity httpLib repos callback = go Map.empty repos
where
go :: Map Repo SecureRepo -> [(RemoteRepo, FilePath)] -> IO a
go !acc [] = callback acc
go !acc ((r,cacheDir):rs) = do
cachePath <- Sec.makeAbsolute $ Sec.fromFilePath cacheDir
initSecureRepo verbosity httpLib r cachePath $ \r' ->
go (Map.insert (RepoSecure r cacheDir) r' acc) rs
-- | Initialize the given secure repo
--
-- The security library has its own concept of a "local" repository, distinct
-- from @cabal-install@'s; these are secure repositories, but live in the local
-- file system. We use the convention that these repositories are identified by
-- URLs of the form @file:/path/to/local/repo@.
initSecureRepo :: Verbosity
-> Sec.HTTP.HttpLib
-> RemoteRepo -- ^ Secure repo ('remoteRepoSecure' assumed)
-> Sec.Path Sec.Absolute -- ^ Cache dir
-> (SecureRepo -> IO a) -- ^ Callback
-> IO a
initSecureRepo verbosity httpLib RemoteRepo{..} cachePath = \callback -> do
withRepo $ \r -> do
requiresBootstrap <- Sec.requiresBootstrap r
when requiresBootstrap $ Sec.uncheckClientErrors $
Sec.bootstrap r
(map Sec.KeyId remoteRepoRootKeys)
(Sec.KeyThreshold (fromIntegral remoteRepoKeyThreshold))
callback $ SecureRepo r
where
-- Initialize local or remote repo depending on the URI
withRepo :: (forall down. Sec.Repository down -> IO a) -> IO a
withRepo callback | uriScheme remoteRepoURI == "file:" = do
dir <- Sec.makeAbsolute $ Sec.fromFilePath (uriPath remoteRepoURI)
Sec.Local.withRepository dir
cache
Sec.hackageRepoLayout
Sec.hackageIndexLayout
logTUF
callback
withRepo callback =
Sec.Remote.withRepository httpLib
[remoteRepoURI]
Sec.Remote.defaultRepoOpts
cache
Sec.hackageRepoLayout
Sec.hackageIndexLayout
logTUF
callback
cache :: Sec.Cache
cache = Sec.Cache {
cacheRoot = cachePath
, cacheLayout = Sec.cabalCacheLayout
}
-- We display any TUF progress only in verbose mode, including any transient
-- verification errors. If verification fails, then the final exception that
-- is thrown will of course be shown.
logTUF :: Sec.LogMessage -> IO ()
logTUF = info verbosity . Sec.pretty
| headprogrammingczar/cabal | cabal-install/Distribution/Client/GlobalFlags.hs | bsd-3-clause | 10,253 | 0 | 17 | 2,895 | 1,882 | 1,045 | 837 | 192 | 4 |
{-# LANGUAGE Trustworthy #-}
{-# OPTIONS_GHC -#include "HsBase.h" #-}
{-# OPTIONS_GHC -w #-} --tmp
-----------------------------------------------------------------------------
-- |
-- Module : Data.Array.IO.Safe
-- Copyright : (c) The University of Glasgow 2001
-- License : BSD-style (see the file libraries/base/LICENSE)
--
-- Maintainer : libraries@haskell.org
-- Stability : experimental
-- Portability : non-portable (uses Data.Array.MArray)
--
-- Mutable boxed and unboxed arrays in the IO monad.
-- .
-- Safe API only of "Data.Array.IO".
--
-----------------------------------------------------------------------------
module Data.Array.IO.Safe (
-- * @IO@ arrays with boxed elements
IOArray, -- instance of: Eq, Typeable
-- * @IO@ arrays with unboxed elements
IOUArray, -- instance of: Eq, Typeable
-- * Overloaded mutable array interface
module Data.Array.MArray.Safe,
-- * Doing I\/O with @IOUArray@s
hGetArray, -- :: Handle -> IOUArray Int Word8 -> Int -> IO Int
hPutArray, -- :: Handle -> IOUArray Int Word8 -> Int -> IO ()
) where
import Data.Array.IO
import Data.Array.MArray.Safe
| jtojnar/haste-compiler | libraries/ghc-7.8/array/Data/Array/IO/Safe.hs | bsd-3-clause | 1,202 | 0 | 5 | 255 | 71 | 58 | 13 | 11 | 0 |
{-# OPTIONS_GHC -O -fmax-simplifier-iterations=0 #-}
-- Not running the simplifier leads to type-lets persisting longer
module T13708 where
indexOr :: a -> Int -> [a] -> a
indexOr fallback idx xs =
if (idx < length xs)
then xs !! idx
else fallback
| ezyang/ghc | testsuite/tests/simplCore/should_compile/T13708.hs | bsd-3-clause | 257 | 0 | 8 | 52 | 60 | 34 | 26 | 7 | 2 |
{-# OPTIONS_GHC -fno-warn-redundant-constraints #-}
{-# LANGUAGE UndecidableInstances, MultiParamTypeClasses,
FunctionalDependencies, FlexibleInstances #-}
module T3108 where
-- Direct recursion terminates (typechecking-wise)
class C0 x
where
m0 :: x -> ()
m0 = const undefined
instance {-# OVERLAPPING #-} (C0 x, C0 y) => C0 (x,y)
instance {-# OVERLAPPING #-} C0 Bool
instance {-# OVERLAPPABLE #-} C0 (x,Bool) => C0 x
foo :: ()
foo = m0 (1::Int)
-- Indirect recursion does not terminate (typechecking-wise)
class C1 x
where
m1 :: x -> ()
m1 = const undefined
instance {-# OVERLAPPING #-} (C1 x, C1 y) => C1 (x,y)
instance {-# OVERLAPPING #-} C1 Bool
instance {-# OVERLAPPABLE #-} (C2 x y, C1 (y,Bool)) => C1 x
class C2 x y | x -> y
instance C2 Int Int
-- It is this declaration that causes nontermination of typechecking.
bar :: ()
bar = m1 (1::Int)
| urbanslug/ghc | testsuite/tests/typecheck/should_compile/T3108.hs | bsd-3-clause | 882 | 0 | 8 | 174 | 257 | 140 | 117 | -1 | -1 |
{-# LANGUAGE DuplicateRecordFields, TypeFamilies #-}
module OverloadedRecFldsFail10_C (F(..)) where
import OverloadedRecFldsFail10_A
data instance F Char = MkFChar { foo :: Char }
| mettekou/ghc | testsuite/tests/overloadedrecflds/should_fail/OverloadedRecFldsFail10_C.hs | bsd-3-clause | 182 | 0 | 8 | 24 | 37 | 23 | 14 | 4 | 0 |
{-# LANGUAGE TypeFamilies #-}
module ShouldCompile where
import Ind2_help(C(..))
zipT :: (C a, C b) => T a -> T b -> T (a,b)
zipT x y = mkT (unT x, unT y)
| urbanslug/ghc | testsuite/tests/indexed-types/should_compile/ind2.hs | bsd-3-clause | 159 | 0 | 9 | 37 | 85 | 46 | 39 | 5 | 1 |
-- |
-- Module : Palette
-- Description : Colours for Cairo
-- Copyright : (c) Jonatan H Sundqvist, 2015
-- License : MIT
-- Maintainer : Jonatan H Sundqvist
-- Stability : experimental
-- Portability : POSIX (not sure)
--
-- Jonatan H Sundqvist
-- June 11 2015
--
module Palette where
---------------------------------------------------------------------------------------------------
-- We'll need these
---------------------------------------------------------------------------------------------------
import qualified Graphics.Rendering.Cairo as Cairo
---------------------------------------------------------------------------------------------------
-- Types
---------------------------------------------------------------------------------------------------
type Colour = (Double, Double, Double, Double)
---------------------------------------------------------------------------------------------------
-- Colours
---------------------------------------------------------------------------------------------------
black = (0, 0, 0, 1) :: Colour
white = (1, 1, 1, 1) :: Colour
red = (1, 0, 0, 1) :: Colour
green = (0, 1, 0, 1) :: Colour
blue = (0, 0, 1, 1) :: Colour
---------------------------------------------------------------------------------------------------
-- Functions
---------------------------------------------------------------------------------------------------
choose :: (Double, Double, Double, Double) -> Cairo.Render ()
choose (r, g, b, a) = Cairo.setSourceRGBA r g b a | SwiftsNamesake/Copernicus | Palette.hs | mit | 1,536 | 0 | 7 | 178 | 214 | 144 | 70 | 10 | 1 |
module Haskit.Parser
( Definition(..)
, Expr(..)
, UnOp(..)
, BinOp(..)
, Constant(..)
, definition
, global
) where
import Data.Void
import Text.Megaparsec
import Text.Megaparsec.Char
import qualified Text.Megaparsec.Char.Lexer as L
import Text.Megaparsec.Expr
data Definition = Definition
{ definitionName :: String
, definitionParams :: [String]
, definitionBody :: Expr
} deriving (Show)
data Expr
= Unary UnOp Expr
| Binary BinOp Expr Expr
| Constant Constant
| Binding String Expr Expr
| Call String [Expr]
deriving (Show)
data UnOp
= Not
| Neg
deriving (Show)
data BinOp
= Greater
| Less
| Add
| Sub
| Mult
| Div
deriving (Show)
data Constant
= Ident String
| IntConst Integer
| BoolConst Bool
deriving (Show)
type Parser = Parsec Void String
sc :: Parser ()
sc = L.space space1 lineCmnt blockCmnt
where
lineCmnt = L.skipLineComment "//"
blockCmnt = L.skipBlockComment "/*" "*/"
lexeme :: Parser a -> Parser a
lexeme = L.lexeme sc
symbol :: String -> Parser String
symbol = L.symbol sc
parens :: Parser a -> Parser a
parens = between (symbol "(") (symbol ")")
integer :: Parser Integer
integer = lexeme L.decimal
rword :: String -> Parser ()
rword w = lexeme (string w *> notFollowedBy alphaNumChar)
rws :: [String] -- list of reserved words
rws = ["if", "then", "else", "let", "in", "true", "false", "not", "and", "or"]
identifier :: Parser String
identifier = (lexeme . try) (p >>= check)
where
p = (:) <$> letterChar <*> many alphaNumChar
check x =
if x `elem` rws
then fail $ "keyword " ++ show x ++ " cannot be an identifier"
else return x
aExpr :: Parser Expr
aExpr = makeExprParser aTerm aOperators
bExpr :: Parser Expr
bExpr = makeExprParser bTerm bOperators
expr :: Parser Expr
expr = aExpr <|> bExpr <|> binding
aOperators :: [[Operator Parser Expr]]
aOperators =
[ [Prefix (Unary Neg <$ symbol "-")]
, [InfixL (Binary Mult <$ symbol "*"), InfixL (Binary Div <$ symbol "/")]
, [InfixL (Binary Add <$ symbol "+"), InfixL (Binary Sub <$ symbol "-")]
]
bOperators :: [[Operator Parser Expr]]
bOperators =
[ [Prefix (Unary Not <$ rword "not")] ]
aTerm :: Parser Expr
aTerm =
parens aExpr <|>
(identifier >>= (\ident -> call ident <|> (pure . Constant $ Ident ident))) <|>
(Constant . IntConst) <$> integer
bTerm :: Parser Expr
bTerm =
parens bExpr <|>
((Constant . BoolConst) True <$ rword "true") <|>
((Constant . BoolConst) False <$ rword "false") <|>
rExpr
rExpr :: Parser Expr
rExpr = do
a1 <- aExpr
op <- relation
a2 <- aExpr
return (Binary op a1 a2)
relation :: Parser BinOp
relation = (symbol ">" *> pure Greater) <|> (symbol "<" *> pure Less)
binding :: Parser Expr
binding = do
rword "let"
sym <- identifier
symbol "="
value <- expr
rword "in"
body <- expr
return $ Binding sym value body
call :: String -> Parser Expr
call sym = do
symbol "("
args <- expr `sepBy` char ','
symbol ")"
return $ Call sym args
definition :: Parser Definition
definition = do
sym <- identifier
params <- many identifier
symbol "="
body <- expr
return $ Definition sym params body
global :: Parser [Definition]
global = many definition
| jac3km4/haskit | src/Haskit/Parser.hs | mit | 3,278 | 0 | 15 | 765 | 1,233 | 646 | 587 | 123 | 2 |
{-# OPTIONS_GHC -Wall #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE Strict #-}
module Main (main) where
import System.Random
import Data.Foldable (toList, foldl')
import qualified Data.Vector as V
data Nat :: * where
Z :: Nat
S :: Nat -> Nat
data SNat :: Nat -> * where
SZ :: SNat 'Z
SS :: SNat n -> SNat ('S n)
instance Show (SNat n) where
show = ("SNat " ++) . show . snatToInt
snatToInt :: SNat n -> Int
snatToInt = snatToInt' 0
where
snatToInt' :: Int -> SNat n -> Int
snatToInt' acc SZ = acc
snatToInt' acc (SS sn) = snatToInt' (acc+1) sn
infixr 5 :-
data Vector' :: Nat -> * -> * where
Nil :: Vector' 'Z a
(:-) :: a -> Vector' n a -> Vector' ('S n) a
instance Foldable (Vector' n) where
foldMap _ Nil = mempty
foldMap f (x :- xs) = f x `mappend` foldMap f xs
data Vector :: Nat -> * where
Vector :: SNat n -> V.Vector Double -> Vector n
instance Show (Vector n) where
show (Vector _ a) = "Vector " ++ show (V.length a) ++ " " ++ show a
vector :: SNat ('S n) -> Vector' ('S n) Double -> Vector ('S n)
vector sn = Vector sn . foldl' V.snoc V.empty . toList
zeros :: SNat ('S n) -> Vector ('S n)
zeros sn = Vector sn $ V.replicate (snatToInt sn) 0
type NFeatures = ('S ('S 'Z))
sNFeatures :: SNat NFeatures
sNFeatures = SS (SS SZ)
type Model = Vector ('S NFeatures)
type Target = Double
type Features = Vector NFeatures
type Hypothesis = Model -> Features -> Target
-- General purpose example
data Example = Example
Features
Target deriving Show
{-# INLINE nextModel #-}
nextModel ::
Double -> --lambda
Double -> --learningRate
Double -> --difference
Model -> --model
Features ->
Model --the resulting model
nextModel lambda learningRate difference (Vector sn modelArr) (Vector _ featureArr) = Vector sn $
V.update
(V.zipWith (-) modelArr $ (* learningRate) <$> V.zipWith (+) (fmap (* difference) featureArr) (fmap (* lambda) modelArr))
(V.singleton (0, (modelArr V.! 0) - learningRate * difference))
stochaticGradientDescentUpdate :: Hypothesis -> Double -> Double -> Example -> Model -> (Target, Model)
stochaticGradientDescentUpdate hypothesis lambda learningRate (Example features target) model =
let
cost = negate (log approximation*target + log(1 - approximation)*(1-target))
nxtModel = nextModel lambda learningRate difference model features
in ((,) $! cost) $! nxtModel
where
difference :: Target
difference = approximation - target
approximation :: Target
approximation = hypothesis model features
{-- Octave code
h = sigmoid(theta'*X');
reg_theta = [0; theta(2:end)];
first_cost_term = (log(h)*y);
second_const_term = log(1 - h) * (1 - y);
third_cost_term = (lambda/2)*sum(reg_theta.^2);
J = ((-1)/m)*( first_cost_term + second_const_term - third_cost_term);
grad = (1/m)*( ( (h - y') * X) + (lambda) *reg_theta');
-}
-- Test main
main :: IO ()
main =
print $ foldr folder (1000,zeroModel) $ take 1000000 d
where
folder ex (_, model) =
let
(err, nxtModel) = stochaticGradientDescentUpdate sigmoidHypothesis 0.01 0.1 ex model
in (err, nxtModel)
d :: [Example]
d = example <$> randomRs (0,1) (mkStdGen 332) <*> randomRs (0,1) (mkStdGen 2132)
example :: Double -> Double -> Example
example x y =
Example
(vector
sNFeatures -- SS because of the 1
(x :- y :- Nil))
(if y > 0.5 then 1 else 0)
zeroModel = zeros (SS sNFeatures)
sigmoidHypothesis :: Model -> Features -> Target
sigmoidHypothesis (Vector _ modelArr) (Vector _ featuresArr) =
1 / ( 1 + exp (negate $ V.foldl' (+) 0 $ V.zipWith (*) modelArr (V.cons 1 featuresArr)))
-- vim: expandtab
| argent0/haskell-ml-benchmark | src/MainVector.hs | mit | 3,810 | 0 | 15 | 851 | 1,319 | 701 | 618 | 91 | 2 |
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE PolyKinds #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fwarn-incomplete-patterns #-}
module HW08 where
import Prelude (Show(..), Eq(..), ($), (.), flip)
-- Propositional Logic --------------------------------
-- False, the uninhabited type
data False
-- Logical Not
type Not p = p -> False
-- Logical Disjunction
data p \/ q = Left p
| Right q
-- Logical Conjunction
data p /\ q = Conj p q
-- If and only if
type p <-> q = (p -> q) /\ (q -> p)
-- Admit is used to assume an axiom without proof
admit :: p
admit = admit
-- There is no way to prove this axiom in constructive logic, therefore we
-- leave it admitted
excluded_middle :: p \/ Not p
excluded_middle = admit
absurd :: False -> p
absurd false = admit
double_negation :: p <-> Not (Not p)
double_negation = Conj (\p not_p -> not_p p) admit
modus_ponens :: (p -> q) -> p -> q
modus_ponens = ($)
modus_tollens :: (p -> q) -> Not q -> Not p
modus_tollens = flip (.)
material_implication :: (p -> q) <-> (Not p \/ q)
-- The proof has two parts, the forward direction (->) and
-- the backwards direction (<-)
material_implication = Conj dir1 dir2
where
-- Case 1: (P -> Q) -> (~P \/ Q)
dir1 p_imp_q =
-- There are 2 cases, P and ~P
case excluded_middle of
-- SCase 1: P, then Q since P -> Q
Left p -> Right $ p_imp_q p
-- SCase 2: ~P, then ~P
Right not_p -> Left not_p
-- Case 2: (~P \/ Q) -> (P -> Q)
-- SCase 1: ~P -> (P -> Q)
dir2 (Left not_p) p =
-- This is a contradiction since we have both
-- P and ~P
absurd $ not_p p
-- SCase 2: Q -> (P -> Q)
dir2 (Right q) _ =
-- q is a witness for the proposition Q,
-- therefore we can just return it
q
-- Exercise 1 -----------------------------------------
disjunctive_syllogism :: (p \/ q) -> Not p -> q
disjunctive_syllogism p_or_q not_p = case p_or_q of
Left p -> absurd $ not_p p
Right q -> q
-- Exercise 2 -----------------------------------------
composition :: (p -> q) \/ (p -> r) -> p -> q \/ r
composition case1_or_case2 p = case case1_or_case2 of
Left p_imp_q -> Left $ p_imp_q p
Right p_imp_r -> Right $ p_imp_r p
-- Exercise 3 -----------------------------------------
transposition :: (p -> q) <-> (Not q -> Not p)
transposition = Conj modus_tollens dir2
where dir2 not_q_imp_not_p p = let Conj p_imp_not_not_p _ = double_negation
not_not_p = p_imp_not_not_p p
not_not_q = modus_tollens not_q_imp_not_p not_not_p
Conj _ not_not_q_imp_q = double_negation
in not_not_q_imp_q not_not_q
-- Exercise 4 -----------------------------------------
de_morgan :: Not (p \/ q) <-> (Not p /\ Not q)
de_morgan = Conj dir1 dir2
where dir1 not_disj =
case excluded_middle of
Left p -> absurd $ not_disj (Left p)
Right not_p -> case excluded_middle of
Left q -> absurd $ not_disj (Right q)
Right not_q -> Conj not_p not_q
dir2 (Conj not_p not_q) p_or_q = not_q $ disjunctive_syllogism p_or_q not_p
-- Natural Numbers ------------------------------------
data Nat = O | S Nat
deriving (Show, Eq)
type family (n :: Nat) + (m :: Nat) :: Nat
type instance O + m = m
type instance (S n) + m = S (n + m)
infixl 6 +
data Forall n where
Zero :: Forall O
Succ :: Forall n -> Forall (S n)
data (n :: Nat) == (m :: Nat) where
Refl :: n == n
infix 4 ==
type (n :: Nat) /= (m :: Nat) = Not (n == m)
infix 4 /=
data n < m where
LT_Base :: O < S n
LT_Rec :: n < m -> S n < S m
type n > m = m < n
type n <= m = (n < m) \/ (n == m)
type n >= m = m <= n
-- Weakening Lemma
neq_weaken :: S n /= S m -> n /= m
neq_weaken h_neq Refl = h_neq Refl
{- ********************************************************
* Theorem: Not Equal Implies Greater Than or Less Then *
******************************************************** -}
neq_gt_lt :: Forall n -> Forall m ->
n /= m -> (n < m) \/ (n > m)
-- The proof is by induction on n and m
-- Base Case 1: both n and m are 0. This is impossible since the hypothesis h
-- states that n /= m
neq_gt_lt Zero Zero h = absurd $ h Refl
-- Base Case 2: n == 0 and m > 0. Here we choose the left case, n < m
neq_gt_lt Zero (Succ m) _ = Left LT_Base
-- Base Case 3: n > 0 and m == 0. Here we choose the right case, n > m
neq_gt_lt (Succ n) Zero _ = Right LT_Base
-- Inductive Step: both n and m are greater than 0
neq_gt_lt (Succ n) (Succ m) h_neq =
-- We generate an induction hypothesis by invoking a recursive call on n,
-- m, and the weakening hypothesis
case neq_gt_lt n m (neq_weaken h_neq) of
-- Case 1: n < m with witness w. This means that S n < S m
Left w -> Left $ LT_Rec w
-- Case 2: n > m with witness w. This means that S n > S m
Right w -> Right $ LT_Rec w
-- Exercise 5 -----------------------------------------
o_plus_n :: O + n == n
o_plus_n = Refl
n_plus_0 :: Forall n -> n + O == n
-- Base Case:
n_plus_0 Zero = Refl {- :: O + O == O -}
-- Inductive Step:
n_plus_0 (Succ n) = case n_plus_0 n of
Refl {- :: n + O == n -} ->
Refl {- :: S n + O == S n -}
add_zero :: Forall n -> O + n == n + O
add_zero Zero = Refl
add_zero (Succ n) = case add_zero n of
Refl -> Refl
-- Exercise 6 -----------------------------------------
n_lt_sn :: Forall n -> n < S n
n_lt_sn Zero = LT_Base
n_lt_sn (Succ n) = LT_Rec $ n_lt_sn n
-- Exercise 7 -----------------------------------------
data Even :: Nat -> * where
E_Zero :: Even O
E_Rec :: Even n -> Even (S (S n))
data Odd :: Nat -> * where
O_One :: Odd (S O)
O_Rec :: Odd n -> Odd (S (S n))
even_plus_one :: Even n -> Odd (S n)
-- Base Case: The successor of zero is odd
even_plus_one E_Zero = O_One
-- Inductive Step: if S (S n) is even then S (S (S n)) is odd
even_plus_one (E_Rec n) = O_Rec $ even_plus_one n
odd_plus_one :: Odd n -> Even (S n)
odd_plus_one O_One = E_Rec E_Zero
odd_plus_one (O_Rec n) = E_Rec $ odd_plus_one n
-- Exercise 8 -----------------------------------------
succ_sum :: Forall n -> Forall m ->
S n + S m == S (S (n + m))
succ_sum Zero m = Refl
succ_sum (Succ n) m = case succ_sum n m of
Refl -> Refl
double_even :: Forall n -> Even (n + n)
double_even Zero = E_Zero
double_even (Succ n) = case succ_sum n n of
Refl -> E_Rec $ double_even n
| mrordinaire/upenn-haskell | src/HW08.hs | mit | 7,052 | 4 | 16 | 2,215 | 1,868 | 989 | 879 | -1 | -1 |
-- Extended from aeson-serialize by Kevin Holt
{-|
- This module defines a newtype wrapper for instances of FromJSON and ToJSON which
- is an instance of Serialize. The serialized form is a UTF-8 encoded bytestring
- of the JSON representation of the datatype.
|-}
module Data.Serialize.Aeson where
import Data.Aeson
import Data.Serialize hiding (decode, encode)
-- | put function for all serialization of a json type
putToJSON :: (ToJSON a) => Putter a
putToJSON = put . encode
-- | get function for all deserialization of a json type
getFromJSON :: (FromJSON a) => Get a
getFromJSON = get >>= (either fail return) . eitherDecode
-- | Newtype wrapper for (From,To)JSON instances which has a Serializable
-- instance
newtype JSONToSerialize a = JSONToSerialize a deriving (Read, Show, Ord, Eq)
instance (FromJSON a, ToJSON a) => Serialize (JSONToSerialize a) where
put (JSONToSerialize x) = putToJSON x
get = fmap JSONToSerialize getFromJSON
| plow-technologies/cereal-aeson | src/Data/Serialize/Aeson.hs | mit | 976 | 0 | 8 | 184 | 180 | 101 | 79 | 11 | 1 |
-- Playfield
module Playfield
( Well
, Cell(..)
, emptyWell
, numberRows
, numberCells
, coordCells
, renderPiece
, pieceCollides
, clearAndCountFilledRows
, cellColor
) where
import Piece
import Data.List
import Graphics.Gloss
-- A cell is a rectangle in the playfield - it can either be full or empty
data Cell = Empty | FilledWith Color deriving (Show, Eq)
-- Returns the color of the cell, or black if empty
cellColor :: Cell -> Color
cellColor (FilledWith col) = col
cellColor _ = black
-- Row of cells
data Row = RowOfCells [Cell] deriving (Show)
-- Creates an empty Row
emptyRow = RowOfCells (replicate 10 Empty)
-- Function stubs that tell if a row is empty or full
isRowEmpty :: Row -> Bool
isRowEmpty r = undefined
isRowFull :: Row -> Bool
isRowFull r = undefined
-- For compatibility with the Piece, our Well consists of rows of height 2.
-- The rows in turn consist of cells of width 2.
-- There are 22 rows of 10 cells each. The top 2 rows are "invisible".
-- For simplicity, we'll put the origin (0,0) at the center of the invisible rows.
-- This way, when we render a piece at (0,0), it will be completely hidden.
data Well = WellOfRows [Row] deriving (Show)
-- Creates an empty Well
emptyWell = WellOfRows (replicate 22 emptyRow)
-- Converts Well to Ascii-art String.
wellToAA :: Well -> String
wellToAA (WellOfRows rs) = intercalate "\n" (map rowToString rs)
where rowToString (RowOfCells cs) = map cellToChar cs
where cellToChar cell | cell == Empty = '.'
| otherwise = '*'
-- Small refactoring: These might come in handy later.
numberRows :: Well -> [(Int, Row)]
numberRows (WellOfRows rs) = zip [1,-1..(-41)] rs
numberCells :: Row -> [(Int, Cell)]
numberCells (RowOfCells cs) = zip [-9,-7..9] cs
-- This one will create a 3-tuple of the cell and its coordinates (x,y,cell)
-- It's going to be more convenient for the rendering module to just use these 3-tuples instead of manually unfolding the well
coordCells :: Well -> [(Int, Int, Cell)]
coordCells w = concat (map extractCells (numberRows w))
where
extractCells (y, cs) = map extractCell (numberCells cs)
where extractCell (x, c) = (x, y, c)
-- Renders a piece in the Well
renderPiece :: Piece -> (Int, Int) -> Well -> Well
renderPiece piece (pX, pY) well
| odd pX || odd pY = error "Odd piece coordinates used"
| otherwise = WellOfRows (map renderRow (numberRows well))
where renderRow (y, row) = RowOfCells (map renderCell (numberCells row))
where renderCell (x, c)
| c /= Empty = c
| pieceContains (x-pX, y-pY) piece = FilledWith (pieceColor piece)
| otherwise = Empty
-- Because I'm extremely lazy, I'm going to implement collision detection based on the renderPiece function I have already
-- First, I'll render a piece in an enpty well
-- Then, all that is needed is a function that compares two wells cell by cell
pieceCollides :: Piece -> (Int, Int) -> Well -> Bool
pieceCollides piece piecePos well = wellsCollide rendered well
where
rendered = renderPiece piece piecePos emptyWell
wellsCollide (WellOfRows rs1) (WellOfRows rs2) = or (map rowsCollide (zip rs1 rs2))
rowsCollide (RowOfCells cs1, RowOfCells cs2) = or (map cellsCollide (zip cs1 cs2))
cellsCollide (a, b) = (a /= Empty) && (b /= Empty)
-- Clears a well of its filled rows and returns the filled row count
clearAndCountFilledRows :: Well -> (Well, Int)
clearAndCountFilledRows (WellOfRows rs) = (well', count)
where
well' = WellOfRows (asManyClear ++ remaining)
remaining = filter notFull rs
count :: Int
count = (length rs) - (length remaining)
asManyClear :: [Row]
asManyClear = replicate count emptyRow
notFull (RowOfCells cs) = not (and (map (\c -> c /= Empty) cs))
| mgeorgoulopoulos/TetrisHaskellWeekend | Playfield.hs | mit | 4,221 | 0 | 14 | 1,222 | 1,023 | 551 | 472 | 63 | 1 |
-- |
-- Module: BigE.Model.IndexAllocator
-- Copyright: (c) 2017 Patrik Sandahl
-- Licence: MIT
-- Maintainer: Patrik Sandahl <patrik.sandahl@gmail.com>
-- Stability: experimental
-- Portability: portable
module BigE.Model.IndexAllocator
( IndexAllocator
, AllocReply (..)
, init
, alloc
) where
import BigE.Model.Parser (Point)
import Data.HashMap.Strict (HashMap)
import qualified Data.HashMap.Strict as HashMap
import Graphics.GL (GLuint)
import Prelude hiding (init)
-- | Allocate indices to vertex points.
data IndexAllocator = IndexAllocator
{ hashMap :: !(HashMap Point GLuint)
, nextIndex :: !GLuint
} deriving Show
-- | Allocation reply.
data AllocReply
= Index !GLuint !IndexAllocator
| AlreadyIndexed !GLuint
deriving Show
-- | Get a new allocator.
init :: IndexAllocator
init =
IndexAllocator
{ hashMap = HashMap.empty
, nextIndex = 0
}
-- | Get an index for the point.
alloc :: Point -> IndexAllocator -> AllocReply
alloc point allocator =
case HashMap.lookup point (hashMap allocator) of
Just index -> AlreadyIndexed index
Nothing ->
let newHashMap = HashMap.insert point
(nextIndex allocator)
(hashMap allocator)
newAllocator = allocator { hashMap = newHashMap
, nextIndex = nextIndex allocator + 1
}
in Index (nextIndex allocator) newAllocator
| psandahl/big-engine | src/BigE/Model/IndexAllocator.hs | mit | 1,631 | 0 | 15 | 548 | 295 | 170 | 125 | 44 | 2 |
{-# LANGUAGE TypeOperators #-}
module Terrain where
import Numeric.Noise.Perlin
import System.Random (randomRs,mkStdGen)
import qualified Data.Array.Repa as R
import qualified Data.Vector.Unboxed as R (Unbox)
type Seed = Int
rangeMap :: (Ord a) => b -> [(a,b)] -> a -> b
rangeMap def rs x = case dropWhile (\(a,_) -> x > a) rs of
(_,b):_ -> b
_ -> def
randomPerlin
:: (R.Unbox b)
=> Seed -- Perlin Seed
-> Seed -- Random Seed
-> (Double,Double) -- Random Range
-> (Int,Int) -- Matrix Width & Height
-> (Double -> b)
-> R.Array R.U R.DIM2 b
randomPerlin pSeed rSeed range (w,h) f = R.fromListUnboxed shape zips
where
perl = perlin pSeed 32 (1/128) (1/2)
shape = R.ix2 w h
rnds = randomRs range $ mkStdGen rSeed
zips = zipWith (\(x,y) rnd -> f $ rnd + noiseValue perl (fromIntegral x, fromIntegral y, 0))
[(x,y) | x <- [0..w-1], y <- [0..h-1]]
rnds
perlinMap :: (R.Unbox a)
=> Seed
-> (Int,Int)
-> (Double -> a)
-> IO (R.Array R.U R.DIM2 (Int,Int,a))
perlinMap seed (w,h) f = R.computeUnboxedP
$ R.fromFunction (R.ix2 w h) (\sh@(R.Z R.:. x R.:. y) -> (x,y, f $ perl (fromIntegral x, fromIntegral y, 0)))
where
perl xyz = noiseValue (perlin seed 16 (1/128) (1/2)) xyz | RTS2013/RTS | server/src/Terrain.hs | mit | 1,334 | 0 | 13 | 374 | 616 | 342 | 274 | 34 | 2 |
-- file ch03/ex07.hs
-- Define a function that joins a list of lists together using a separator value
-- intersperse :: (Show t) => Char -> [t] -> Char
intersperse :: Char -> [[Char]] -> [Char]
intersperse _ [] = ""
intersperse _ (x:[]) = x
intersperse delimiter (x:xs) = x ++ [delimiter] ++ intersperse delimiter xs
| imrehg/rwhaskell | ch03/ex07.hs | mit | 317 | 0 | 8 | 57 | 90 | 49 | 41 | 4 | 1 |
-- | Helpers for dealing with HTTP requests.
module Strive.Internal.HTTP
( delete
, get
, post
, put
, buildRequest
, performRequest
, handleResponse
, decodeValue
) where
import Data.Aeson (FromJSON, eitherDecode)
import Data.ByteString.Char8 (unpack)
import Data.ByteString.Lazy (ByteString)
import Network.HTTP.Conduit (Request, Response, checkStatus, method, parseUrl,
responseBody)
import Network.HTTP.Types (Method, Query, QueryLike, methodDelete, methodGet,
methodPost, methodPut, renderQuery, toQuery)
import Strive.Aliases (Result)
import Strive.Client (Client (client_accessToken, client_requester))
-- | Perform an HTTP DELETE request.
delete :: (QueryLike q, FromJSON j) => Client -> String -> q -> IO (Result j)
delete = http methodDelete
-- | Perform an HTTP GET request.
get :: (QueryLike q, FromJSON j) => Client -> String -> q -> IO (Result j)
get = http methodGet
-- | Perform an HTTP POST request.
post :: (QueryLike q, FromJSON j) => Client -> String -> q -> IO (Result j)
post = http methodPost
-- | Perform an HTTP PUT request.
put :: (QueryLike q, FromJSON j) => Client -> String -> q -> IO (Result j)
put = http methodPut
-- | Perform an HTTP request.
http :: (QueryLike q, FromJSON j) => Method -> Client -> String -> q -> IO (Result j)
http httpMethod client resource query = do
request <- buildRequest httpMethod client resource query
response <- performRequest client request
return (handleResponse response)
-- | Build a request.
buildRequest :: QueryLike q => Method -> Client -> String -> q -> IO Request
buildRequest httpMethod client resource query = do
request <- parseUrl (buildUrl client resource query)
return request
{ checkStatus = \ _ _ _ -> Nothing
, method = httpMethod
}
-- | Build a URL.
buildUrl :: QueryLike q => Client -> String -> q -> String
buildUrl client resource query = concat
[ "https://www.strava.com/"
, resource
, unpack (renderQuery True (buildQuery client ++ toQuery query))
]
-- | Build a query.
buildQuery :: Client -> Query
buildQuery client = toQuery
[ ("access_token", client_accessToken client)
]
-- | Actually perform an HTTP request.
performRequest :: Client -> Request -> IO (Response ByteString)
performRequest client request = (client_requester client) request
-- | Handle decoding a potentially failed response.
handleResponse :: FromJSON j => Response ByteString -> Result j
handleResponse response = case decodeValue response of
Left message -> Left (response, message)
Right value -> Right value
-- | Decode a response body as JSON.
decodeValue :: FromJSON j => Response ByteString -> Either String j
decodeValue response = eitherDecode (responseBody response)
| bitemyapp/strive | library/Strive/Internal/HTTP.hs | mit | 2,760 | 0 | 12 | 533 | 809 | 430 | 379 | 53 | 2 |
module Physics.Hurl.Geometry
(
-- * Shape
Shape (..),
validShape,
area,
transformShape,
translateShape,
rectangle,
-- * Position
Position(..),
positionIso,
moveShape,
module Physics.Hurl.Geometry.Isometry,
-- * Linear Re-exports
V2 (..),
) where
import Control.Applicative
import Data.Monoid
import Data.Traversable ( traverse )
import Linear hiding ( rotate )
import Control.Lens ( over )
import Physics.Hurl.Geometry.Isometry
data Shape
= Circle Double (V2 Double)
-- ^ A circle with positive radius and position
| Segment Double (V2 Double) (V2 Double)
-- ^ A line segment with positive thickness and two positions
| Poly [V2 Double]
-- ^ A convex polygon with clockwise winding
deriving (Show, Eq, Ord)
validShape :: Shape -> Bool
validShape s = case s of
Circle r _ -> r > 0
Segment t a b -> t > 0 && a /= b
Poly ps -> length ps > 2 -- TODO verify clockwise and convex
area :: Shape -> Double
area s = case s of
Circle r _ -> r * r
Segment t a b -> t * distance a b
Poly ps -> polygonAreaCCW (reverse ps)
-- | @polygonArea ps@ is the area of the convex polygon given by the
-- counter-clockwise points @ps@.
polygonAreaCCW :: [V2 Double] -> Double
polygonAreaCCW ps = 0.5 * f xs ys - f ys xs
where
(xs, ys) = unzip $ map (\(V2 x y) -> (x,y)) ps
f as bs = sum $ zipWith (*) as $ drop 1 bs ++ bs
transformShape :: Isometry Double -> Shape -> Shape
transformShape i = over points $ transform i
translateShape :: V2 Double -> Shape -> Shape
translateShape = transformShape . translate
rotateShape :: Double -> Shape -> Shape
rotateShape = transformShape . rotate
reflectShapeY :: Shape -> Shape
reflectShapeY = transformShape reflectY
-- | @points :: Traversal' Shape Point@
points :: (Applicative f) => (V2 Double -> f (V2 Double)) -> Shape -> f Shape
points f s = case s of
Circle r p -> Circle r <$> f p
Segment th p q -> Segment th <$> f p <*> f q
Poly ps -> Poly <$> traverse f ps
-- | @rectangle w h@ is a centered rectangle with width @w@ and height @h@.
rectangle :: Double -> Double -> Shape
rectangle w h = Poly [V2 (-x) (-y), V2 (-x) y, V2 x y, V2 x (-y)]
where x = w/2
y = h/2
{-
translate :: Position -> Shape -> Shape
translate v = over points (translatePoint v)
translatePoint :: Position -> Point -> Point
translatePoint v (V2 x y) =
let V4 x' y' 0 0 = posMatrix v !* V4 x y 0 0
in V2 x' y'
-}
------------------------------------------------------------------------------
-- TODO improve the efficiency of these operations
------------------------------------------------------------------------------
-- | A 2D translation and rotation.
data Position = Pos
{ trans :: !(V2 Double)
, angle :: !Double
} deriving (Show, Eq, Ord)
positionIso :: Position -> Isometry Double
positionIso (Pos t a) = translate t <> rotate a
moveShape :: Position -> Shape -> Shape
moveShape = transformShape . positionIso
{-
instance Monoid Position where
mempty = Pos 0 0
a `mappend` b = unsafeFromMatrix $ posMatrix a !*! posMatrix b
mconcat ps = case ps of
[] -> mempty
[p] -> p
_ -> unsafeFromMatrix $ foldl1' (!*!) . map posMatrix $ ps
unsafeFromMatrix :: M44 Double -> Position
unsafeFromMatrix (V4 (V4 _ _ _ x) (V4 c d _ y) _ _) = Pos (V2 x y) (atan (c/d))
posMatrix :: Position -> M44 Double
posMatrix (Pos (V2 x y) r) = mkTransformation quat (V3 x y 0)
where
quat = axisAngle (V3 0 0 1) r
-}
| cdxr/haskell-hurl | Physics/Hurl/Geometry.hs | mit | 3,595 | 0 | 12 | 907 | 887 | 472 | 415 | 67 | 3 |
module Main where
import Language.Egison.Core
import Language.Egison.Types
import Control.Monad.Error
import System.Environment
main :: IO ()
main = do
args <- getArgs
env <- primitiveBindings
ret1 <- runIOThrows $ liftM concat $ mapM (evalTopExpr env) topExprs
case ret1 of
Just errMsg -> putStrLn errMsg
_ -> do
ret2 <- runIOThrows $ evalTopExpr env $ Execute args
case ret2 of
Just errMsg -> putStrLn errMsg
_ -> return ()
| aretoky/egison2 | etc/template.hs | mit | 465 | 0 | 16 | 106 | 161 | 78 | 83 | 17 | 3 |
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Test.Framework
import Test.Framework.Providers.HUnit
import Test.HUnit
import Test.HUnit.Base (Test(TestLabel))
import qualified Data.HashMap as Hash
import Data.Maybe (fromMaybe)
import Utils.File
import Utils.Text
import Madl.Network as Madl
import Madl.Cycles
import Madl.Base (isConsistent)
import qualified Examples
main :: IO()
main = defaultMain =<< tests
tests :: IO [Test.Framework.Test]
tests = (return . hUnitTestToTests . TestList) =<< fmap concat (sequence alltests) where
alltests :: [IO [Test.HUnit.Base.Test]]
alltests = map getTests testcases
pathToTests :: FilePath
pathToTests = "examples/"
testcases :: [(FilePath, Bool)]
testcases =
[
--("internship/gen0_no_reorder.madl", True)
--, ("internship/gen0_reorder.madl", True)
--, ("internship/gen0_reorder_cc.madl", True)
("bugs/issue68.madl", True)
, ("solvedBugs/issue98.madl", True)
, ("solvedBugs/issue133.madl", True)
, ("solvedBugs/issue129.madl", True)
, ("solvedBugs/issue97.madl", True)
, ("solvedBugs/issue106.madl", True)
, ("solvedBugs/issue110.madl", True)
, ("solvedBugs/issue119.madl", True)
, ("solvedBugs/issue120.madl", True)
, ("solvedBugs/issue121.madl", True)
, ("solvedBugs/issue125.madl", True)
, ("solvedBugs/issue127.madl", True)
, ("solvedBugs/issue132.madl", True)
, ("solvedBugs/issue149-0.madl", True)
, ("solvedBugs/issue149-1.madl", True)
, ("solvedBugs/issue149-2.madl", True)
, ("solvedBugs/issue167.madl", True)
, ("solvedBugs/issue174.madl", True)
, ("solvedBugs/issue183.madl", False) -- TODO(snnw) Cycles Automaton (js)
, ("solvedBugs/issue184.madl", False) -- TODO(snnw) Cycles Automaton (js)
, ("spidergon/spSpidergon4.madl", True)
, ("spidergon/spSpidergon_distributed_routing.madl", True)
-- , ("spidergon/spSpidergon_master_slave.madl", True)
, ("spidergon/spSpidergon_master_slave_4.madl", True)
, ("spidergon/spSpidergon_src_routing.madl", True)
, ("ligero/model00.madl", True)
, ("mesh_xy/mesh_xy.madl", True)
, ("mesh_xy/mesh_xy_22.madl", True)
, ("mesh_xy/mesh_xy_22_ms.madl", True)
, ("mesh_xy/mesh_xy_wc.madl", True)
, ("mesh_xy/mesh_xy_wc_ms.madl", True)
-- , ("mesh_xy/mesh_xy_ms.madl", True)
, ("generatedExamples/allprim.madl", True)
, ("generatedExamples/allprimDL.madl", True)
, ("generatedExamples/itn.madl", True)
, ("generatedExamples/itn2.madl", True)
, ("generatedExamples/mergeblock.madl", True)
, ("generatedExamples/msn.madl", True)
, ("generatedExamples/redblue.madl", True)
, ("generatedExamples/redblueDL.madl", True)
, ("generatedExamples/rtn-22F.madl", True)
, ("generatedExamples/rtn-22T.madl", True)
, ("generatedExamples/rtn-23F.madl", True)
, ("generatedExamples/rtn-23T.madl", True)
, ("generatedExamples/rtn-32F.madl", True)
, ("generatedExamples/rtn-32T.madl", True)
, ("generatedExamples/rtn-34F.madl", True)
, ("generatedExamples/rtn-34T.madl", True)
, ("generatedExamples/rtn-45F.madl", True)
, ("generatedExamples/rtn-45T.madl", True)
-- , ("generatedExamples/rtn2-2F.madl", True) -- TODO(snnw) the network has a cycle!
-- , ("generatedExamples/rtn2-2T.madl", True) -- TODO(snnw) the network has a cycle!
-- , ("generatedExamples/rtn2-3F.madl", True) --excluded because merge with 3 inputs is not supported (#78)
-- , ("generatedExamples/rtn2-3T.madl", True)
, ("generatedExamples/rtn3-22F.madl", True)
, ("generatedExamples/rtn3-22T.madl", True)
, ("generatedExamples/rtn3-23F.madl", True)
, ("generatedExamples/rtn3-23T.madl", True)
, ("generatedExamples/rtn3-32F.madl", True)
, ("generatedExamples/rtn3-32T.madl", True)
, ("generatedExamples/sfn.madl", True)
, ("generatedExamples/smn.madl", True)
, ("generatedExamples/smt.madl", True)
, ("generatedExamples/smt2.madl", True)
, ("generatedExamples/smt3.madl", True)
, ("generatedExamples/ssn.madl", True)
, ("generatedExamples/stn.madl", True)
, ("generatedExamples/twoagents10.madl", True)
, ("generatedExamples/twoagents9.madl", True)
, ("generatedExamples/twoagents8.madl", True)
, ("simpleTests/allprimWithVars.madl", True)
, ("simpleTests/allprimWithVarsDL.madl", True)
, ("simpleTests/constswidletn.madl", True)
, ("simpleTests/constswidletnDL.madl", True)
, ("simpleTests/constswtn.madl", True)
, ("simpleTests/constswtn2.madl", True)
, ("simpleTests/constswtnDL.madl", True)
, ("simpleTests/dstn.madl", True)
, ("simpleTests/fcjtn01.madl", True)
, ("simpleTests/fcjtn01DL.madl", True)
, ("simpleTests/ifThenElse1.madl", True)
, ("simpleTests/ifThenElse2.madl", True)
, ("simpleTests/int_switch.madl", True)
, ("simpleTests/lbtn.madl", True)
, ("simpleTests/lbtnDL.madl", True)
, ("simpleTests/mtn01.madl", True)
, ("simpleTests/mtn01DL.madl", True)
, ("simpleTests/mtn02DL.madl", True)
, ("simpleTests/processExample.madl", False) -- TODO(snnw) Cycles Automaton
, ("simpleTests/processExampleWithFunction.madl", False) -- TODO(snnw) Cycles Automaton
, ("simpleTests/processWithVariable.madl", False) -- TODO(snnw) Cycles Automaton
, ("simpleTests/simpleMacro.madl", True)
, ("simpleTests/testInclude.madl", True)
, ("simpleTests/deadSource.madl", True)
, ("simpleTests/testing_cross_invs_01.madl", False) -- TODO(snnw) Cycles Automaton
, ("simpleTests/testing_cross_invs_02.madl", False) -- TODO(snnw) Cycles Automaton
, ("simpleTests/testing_cross_invs_03.madl", False) -- TODO(snnw) Cycles Automaton
, ("simpleTests/testing_cross_invs_04.madl", False) -- TODO(snnw) Cycles Automaton
, ("simpleTests/tn_0000.madl", True)
, ("simpleTests/tn_0001.madl", True)
, ("simpleTests/tn_0002.madl", True)
, ("simpleTests/tn_0003.madl", True)
, ("simpleTests/tn_0004.madl", True)
, ("simpleTests/tn_0005.madl", True)
, ("simpleTests/tn_0006.madl", True)
, ("simpleTests/tn_0007.madl", True)
, ("simpleTests/tn_0008.madl", True)
, ("simpleTests/tn_0009.madl", True)
, ("simpleTests/tn_0010.madl", True)
, ("simpleTests/tn_0011.madl", True)
-- , ("prodcon_v00.madl", True) -- TODO(snnw) the network has a cycle!
, ("prodcon_v01.madl", True)
, ("twoagents2_2.madl", True)
, ("vcwbn.madl", True)
]
unittests :: [(Text, Madl.MadlNetwork -> Assertion)]
unittests = [
("validNetwork", testValidNetwork)
, ("unfoldMacros", testUnfoldMacros)
, ("unfoldMacrosIdentity", testUnfoldMacrosIdentity)
, ("consistency of network", testConsistency)
, ("combinatorialCycleCheck", testCycles)
]
getTests :: (FilePath, Bool) -> IO [Test.HUnit.Base.Test]
getTests (file, runCycleCheck) = do
netOrError <- readNetworkFromFile defaultReadOptions (pathToTests ++ file)
let tstcase test = case netOrError of
Left err -> assertFailure $ "Error in network " ++file ++": " ++ err
Right net -> test net
return $ map (\(name, test) -> TestLabel (file ++ "_" ++ (utxt name)) (TestCase $ tstcase test)) . (if runCycleCheck then id else reverse . drop 1 . reverse) $ unittests
testValidNetwork :: Madl.MadlNetwork -> Assertion
testValidNetwork = assertString . fromMaybe "" . Madl.validMaDLNetwork
testUnfoldMacros :: Madl.MadlNetwork -> Assertion
testUnfoldMacros net = assertString . (fromMaybe "") $ Madl.validMaDLNetwork net' where
net' :: Madl.MadlNetwork
net' = Madl.cast' $ Madl.unflatten net_flat
net_flat :: Madl.FlatFlattenedNetwork
net_flat = Madl.unfoldMacros net
testUnfoldMacrosIdentity :: Madl.MadlNetwork -> Assertion
testUnfoldMacrosIdentity net = case Madl.getMacros net of
[] -> assertEqual "" net (Madl.cast' $ Madl.unflatten net_flat) where
net_flat :: Madl.FlatFlattenedNetwork
net_flat = Madl.unfoldMacros net
_ -> assertBool "" True
testConsistency :: Madl.MadlNetwork -> Assertion
testConsistency net = do c1; c2 where
c1 = assertBool "pre unfold consistent" (isConsistent net)
c2 = assertBool "post unfold consistent" (isConsistent expanded)
expanded :: Madl.FlatFlattenedNetwork
expanded = Madl.unfoldMacros net
testCycles :: Madl.MadlNetwork -> Assertion
testCycles net = case checkCycles net' of
[] -> assertBool "" True
_cycles -> assertBool "The net contains combinatorial cycles" False
where
net' :: Madl.FlattenedNetwork
net' = Madl.unflatten net_flat
net_flat :: Madl.FlatFlattenedNetwork
net_flat = Madl.unfoldMacros net
| julienschmaltz/madl | test/src/Madl/TestNetwork.hs | mit | 8,646 | 0 | 17 | 1,435 | 1,822 | 1,117 | 705 | 174 | 3 |
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE CPP #-}
-- | Widgets combine HTML with JS and CSS dependencies with a unique identifier
-- generator, allowing you to create truly modular HTML components.
module Yesod.Core.Widget
( -- * Datatype
WidgetT
, WidgetFor
, PageContent (..)
-- * Special Hamlet quasiquoter/TH for Widgets
, whamlet
, whamletFile
, ihamletToRepHtml
, ihamletToHtml
-- * Convert to Widget
, ToWidget (..)
, ToWidgetHead (..)
, ToWidgetBody (..)
, ToWidgetMedia (..)
-- * Creating
-- ** Head of page
, setTitle
, setTitleI
-- ** CSS
, addStylesheet
, addStylesheetAttrs
, addStylesheetRemote
, addStylesheetRemoteAttrs
, addStylesheetEither
, CssBuilder (..)
-- ** Javascript
, addScript
, addScriptAttrs
, addScriptRemote
, addScriptRemoteAttrs
, addScriptEither
-- * Subsites
, handlerToWidget
-- * Internal
, whamletFileWithSettings
, asWidgetT
) where
import Data.Monoid
import qualified Text.Blaze.Html5 as H
import Text.Hamlet
import Text.Cassius
import Text.Julius
import Yesod.Routes.Class
import Yesod.Core.Handler (getMessageRender, getUrlRenderParams)
#if __GLASGOW_HASKELL__ < 710
import Control.Applicative ((<$>))
#endif
import Text.Shakespeare.I18N (RenderMessage)
import Data.Text (Text)
import qualified Data.Map as Map
import Language.Haskell.TH.Quote (QuasiQuoter)
import Language.Haskell.TH.Syntax (Q, Exp (InfixE, VarE, LamE, AppE), Pat (VarP), newName)
import qualified Text.Hamlet as NP
import Data.Text.Lazy.Builder (fromLazyText)
import Text.Blaze.Html (toHtml, preEscapedToMarkup)
import qualified Data.Text.Lazy as TL
import qualified Data.Text.Lazy.Builder as TB
import Yesod.Core.Types
import Yesod.Core.Class.Handler
type WidgetT site (m :: * -> *) = WidgetFor site
{-# DEPRECATED WidgetT "Use WidgetFor directly" #-}
preEscapedLazyText :: TL.Text -> Html
preEscapedLazyText = preEscapedToMarkup
class ToWidget site a where
toWidget :: (MonadWidget m, HandlerSite m ~ site) => a -> m ()
instance render ~ RY site => ToWidget site (render -> Html) where
toWidget x = tell $ GWData (Body x) mempty mempty mempty mempty mempty mempty
instance render ~ RY site => ToWidget site (render -> Css) where
toWidget x = toWidget $ CssBuilder . fromLazyText . renderCss . x
instance ToWidget site Css where
toWidget x = toWidget $ CssBuilder . fromLazyText . renderCss . const x
instance render ~ RY site => ToWidget site (render -> CssBuilder) where
toWidget x = tell $ GWData mempty mempty mempty mempty (Map.singleton Nothing $ unCssBuilder . x) mempty mempty
instance ToWidget site CssBuilder where
toWidget x = tell $ GWData mempty mempty mempty mempty (Map.singleton Nothing $ unCssBuilder . const x) mempty mempty
instance render ~ RY site => ToWidget site (render -> Javascript) where
toWidget x = tell $ GWData mempty mempty mempty mempty mempty (Just x) mempty
instance ToWidget site Javascript where
toWidget x = tell $ GWData mempty mempty mempty mempty mempty (Just $ const x) mempty
instance (site' ~ site, a ~ ()) => ToWidget site' (WidgetFor site a) where
toWidget = liftWidget
instance ToWidget site Html where
toWidget = toWidget . const
-- | @since 1.4.28
instance ToWidget site Text where
toWidget = toWidget . toHtml
-- | @since 1.4.28
instance ToWidget site TL.Text where
toWidget = toWidget . toHtml
-- | @since 1.4.28
instance ToWidget site TB.Builder where
toWidget = toWidget . toHtml
-- | Allows adding some CSS to the page with a specific media type.
--
-- Since 1.2
class ToWidgetMedia site a where
-- | Add the given content to the page, but only for the given media type.
--
-- Since 1.2
toWidgetMedia :: (MonadWidget m, HandlerSite m ~ site)
=> Text -- ^ media value
-> a
-> m ()
instance render ~ RY site => ToWidgetMedia site (render -> Css) where
toWidgetMedia media x = toWidgetMedia media $ CssBuilder . fromLazyText . renderCss . x
instance ToWidgetMedia site Css where
toWidgetMedia media x = toWidgetMedia media $ CssBuilder . fromLazyText . renderCss . const x
instance render ~ RY site => ToWidgetMedia site (render -> CssBuilder) where
toWidgetMedia media x = tell $ GWData mempty mempty mempty mempty (Map.singleton (Just media) $ unCssBuilder . x) mempty mempty
instance ToWidgetMedia site CssBuilder where
toWidgetMedia media x = tell $ GWData mempty mempty mempty mempty (Map.singleton (Just media) $ unCssBuilder . const x) mempty mempty
class ToWidgetBody site a where
toWidgetBody :: (MonadWidget m, HandlerSite m ~ site) => a -> m ()
instance render ~ RY site => ToWidgetBody site (render -> Html) where
toWidgetBody = toWidget
instance render ~ RY site => ToWidgetBody site (render -> Javascript) where
toWidgetBody j = toWidget $ \r -> H.script $ preEscapedLazyText $ renderJavascriptUrl r j
instance ToWidgetBody site Javascript where
toWidgetBody j = toWidget $ \_ -> H.script $ preEscapedLazyText $ renderJavascript j
instance ToWidgetBody site Html where
toWidgetBody = toWidget
class ToWidgetHead site a where
toWidgetHead :: (MonadWidget m, HandlerSite m ~ site) => a -> m ()
instance render ~ RY site => ToWidgetHead site (render -> Html) where
toWidgetHead = tell . GWData mempty mempty mempty mempty mempty mempty . Head
instance render ~ RY site => ToWidgetHead site (render -> Css) where
toWidgetHead = toWidget
instance ToWidgetHead site Css where
toWidgetHead = toWidget
instance render ~ RY site => ToWidgetHead site (render -> CssBuilder) where
toWidgetHead = toWidget
instance ToWidgetHead site CssBuilder where
toWidgetHead = toWidget
instance render ~ RY site => ToWidgetHead site (render -> Javascript) where
toWidgetHead j = toWidgetHead $ \r -> H.script $ preEscapedLazyText $ renderJavascriptUrl r j
instance ToWidgetHead site Javascript where
toWidgetHead j = toWidgetHead $ \_ -> H.script $ preEscapedLazyText $ renderJavascript j
instance ToWidgetHead site Html where
toWidgetHead = toWidgetHead . const
-- | Set the page title. Calling 'setTitle' multiple times overrides previously
-- set values.
setTitle :: MonadWidget m => Html -> m ()
setTitle x = tell $ GWData mempty (Last $ Just $ Title x) mempty mempty mempty mempty mempty
-- | Set the page title. Calling 'setTitle' multiple times overrides previously
-- set values.
setTitleI :: (MonadWidget m, RenderMessage (HandlerSite m) msg) => msg -> m ()
setTitleI msg = do
mr <- getMessageRender
setTitle $ toHtml $ mr msg
-- | Link to the specified local stylesheet.
addStylesheet :: MonadWidget m => Route (HandlerSite m) -> m ()
addStylesheet = flip addStylesheetAttrs []
-- | Link to the specified local stylesheet.
addStylesheetAttrs :: MonadWidget m
=> Route (HandlerSite m)
-> [(Text, Text)]
-> m ()
addStylesheetAttrs x y = tell $ GWData mempty mempty mempty (toUnique $ Stylesheet (Local x) y) mempty mempty mempty
-- | Link to the specified remote stylesheet.
addStylesheetRemote :: MonadWidget m => Text -> m ()
addStylesheetRemote = flip addStylesheetRemoteAttrs []
-- | Link to the specified remote stylesheet.
addStylesheetRemoteAttrs :: MonadWidget m => Text -> [(Text, Text)] -> m ()
addStylesheetRemoteAttrs x y = tell $ GWData mempty mempty mempty (toUnique $ Stylesheet (Remote x) y) mempty mempty mempty
addStylesheetEither :: MonadWidget m
=> Either (Route (HandlerSite m)) Text
-> m ()
addStylesheetEither = either addStylesheet addStylesheetRemote
addScriptEither :: MonadWidget m
=> Either (Route (HandlerSite m)) Text
-> m ()
addScriptEither = either addScript addScriptRemote
-- | Link to the specified local script.
addScript :: MonadWidget m => Route (HandlerSite m) -> m ()
addScript = flip addScriptAttrs []
-- | Link to the specified local script.
addScriptAttrs :: MonadWidget m => Route (HandlerSite m) -> [(Text, Text)] -> m ()
addScriptAttrs x y = tell $ GWData mempty mempty (toUnique $ Script (Local x) y) mempty mempty mempty mempty
-- | Link to the specified remote script.
addScriptRemote :: MonadWidget m => Text -> m ()
addScriptRemote = flip addScriptRemoteAttrs []
-- | Link to the specified remote script.
addScriptRemoteAttrs :: MonadWidget m => Text -> [(Text, Text)] -> m ()
addScriptRemoteAttrs x y = tell $ GWData mempty mempty (toUnique $ Script (Remote x) y) mempty mempty mempty mempty
whamlet :: QuasiQuoter
whamlet = NP.hamletWithSettings rules NP.defaultHamletSettings
whamletFile :: FilePath -> Q Exp
whamletFile = NP.hamletFileWithSettings rules NP.defaultHamletSettings
whamletFileWithSettings :: NP.HamletSettings -> FilePath -> Q Exp
whamletFileWithSettings = NP.hamletFileWithSettings rules
asWidgetT :: WidgetT site m () -> WidgetT site m ()
asWidgetT = id
rules :: Q NP.HamletRules
rules = do
ah <- [|asWidgetT . toWidget|]
let helper qg f = do
x <- newName "urender"
e <- f $ VarE x
let e' = LamE [VarP x] e
g <- qg
bind <- [|(>>=)|]
return $ InfixE (Just g) bind (Just e')
let ur f = do
let env = NP.Env
(Just $ helper [|getUrlRenderParams|])
(Just $ helper [|fmap (toHtml .) getMessageRender|])
f env
return $ NP.HamletRules ah ur $ \_ b -> return $ ah `AppE` b
-- | Wraps the 'Content' generated by 'hamletToContent' in a 'RepHtml'.
ihamletToRepHtml :: (MonadHandler m, RenderMessage (HandlerSite m) message)
=> HtmlUrlI18n message (Route (HandlerSite m))
-> m Html
ihamletToRepHtml = ihamletToHtml
{-# DEPRECATED ihamletToRepHtml "Please use ihamletToHtml instead" #-}
-- | Wraps the 'Content' generated by 'hamletToContent' in a 'RepHtml'.
--
-- Since 1.2.1
ihamletToHtml :: (MonadHandler m, RenderMessage (HandlerSite m) message)
=> HtmlUrlI18n message (Route (HandlerSite m))
-> m Html
ihamletToHtml ih = do
urender <- getUrlRenderParams
mrender <- getMessageRender
return $ ih (toHtml . mrender) urender
tell :: MonadWidget m => GWData (Route (HandlerSite m)) -> m ()
tell = liftWidget . tellWidget
toUnique :: x -> UniqueList x
toUnique = UniqueList . (:)
handlerToWidget :: HandlerFor site a -> WidgetFor site a
handlerToWidget (HandlerFor f) = WidgetFor $ f . wdHandler
| psibi/yesod | yesod-core/Yesod/Core/Widget.hs | mit | 10,891 | 0 | 18 | 2,313 | 3,071 | 1,608 | 1,463 | 206 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE DeriveGeneric #-}
module Types.Poll where
import Data.Text
import Data.Aeson
import Data.UUID
import Control.Applicative
import GHC.Generics
import Data.Time.Clock
import Database.PostgreSQL.Simple.FromField
import Database.PostgreSQL.Simple.FromRow
--import Database.PostgreSQL.Simple.ToField
import Database.PostgreSQL.Simple.ToRow
import Data.Default
--------------------------------------------------------------------------------
data Poll =
Poll { pollId :: Int
, pollTitle :: Maybe Text
, pollDesc :: Maybe Text
, pollStart :: Maybe UTCTime
, pollEnd :: Maybe UTCTime
, pollOwner :: Maybe Int
, pollChann :: Maybe Int
} deriving (Eq, Generic, Show)
instance FromJSON Poll
instance ToJSON Poll
instance FromRow Poll
instance ToRow Poll
instance Default Poll where
def = Poll 0 Nothing Nothing Nothing Nothing Nothing Nothing
| sigrlami/pollock | app-snap/src/Types/Poll.hs | mit | 1,006 | 0 | 9 | 197 | 208 | 119 | 89 | 29 | 0 |
solution = (sum [1..100]) ^ 2 - sum ( map (^ 2) [1..100]) | DylanSp/Project-Euler-in-Haskell | prob6/solution.hs | mit | 57 | 0 | 9 | 12 | 45 | 24 | 21 | 1 | 1 |
-- AnalyzerCondition.hs ---
--
-- Filename: AnalyzerCondition.hs
-- Description:
-- Author: Manuel Schneckenreither
-- Maintainer:
-- Created: Mon Oct 6 23:22:48 2014 (+0200)
-- Version:
-- Package-Requires: ()
-- Last-Updated: Tue Apr 11 14:34:09 2017 (+0200)
-- By: Manuel Schneckenreither
-- Update #: 7
-- URL:
-- Doc URL:
-- Keywords:
-- Compatibility:
--
--
-- Commentary:
--
--
--
--
-- Change Log:
--
--
--
--
--
--
--
-- Code:
-- | TODO: comment this module
module Data.Rewriting.ARA.ByInferenceRules.AnalyzerCondition
( module Data.Rewriting.ARA.ByInferenceRules.AnalyzerCondition.Type
, module Data.Rewriting.ARA.ByInferenceRules.AnalyzerCondition.Pretty
)
where
import Data.Rewriting.ARA.ByInferenceRules.AnalyzerCondition.Pretty
import Data.Rewriting.ARA.ByInferenceRules.AnalyzerCondition.Type
--
-- AnalyzerCondition.hs ends here
| ComputationWithBoundedResources/ara-inference | src/Data/Rewriting/ARA/ByInferenceRules/AnalyzerCondition.hs | mit | 903 | 0 | 5 | 156 | 84 | 73 | 11 | 5 | 0 |
module Rosalind.Bases where
-- We represent the bases of DNA A, C, G, T as Haskell values. And stuff.
-- There is a bit at the end of this module that deals with generating random
-- gene sequences then looking at the reverse complement of those sequences.
import Control.Comonad
import Control.Monad.State
import Data.Array
import Data.Char
import Data.Monoid
-- below imports available via 1HaskellADay git repository
import Control.List -- for List comonad
import Data.Random
data Base = A | T | C | G
deriving (Eq, Ord, Enum, Bounded, Ix, Show, Read)
allBases :: [Base]
allBases = [A ..]
data NucleotideTriple = Triple (Base, Base, Base)
deriving (Eq, Ord)
allTriples :: [NucleotideTriple]
allTriples = map Triple [(a,b,c) | a <- allBases, b <- allBases, c <- allBases]
{--
For the read instance of a triple, we will specialize on the formatting
we are give which is, e.g.: "tgg"
--}
instance Show NucleotideTriple where
show (Triple (a, b, c)) = map (head . show) [a, b, c]
mkTrip :: [Base] -> NucleotideTriple
mkTrip [a,b,c] = Triple (a,b,c)
instance Read NucleotideTriple where
readsPrec prec = readParen False
(\r -> [(mkTrip bases, rest) |
(trechars, rest) <- lex r,
let bases = map (read . return . toUpper) trechars])
-- so, let triple = Triple (T, G, G) in read (show triple) == triple is True
-- Now, let's talk generating Gene Sequences from 1HAD 2016-02-12:
data GeneSequence = GS { bases :: [Base] }
instance Show GeneSequence where
show (GS seq) = map (head . show) seq
instance Read GeneSequence where
readsPrec _ str = [(GS $ map (read . pure) str, "")]
instance Monoid GeneSequence where
mempty = GS []
GS a `mappend` GS b = GS (a `mappend` b)
rndGeneSequence :: Monad m => Int -> StateT (RNG Int) m GeneSequence
rndGeneSequence = fmap (GS . map (toEnum . (`mod` 4))) . someRNDs
-- ... return a really long one, like more than 1,000 nucleotides ... we'll
-- be sequencing it for a future exercise, don't you know.
-- (So, yah, I just said, 'return a random gene sequence, but make sure it's
-- long') (deal with the conundrum.)
-- geophf, n.: heart-breaker, dream wrecker, train crasher, conundrum maker.
{--
*Main> rndSeed >>= evalStateT (rndGeneSequence 1000) ~>
AAATGTATGCCCTGAGTGCCGTTCTTGATGCTGTTGATCGCGGATTGCGTGACCCCCTGAGAAATTATTCGGACGTG
AATGTATCGCACCGTTGAGGGCGACACTCCCTGATGTTTTTTGGGAATCATGCAATTAAACATCAGAGCTTGCTGCA
CCGTCAGCAGTGATTTTGTGGTTCTGCCGCACTATGCCAGTTTGAGCCTGTTTGATATGGAGCACTATTGAGTAAAG
GGACTTTCTGTTTGTGAGAACTTCACCTTGGTCGCGCCAACGCGAGCACGTTCGAAATACTAATCACCATCTCTGTG
TGTATTGATGGTACCCCATATACTGTTGATCAGCGCAGACGTACAGCGCGCTTCTACAATAAACTTGTAGGTATGCT
CTCCAAAAAAAGACTAATTTGCCGATTTCCGCTTTTGCGAGACACTTGAGTAAGAATAGGCTCACAGTACGCAACCG
ACGAAAGATGTCTGGTATGCGAAATCCCCTCTGATTGCGGCATTGGGGATCATATAGGAGCATGAGAATCAATTTTT
CCACAGGAACGCGTATGGCATAAACTCTCATCCATCGATACGCCAGCATTACACGATGGACTGAACAATTACCCAGC
CAACTTGGAGTTCTCCCGGACGACAAATCTTAGGTCCGAGCGAGACGCTCAGTTATAAAATCATGTATAACCCCTGA
ACGTCCTTGCGATCGCTTGCCCCGCAAATTATCATTTATGTTCGTAGTAATGGGCGTGGATAGTCGTCTGTATTCTG
CAAGGTCGCTGCCATACAAAGGATTAAGAGTTGTGTTAGATCGCGATTAACGTAGGCTTGGAGACGCACCGAGGAGT
ATTGACCTGGACGGGTATCGCGTCGGAAGACCGCACGCTCGACGAGCTATCCTTTTTGGTGCCGTGATCTGATTAGA
GTACGGTCCAGGCAAATTGGGGGAAACGCAAGGGTTTACAAGACGGGCGATCGAGCGCATAATTATAGCAGTAACC
Okay, now let's separate the above into nucleotide triples.
Here's the thing: in a strand, you don't know where you're 'starting.' So you
don't know what the triples are, so, say you have this strand:
... GCTCAGATGTTAGAAGGAGATTAGGCGTCAGAAGCTAAGGGTATTCCAGA ...
Where is it's 'beginning'? You don't know. So the leading triples here could be:
[GCT,CAG,ATG,...] (obviously)
OR, they could be:
[CTC,AGA,TGT, ...] (drop 1)
OR, they could be:
[TCA,GAT,GTT, ...] (drop 2)
So let's do that. How? Comonads, obviously!
First we make the bases of a gene sequence a comonad. We can do this because
we 'know' that a gene sequence is never empty. 'Know' is a technical term:
it means 'know.'
--}
-- Now we chunk-n-dunk? Nah: let's slice-n-dice, instead!
strands :: GeneSequence -> [[NucleotideTriple]]
strands (GS genes) = take 3 (genes =>> slicer)
slicer :: [Base] -> [NucleotideTriple]
slicer (a:b:c:rest) = Triple (a,b,c) : slicer rest
slicer _ = []
{--
So, for the above set of bases:
*Main> let bases = "GCTCAGATGTTAGAAGGAGATTAGGCGTCAGAAGCTAAGGGTATTCCAGA"
*Main> strands (GS $ map (read . return) bases) ~>
[[GCT,CAG,ATG,TTA,GAA,GGA,GAT,TAG,GCG,TCA,GAA,GCT,AAG,GGT,ATT,CCA],
[CTC,AGA,TGT,TAG,AAG,GAG,ATT,AGG,CGT,CAG,AAG,CTA,AGG,GTA,TTC,CAG],
[TCA,GAT,GTT,AGA,AGG,AGA,TTA,GGC,GTC,AGA,AGC,TAA,GGG,TAT,TCC,AGA]]
Okay, now let's generate a random set of bases:
*Main> rndSeed >>= evalStateT (rndGeneSequence 1000) ~>
TTTCACAGAAAGCGTTAGGGGAGGGCCAGGCGTCTTTGAGTGTTCATTTATTC ...
*Main> strands bases ~>
[[TTT,CAC,AGA,AAG,CGT,TAG,GGG,AGG,GCC,AGG,CGT,CTT,TGA, ...], ...]
--}
-- How about the reverse complement?
reverseComplement :: GeneSequence -> GeneSequence
reverseComplement (GS bases) = GS (map complement (reverse bases))
complement :: Base -> Base
complement A = T
complement T = A
complement G = C
complement C = G
isComplement :: Base -> Base -> Bool
isComplement b = (b ==) . complement
| geophf/1HaskellADay | exercises/HAD/Rosalind/Bases.hs | mit | 5,215 | 0 | 17 | 784 | 809 | 449 | 360 | 49 | 1 |
module Text.Regex.VerbalExpressions
( verEx
, add
, startOfLine
, startOfLine'
, endOfLine
, endOfLine'
, find
, possibly
, anything
, anythingBut
, something
, somethingBut
, replace
, lineBreak
, br
, tab
, word
, anyOf
, range
, withAnyCase
, withAnyCase'
, searchOneLine
, searchOneLine'
, searchGlobal
, searchGlobal'
, multiple
, alt
, test
) where
import Text.Regex.PCRE (getAllTextMatches, (=~))
import Data.Bits((.|.), (.&.), xor )
import Data.List(intersperse, isPrefixOf)
type Flag = Int
ignorecase :: Flag
ignorecase = 1
multiline :: Flag
multiline = 2
global :: Flag
global = 4
data VerStruct = VerStruct { prefix :: String
, pattern :: String
, suffix :: String
, source :: String
, flags :: Flag
}
instance Show VerStruct where
show = pattern
verEx :: VerStruct
verEx = VerStruct "" "" "" "" 0
withAnyCase :: VerStruct -> VerStruct
withAnyCase v = withAnyCase' True v
withAnyCase' :: Bool -> VerStruct -> VerStruct
withAnyCase' True v = v { flags = flags v .|. ignorecase }
withAnyCase' False v = v { flags = flags v `xor` ignorecase }
searchOneLine :: VerStruct -> VerStruct
searchOneLine v = searchOneLine' True v
searchOneLine' :: Bool -> VerStruct -> VerStruct
searchOneLine' True v = v { flags = flags v `xor` multiline }
searchOneLine' False v = v { flags = flags v .|. multiline }
searchGlobal :: VerStruct -> VerStruct
searchGlobal v = searchGlobal' True v
searchGlobal' :: Bool -> VerStruct -> VerStruct
searchGlobal' True v = v { flags = flags v .|. global }
searchGlobal' False v = v { flags = flags v `xor` global }
add :: String -> VerStruct -> VerStruct
add val v = v { pattern = foldl (++) "" [prefix v, source v, val, suffix v]
, source = foldl (++) "" [source v, val] }
find :: String -> VerStruct -> VerStruct
find val v = add ("(?:" ++ val ++ ")") v
possibly :: String -> VerStruct -> VerStruct
possibly val v = add ("(?:" ++ val ++ ")?") v
anything :: VerStruct -> VerStruct
anything v = add "(?:.*)" v
anythingBut :: String -> VerStruct -> VerStruct
anythingBut val v = add ("(?:[^" ++ val ++ "]*)") v
something :: VerStruct -> VerStruct
something v = add "(?:.+)" v
somethingBut :: String -> VerStruct -> VerStruct
somethingBut val v = add ("(?:[^" ++ val ++ "]+)") v
startOfLine :: VerStruct -> VerStruct
startOfLine v = startOfLine True v
startOfLine' :: Bool -> VerStruct -> VerStruct
startOfLine' True v = add "" v { prefix = "^" }
startOfLine' False v = add "" v { prefix = "" }
endOfLine :: VerStruct -> VerStruct
endOfLine v = endOfLine True v
endOfLine' :: Bool -> VerStruct -> VerStruct
endOfLine' True v = add "" v { suffix = "$" }
endOfLine' False v = add "" v { suffix = "" }
lineBreak :: VerStruct -> VerStruct
lineBreak v = add "(?:(?:\\n)|(?:\\r\\n))" v
br :: VerStruct -> VerStruct
br v = lineBreak v
tab :: VerStruct -> VerStruct
tab v = add "(\\t)" v
word :: VerStruct -> VerStruct
word v = add "(\\w+)" v
anyOf :: String -> VerStruct -> VerStruct
anyOf val v = add ("[" ++ val ++ "]") v
range :: [String] -> VerStruct -> VerStruct
range args v = add ("[" ++ buildrange args ++ "]") v
where
buildrange xs | length xs >= 2 = head xs ++ "-" ++ (head $ tail xs) ++ (buildrange $ tail $ tail xs)
| otherwise = ""
multiple :: String -> VerStruct -> VerStruct
multiple val v | head val == '*' = add val v
| head val == '+' = add val v
| otherwise = add ("+" ++ val) v
alt :: String -> VerStruct -> VerStruct
alt val v = find val (add ")|(" v { prefix = checkPrefix, suffix = checkSuffix })
where
checkPrefix
| elem '(' (prefix v) == True = prefix v ++ "("
| otherwise = prefix v
checkSuffix
| elem ')' (suffix v) == True = ")" ++ suffix v
| otherwise = suffix v
replace :: String -> String -> VerStruct -> String
replace s val v = replacewords (getStringMatches s v) val s
test :: String -> VerStruct -> Bool
test val v | flags v .&. multiline > 0 = foundMatch val
| otherwise = foundMatch $ foldl (++) "" (split "\n" val)
where
foundMatch :: String -> Bool
foundMatch value | flags v .&. global > 0 = resultOf $ globalSearch value
| otherwise = resultOf $ lineSearch value
searcher :: String -> [String]
searcher value = getStringMatches value v
resultOf :: [a] -> Bool
resultOf l = length l /= 0
globalSearch :: String -> [String]
globalSearch value = searcher value
lineSearch :: String -> [String]
lineSearch value = foldl (++) [] (map searcher (lines value))
replacewords :: [String] -> String -> String -> String
replacewords [] _ sen = sen
replacewords (x:xs) replacer sen = replacewords xs replacer (replacefirst x sen)
where
replacefirst :: String -> String -> String
replacefirst w s = (head $ split w s)
++ replacer
++ join w (tail $ split w s)
getStringMatches :: String -> VerStruct -> [String]
getStringMatches val v = getAllTextMatches $ val =~ pattern v :: [String]
--these are from Data.List.Utils
split :: Eq a => [a] -> [a] -> [[a]]
split _ [] = []
split delim str =
let (firstline, remainder) = breakList (isPrefixOf delim) str
in
firstline : case remainder of
[] -> []
x -> if x == delim
then [] : []
else split delim
(drop (length delim) x)
breakList :: ([a] -> Bool) -> [a] -> ([a], [a])
breakList func = spanList (not . func)
spanList :: ([a] -> Bool) -> [a] -> ([a], [a])
spanList _ [] = ([],[])
spanList func list@(x:xs) =
if func list
then (x:ys,zs)
else ([],list)
where (ys,zs) = spanList func xs
join :: [a] -> [[a]] -> [a]
join delim l = concat (intersperse delim l) | whackashoe/HaskellVerbalExpressions | Text/Regex/VerbalExpressions/verbalexpressions.hs | mit | 6,439 | 0 | 16 | 2,100 | 2,273 | 1,199 | 1,074 | 160 | 3 |
module IRC.Log (
logMessage,
commandHasLogger,
)
where
import Data.List
import qualified Data.Map as Map
import IRC.Parsers
import IRC.Types
import Network
import System.IO
import Text.Printf
commandHasLogger :: CommandName -> Bool
commandHasLogger command = Map.member command commandFormatters
commandFormatters = Map.fromList [
("PRIVMSG", formatPrivmsgForLog),
("JOIN", formatJoinForLog),
("NICK", formatNickChangeForLog),
("PART", formatPartForLog),
("QUIT", formatQuitForLog),
("NOTICE", formatNoticeForLog),
("353", formatNamesListForLog),
("332", formatTopicForLog)]
logMessage :: LogHandle -> CommandName -> RawIRCMessage -> IO ()
logMessage fh command message = writeLogMessage fh (Map.lookup command commandFormatters) message
writeLogMessage :: LogHandle -> Maybe (RawIRCMessage -> String) -> RawIRCMessage -> IO ()
writeLogMessage fh (Just formatf) = hPutStrLn fh . formatf
-- Format Messages For Logs
-- These take a recieved message, and return a format suitable for writing to the log file.
formatFromUserForLog :: RawIRCMessage -> String -> String
formatFromUserForLog format_string x = printf format_string username message where
details = getUserAndMessage x
username = fst details
message = snd details
formatPrivmsgForLog :: RawIRCMessage -> String
formatPrivmsgForLog = formatFromUserForLog "<%s> %s"
formatNoticeForLog :: RawIRCMessage -> String
formatNoticeForLog = printf "Notice: %s" . getMultiWordPortion
formatQuitForLog :: RawIRCMessage -> String
formatQuitForLog = formatFromUserForLog "%s quit (%s)"
formatJoinForLog :: RawIRCMessage -> String
formatJoinForLog = formatFromUserForLog "%s joined %s"
formatTopicForLog :: RawIRCMessage -> String
formatTopicForLog = printf "Topic: %s" . getMultiWordPortion
formatNamesListForLog :: RawIRCMessage -> String
formatNamesListForLog = printf "Users in room: %s" . getMultiWordPortion
formatNickChangeForLog :: RawIRCMessage -> String
formatNickChangeForLog = formatFromUserForLog "%s changed nick to %s"
formatPartForLog :: RawIRCMessage -> String
formatPartForLog message = printf "%s left %s" (getUser message) ((words message) !! 2)
| Macha/Mbot | IRC/Log.hs | mit | 2,210 | 0 | 9 | 349 | 495 | 271 | 224 | 46 | 1 |
{-# LANGUAGE NoImplicitPrelude, OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE CPP #-}
module IHaskell.Convert.IpynbToLhs (ipynbToLhs) where
import IHaskellPrelude
import qualified Data.Text.Lazy as LT
import qualified Data.ByteString.Lazy as LBS
import Data.Aeson (decode, Object, Value(Array, Object, String))
import Data.Vector (Vector)
import qualified Data.Text.Lazy.IO as LTIO
import qualified Data.Vector as V (map, mapM, toList)
import IHaskell.Flags (LhsStyle(..))
#if MIN_VERSION_aeson(2,0,0)
import Data.Aeson.KeyMap (lookup)
#else
import Data.HashMap.Strict (lookup)
#endif
ipynbToLhs :: LhsStyle LText
-> FilePath -- ^ the filename of an ipython notebook
-> FilePath -- ^ the filename of the literate haskell to write
-> IO ()
ipynbToLhs sty from to = do
Just (js :: Object) <- decode <$> LBS.readFile from
case lookup "cells" js of
Just (Array cells) ->
LTIO.writeFile to $ LT.unlines $ V.toList $ V.map (\(Object y) -> convCell sty y) cells
_ -> error "IHaskell.Convert.ipynbTolhs: json does not follow expected schema"
concatWithPrefix :: LT.Text -- ^ the prefix to add to every line
-> Vector Value -- ^ a json array of text lines
-> Maybe LT.Text
concatWithPrefix p arr = LT.concat . map (p <>) . V.toList <$> V.mapM toStr arr
toStr :: Value -> Maybe LT.Text
toStr (String x) = Just (LT.fromStrict x)
toStr _ = Nothing
-- | @convCell sty cell@ converts a single cell in JSON into text suitable for the type of lhs file
-- described by the @sty@
convCell :: LhsStyle LT.Text -> Object -> LT.Text
convCell _sty object
| Just (String "markdown") <- lookup "cell_type" object,
Just (Array xs) <- lookup "source" object,
~(Just s) <- concatWithPrefix "" xs
= s
convCell sty object
| Just (String "code") <- lookup "cell_type" object,
Just (Array a) <- lookup "source" object,
Just (Array o) <- lookup "outputs" object,
~(Just i) <- concatWithPrefix (lhsCodePrefix sty) a,
o2 <- fromMaybe mempty (convOutputs sty o)
= "\n" <>
lhsBeginCode sty <> i <> lhsEndCode sty <> "\n" <> o2 <> "\n"
convCell _ _ = "IHaskell.Convert.convCell: unknown cell"
convOutputs :: LhsStyle LT.Text
-> Vector Value -- ^ JSON array of output lines containing text or markup
-> Maybe LT.Text
convOutputs sty array = do
outputLines <- V.mapM (getTexts (lhsOutputPrefix sty)) array
return $ lhsBeginOutput sty <> LT.concat (V.toList outputLines) <> lhsEndOutput sty
getTexts :: LT.Text -> Value -> Maybe LT.Text
getTexts p (Object object)
| Just (Array text) <- lookup "text" object = concatWithPrefix p text
getTexts _ _ = Nothing
| gibiansky/IHaskell | src/IHaskell/Convert/IpynbToLhs.hs | mit | 2,775 | 0 | 15 | 627 | 822 | 419 | 403 | 55 | 2 |
-- List reversion. Tail recursion with "foldl".
module Reverse where
import Prelude hiding (reverse)
import Data.List (foldl)
reverse :: [t] -> [t]
reverse = foldl (\remainingItems item -> item : remainingItems) []
{- GHCi>
reverse ""
reverse "1"
reverse "12"
-}
-- ""
-- "1"
-- "21"
| pascal-knodel/haskell-craft | Examples/· Folds/reverse/foldl/Reverse.hs | mit | 301 | 0 | 8 | 64 | 69 | 43 | 26 | 5 | 1 |
{- |
Module : $Header$
Description : translating a HasCASL subset to Isabelle
Copyright : (c) C. Maeder, DFKI 2008
License : GPLv2 or higher, see LICENSE.txt
Maintainer : Christian.Maeder@dfki.de
Stability : provisional
Portability : portable
utility function for translation from HasCASL to Isabelle leaving open how
partial values are interpreted
-}
module Comorphisms.PPolyTyConsHOL2IsaUtils
( mapTheory
, simpForPairs
, simpForOption
, typeToks
, transSentence
, SimpKind (..)
, OldSimpKind (..)
) where
import HasCASL.As as As
import HasCASL.AsUtils
import HasCASL.Builtin
import HasCASL.DataAna
import HasCASL.Le as Le
import HasCASL.Unify (substGen)
import Isabelle.IsaSign as Isa
import Isabelle.IsaConsts
import Isabelle.IsaPrint
import Isabelle.Translate
import Common.DocUtils
import Common.Id
import Common.Result
import Common.Utils (isSingleton, number)
import Common.Lib.State
import Common.AS_Annotation
import Common.GlobalAnnotations
import qualified Data.Map as Map
import qualified Data.Set as Set
import Data.List
import Data.Maybe
import Control.Monad (foldM)
mapTheory :: SimpKind -> Simplifier -> (Env, [Named Le.Sentence])
-> Result (Isa.Sign, [Named Isa.Sentence])
mapTheory simK simpF (env, sens) = do
let tyToks = typeToks env
sign <- transSignature env tyToks
isens <- mapM (mapNamedM $ transSentence env tyToks simK simpF) sens
(dt, _, _) <- foldM (transDataEntries env tyToks)
([], Set.empty, Set.empty) $ filter (not . null) $ map
(\ ns -> case sentence ns of
DatatypeSen ds -> ds
_ -> []) sens
return ( sign { domainTab = reverse dt }
, filter ((/= mkSen true) . sentence) isens)
-- * Signature
baseSign :: BaseSig
baseSign = MainHC_thy
transAssumps :: GlobalAnnos -> Set.Set String -> Assumps -> Result ConstTab
transAssumps ga toks = foldM insertOps Map.empty . Map.toList where
insertOps m (name, ops) =
let chk = isPlainFunType
in case map opType $ Set.toList ops of
[TypeScheme _ op _ ] -> do
ty <- funType op
return $ Map.insert
(mkIsaConstT (isPredType op) ga (chk ty)
name baseSign toks) (transPlainFunType ty) m
infos -> foldM ( \ m' (TypeScheme _ op _, i) -> do
ty <- funType op
return $ Map.insert
(mkIsaConstIT (isPredType op) ga (chk ty)
name i baseSign toks) (transPlainFunType ty) m'
) m $ number infos
-- all possible tokens of mixfix identifiers that must not be used as variables
getAssumpsToks :: Assumps -> Set.Set String
getAssumpsToks = Map.foldWithKey (\ i ops s ->
Set.union s $ Set.unions
$ map (\ (_, o) -> getConstIsaToks i o baseSign)
$ number $ Set.toList ops) Set.empty
typeToks :: Env -> Set.Set String
typeToks =
Set.map (`showIsaTypeT` baseSign) . Map.keysSet . typeMap
transSignature :: Env -> Set.Set String -> Result Isa.Sign
transSignature env toks = do
let extractTypeName tyId typeInfo m =
let getTypeArgs n k = case k of
ClassKind _ -> []
FunKind _ _ r _ ->
(TFree ("'a" ++ show n) [], holType)
: getTypeArgs (n + 1) r
in Map.insert (showIsaTypeT tyId baseSign)
[(isaTerm, getTypeArgs (1 :: Int) $ typeKind typeInfo)] m
ct <- transAssumps (globAnnos env) toks $ assumps env
return $ Isa.emptySign
{ baseSig = baseSign
-- translation of typeconstructors
, tsig = emptyTypeSig
{ arities = Map.foldWithKey extractTypeName Map.empty
$ typeMap env }
, constTab = ct }
-- * translation of a type in an operation declaration
unitTyp :: Typ
unitTyp = Type "unit" holType []
mkPartialType :: Typ -> Typ
mkPartialType arg = Type "partial" [] [arg]
transFunType :: FunType -> Typ
transFunType fty = case fty of
UnitType -> unitTyp
BoolType -> boolType
FunType f a -> mkFunType (transFunType f) $ transFunType a
PartialVal a -> mkPartialType $ transFunType a
PairType a b -> prodType (transFunType a) $ transFunType b
TupleType l -> case l of
[] -> error "transFunType"
_ -> transFunType $ foldl1 PairType l
ApplType tid args -> Type (showIsaTypeT tid baseSign) []
$ map transFunType args
TypeVar tid -> TFree (showIsaTypeT tid baseSign) []
-- compute number of arguments for plain CASL functions
isPlainFunType :: FunType -> Int
isPlainFunType fty = case fty of
FunType f a -> case a of
FunType _ _ -> -1
_ -> case f of
TupleType l -> length l
_ -> 1
_ -> 0
transPlainFunType :: FunType -> Typ
transPlainFunType fty =
case fty of
FunType (TupleType l) a -> case a of
FunType _ _ -> transFunType fty
_ -> foldr (mkFunType . transFunType) (transFunType a) l
_ -> transFunType fty
data FunType = UnitType | BoolType
| FunType FunType FunType
| PartialVal FunType
| PairType FunType FunType -- only used to represent tuples as nested pairs
| TupleType [FunType]
| ApplType Id [FunType]
| TypeVar Id
deriving (Eq, Show)
isPartialVal :: FunType -> Bool
isPartialVal t = case t of
PartialVal _ -> True
BoolType -> True
_ -> False
makePartialVal :: FunType -> FunType
makePartialVal t = if isPartialVal t then t else case t of
UnitType -> BoolType
_ -> PartialVal t
funType :: Type -> Result FunType
funType t = case getTypeAppl t of
(TypeName tid _ n, tys)
| n == 0 -> do
ftys <- mapM funType tys
return $ case ftys of
[] | tid == unitTypeId -> UnitType
[ty] | tid == lazyTypeId -> makePartialVal ty
[t1, t2] | isArrow tid -> FunType t1 $
if isPartialArrow tid then makePartialVal t2 else t2
(_ : _ : _) | isProductId tid -> TupleType ftys
_ -> ApplType tid ftys
| null tys -> return $ TypeVar tid
_ -> fatal_error "funType: no flat type appl" $ getRange t
-- * translation of a datatype declaration
transDataEntries :: Env -> Set.Set String
-> (DomainTab, Set.Set TName, Set.Set VName) -> [DataEntry]
-> Result (DomainTab, Set.Set TName, Set.Set VName)
transDataEntries env tyToks t@(dt, tys, cs) l = do
let rs = map (transDataEntry env tyToks) l
ms = map maybeResult rs
toWarning = map ( \ d -> d { diagKind = Warning })
appendDiags $ toWarning $ concatMap diags rs
if any isNothing ms then return t
else do
let des = catMaybes ms
ntys = map (Isa.typeId . fst . fst) des
ncs = concatMap (map fst . snd) des
foldF str cnv = foldM ( \ s i ->
if Set.member i s then
fail $ "duplicate " ++ str ++ cnv i
else return $ Set.insert i s)
Result d1 mrtys = foldF "datatype " id tys ntys
Result d2 mrcs = foldF "constructor " new cs ncs
appendDiags $ toWarning $ d1 ++ d2
case (mrtys, mrcs) of
(Just rtys, Just rcs) -> return (des : dt, rtys, rcs)
_ -> return t
-- datatype with name (tyId) + args (tyArgs) and alternatives
transDataEntry :: Env -> Set.Set String -> DataEntry -> Result DomainEntry
transDataEntry env tyToks de@(DataEntry _ _ gk _ _ alts) =
let dp@(DataPat _ i tyArgs _ _) = toDataPat de
in case gk of
Le.Free -> do
nalts <- mapM (transAltDefn env tyToks dp) $ Set.toList alts
let transDName ti = Type (showIsaTypeT ti baseSign) []
. map transTypeArg
return ((transDName i tyArgs, Nothing), nalts)
_ -> fatal_error ("not a free type: " ++ show i)
$ posOfId i
-- arguments of a datatype's typeconstructor
transTypeArg :: TypeArg -> Typ
transTypeArg ta = TFree (showIsaTypeT (getTypeVar ta) baseSign) []
-- datatype alternatives/constructors
transAltDefn :: Env -> Set.Set String -> DataPat -> AltDefn
-> Result (VName, [Typ])
transAltDefn env tyToks dp alt = case alt of
Construct mi ts p _ -> case mi of
Just opId -> case p of
Total -> do
let sc = getConstrScheme dp p ts
nts <- mapM funType ts
-- extract overloaded opId number
return (transOpId env tyToks opId sc, case nts of
[TupleType l] -> map transFunType l
_ -> map transFunType nts)
Partial -> mkError "not a total constructor" opId
Nothing -> mkError "no support for data subtypes" ts
-- * Formulas
-- variables
transVar :: Set.Set String -> Id -> VName
transVar toks v = let
s = showIsaConstT v baseSign
renVar t = if Set.member t toks then renVar $ "X_" ++ t else t
in mkVName $ renVar s
mkTypedConst :: VName -> FunType -> Isa.Term
mkTypedConst v fTy = Isa.Const v $ Disp (transFunType fTy) NA Nothing
transTypedVar :: Set.Set String -> VarDecl -> Result Isa.Term
transTypedVar toks (VarDecl var ty _ _) = do
fTy <- funType ty
return $ mkTypedConst (transVar toks var) fTy
mkSimplifiedSen :: OldSimpKind -> Simplifier -> Isa.Term -> Isa.Sentence
mkSimplifiedSen simK simpF t = mkSen $ evalState (simplify simK simpF t) 0
isTrue :: Isa.Term -> Bool
isTrue t = case t of
Const n _ -> new n == cTrue
_ -> False
mkBinConj :: Isa.Term -> Isa.Term -> Isa.Term
mkBinConj t1 t2 = case isTrue of
isT | isT t1 -> t2
| isT t2 -> t1
_ -> binConj t1 t2
data OldSimpKind = NoSimpLift | Lift2Restrict | Lift2Case deriving Eq
data SimpKind = New | Old OldSimpKind deriving Eq
transSentence :: Env -> Set.Set String -> SimpKind -> Simplifier -> Le.Sentence
-> Result Isa.Sentence
transSentence sign tyToks simK simpF s = case s of
Le.Formula trm -> do
ITC ty t cs <- transTerm sign tyToks (simK == New)
(getAssumpsToks $ assumps sign) Set.empty trm
let et = case ty of
PartialVal UnitType -> mkTermAppl defOp t
_ -> t
bt = if isTrue et then cond2bool cs else
mkTermAppl (integrateCondInBool cs) et
st = mkSimplifiedSen (case simK of
Old osim -> osim
New -> NoSimpLift) simpF bt
case ty of
BoolType -> return st
PartialVal _ -> return st
FunType _ _ -> error "transSentence: FunType"
PairType _ _ -> error "transSentence: PairType"
TupleType _ -> error "transSentence: TupleType"
ApplType _ _ -> error "transSentence: ApplType"
_ -> return $ mkSen true
DatatypeSen ls -> if all (\ (DataEntry _ _ gk _ _ _) -> gk == Generated) ls
then transSentence sign tyToks simK simpF . Le.Formula
$ inductionScheme ls
else return $ mkSen true
ProgEqSen _ _ (ProgEq _ _ r) -> warning (mkSen true)
"translation of sentence not implemented" r
-- disambiguate operation names
transOpId :: Env -> Set.Set String -> Id -> TypeScheme -> VName
transOpId sign tyToks op ts@(TypeScheme _ ty _) =
let ga = globAnnos sign
Result _ mty = funType ty
in case mty of
Nothing -> error "transOpId"
Just fty ->
let args = isPlainFunType fty
in fromMaybe (error $ "transOpId " ++ show op) $ do
ops <- Map.lookup op (assumps sign)
if isSingleton ops then return $
mkIsaConstT (isPredType ty) ga args op baseSign tyToks
else do
i <- elemIndex ts $ map opType $ Set.toList ops
return $ mkIsaConstIT (isPredType ty)
ga args op (i + 1) baseSign tyToks
transLetEq :: Env -> Set.Set String -> Bool -> Set.Set String
-> Set.Set VarDecl -> ProgEq -> Result ((As.Term, Isa.Term), IsaTermCond)
transLetEq sign tyToks collectConds toks pVars (ProgEq pat trm r) = do
(_, op) <- transPattern sign tyToks toks pat
p@(ITC ty _ _) <- transTerm sign tyToks collectConds toks pVars trm
if isPartialVal ty && not (isQualVar pat) then fatal_error
("rhs must not be partial for a tuple currently: "
++ showDoc trm "") r
else return ((pat, op), p)
transLetEqs :: Env -> Set.Set String -> Bool -> Set.Set String
-> Set.Set VarDecl -> [ProgEq]
-> Result (Set.Set VarDecl, [(Isa.Term, IsaTermCond)])
transLetEqs sign tyToks collectConds toks pVars es = case es of
[] -> return (pVars, [])
e : r -> do
((pat, op), pt@(ITC ty _ _)) <-
transLetEq sign tyToks collectConds toks pVars e
(newPVars, newEs) <- transLetEqs sign tyToks collectConds toks
(if isPartialVal ty then Set.insert (getQualVar pat) pVars else pVars) r
return (newPVars, (op, pt) : newEs)
isQualVar :: As.Term -> Bool
isQualVar trm = case trm of
QualVar (VarDecl _ _ _ _) -> True
TypedTerm t _ _ _ -> isQualVar t
_ -> False
getQualVar :: As.Term -> VarDecl
getQualVar trm = case trm of
QualVar vd -> vd
TypedTerm t _ _ _ -> getQualVar t
_ -> error "getQualVar"
ifImplOp :: Isa.Term
ifImplOp = conDouble "ifImplOp"
unitOp :: Isa.Term
unitOp = Tuplex [] NotCont
noneOp :: Isa.Term
noneOp = conDouble "undefinedOp"
whenElseOp :: Isa.Term
whenElseOp = conDouble "whenElseOp"
resOp :: Isa.Term
resOp = conDouble "resOp"
makeTotal :: Isa.Term
makeTotal = conDouble "makeTotal"
uncurryOpS :: String
uncurryOpS = "uncurryOp"
curryOpS :: String
curryOpS = "curryOp"
uncurryOp :: Isa.Term
uncurryOp = conDouble uncurryOpS
curryOp :: Isa.Term
curryOp = conDouble curryOpS
for :: Int -> (a -> a) -> a -> a
for n f a = if n <= 0 then a else for (n - 1) f $ f a
data IsaTermCond = ITC FunType Isa.Term Cond
data Cond = None
| Cond Isa.Term
| CondList [Cond]
| PairCond Cond Cond
instance Show Cond where
show c = case c of
None -> "none"
Cond t -> show $ printTerm t
CondList l -> intercalate " & " $ map show l
PairCond p1 p2 -> '(' : shows p1 ", " ++ shows p2 ")"
joinCond :: Cond -> Cond -> Cond
joinCond c1 c2 = let
toCs c = case c of
CondList cs -> cs
None -> []
_ -> [c]
in case toCs c1 ++ toCs c2 of
[] -> None
[s] -> s
cs -> CondList cs
pairCond :: Cond -> Cond -> Cond
pairCond c1 c2 = case (c1, c2) of
(None, None) -> None
_ -> PairCond c1 c2
condToList :: Cond -> [Isa.Term]
condToList c = case c of
None -> []
Cond t -> [t]
CondList cs -> concatMap condToList cs
PairCond c1 c2 -> condToList c1 ++ condToList c2
{- pass tokens that must not be used as variable names and pass those
variables that are partial because they have been computed in a
let-term. -}
transTerm :: Env -> Set.Set String -> Bool -> Set.Set String
-> Set.Set VarDecl -> As.Term -> Result IsaTermCond
transTerm sign tyToks collectConds toks pVars trm = case trm of
QualVar vd@(VarDecl v t _ _) -> do
fTy <- funType t
let vt = con $ transVar toks v
return $ if Set.member vd pVars then ITC (makePartialVal fTy) vt None
else ITC fTy vt None
QualOp _ (PolyId opId _ _) ts@(TypeScheme targs ty _) insts _ _ -> do
fTy <- funType ty
instfTy <- funType $ substGen (if null insts then Map.empty else
Map.fromList $ zipWith (\ (TypeArg _ _ _ _ i _ _) t
-> (i, t)) targs insts) ty
let cf = mkTermAppl (convFun None $ instType fTy instfTy)
unCurry f = let rf = termAppl uncurryOp $ con f in
ITC fTy rf None
return $ case (opId ==) of
is | is trueId -> ITC fTy true None
| is falseId -> ITC fTy false None
| is botId -> case instfTy of
PartialVal t -> ITC t (termAppl makeTotal noneOp) $ Cond false
_ -> ITC instfTy (cf noneOp) None
| is andId -> unCurry conjV
| is orId -> unCurry disjV
| is implId -> unCurry implV
| is infixIf -> ITC fTy ifImplOp None
| is eqvId -> unCurry eqV
| is exEq -> let
ef = cf $ termAppl uncurryOp existEqualOp
in ITC instfTy ef None
| is eqId -> let
ef = cf $ termAppl uncurryOp $ con eqV
in ITC instfTy ef None
| is notId -> ITC fTy notOp None
| is defId -> ITC instfTy (cf defOp) None
| is whenElse -> ITC instfTy (cf whenElseOp) None
| is resId -> ITC instfTy (cf resOp) None
_ -> let
isaId = transOpId sign tyToks opId ts
ef = cf $ for (isPlainFunType fTy - 1) (termAppl uncurryOp)
$ if elem opId [injName, projName] then
mkTypedConst isaId instfTy
else con isaId
in ITC instfTy ef None
QuantifiedTerm quan varDecls phi _ -> do
let qname = case quan of
Universal -> allS
Existential -> exS
Unique -> ex1S
quantify phi' gvd = case gvd of
GenVarDecl vd -> do
vt <- transTypedVar toks vd
return $ termAppl (conDouble qname) $ Abs vt phi' NotCont
GenTypeVarDecl _ -> return phi'
ITC ty psi cs <- fmap integrateCond
$ transTerm sign tyToks collectConds toks pVars phi
psiR <- foldM quantify psi $ reverse varDecls
return $ ITC ty psiR cs
TypedTerm t _q _ty _ -> transTerm sign tyToks collectConds toks pVars t
LambdaTerm pats q body r -> do
p@(ITC ty _ ncs) <- transTerm sign tyToks collectConds toks pVars body
appendDiags $ case q of
Partial -> []
Total -> [Diag Warning
("partial lambda body in total abstraction: "
++ showDoc body "") r
| isPartialVal ty || not (isTrue $ cond2bool ncs) ]
foldM (abstraction sign tyToks toks) (integrateCond p)
$ reverse pats
LetTerm As.Let peqs body _ -> do
(nPVars, nEqs) <-
transLetEqs sign tyToks collectConds toks pVars peqs
ITC bTy bTrm defCs <-
transTerm sign tyToks collectConds toks nPVars body
let pEs = map (\ (p, ITC _ t _) -> (p, t)) nEqs
cs = foldl joinCond None $ map (\ (_, ITC _ _ c) -> c) nEqs
return $ ITC bTy (mkLetAppl pEs bTrm) $ joinCond cs defCs
TupleTerm ts@(_ : _) _ -> do
nTs <- mapM (transTerm sign tyToks collectConds toks pVars) ts
return $ foldl1 ( \ (ITC s p cs) (ITC t e cr) ->
ITC (PairType s t) (Tuplex [p, e] NotCont) $ pairCond cs cr) nTs
TupleTerm [] _ -> return $ ITC UnitType unitOp None
ApplTerm t1 t2 _ -> mkApp sign tyToks collectConds toks pVars t1 t2
_ -> fatal_error ("cannot translate term: " ++ showDoc trm "")
$ getRange trm
integrateCond :: IsaTermCond -> IsaTermCond
integrateCond (ITC ty trm cs) = if isTrue $ cond2bool cs then
ITC ty trm None
else case ty of
PartialVal _ -> ITC ty (mkTermAppl (integrateCondInPartial cs) trm) None
BoolType -> ITC ty (mkTermAppl (integrateCondInBool cs) trm) None
UnitType -> ITC BoolType (cond2bool cs) None
_ -> ITC (makePartialVal ty)
(mkTermAppl (integrateCondInTotal cs) trm) None
-- return partial result type
instType :: FunType -> FunType -> ConvFun
instType f1 f2 = case (f1, f2) of
(TupleType l1, _) -> instType (foldl1 PairType l1) f2
(_, TupleType l2) -> instType f1 $ foldl1 PairType l2
(PartialVal (TypeVar _), BoolType) -> Partial2bool True
(PairType a c, PairType b d) ->
let c2 = instType c d
c1 = instType a b
in mkCompFun (mkMapFun MapSnd c2) $ mkMapFun MapFst c1
(FunType a c, FunType b d) ->
let c2 = instType c d
c1 = instType a b
in mkCompFun (mkResFun c2) $ mkArgFun $ invertConv c1
_ -> IdOp
invertConv :: ConvFun -> ConvFun
invertConv c = case c of
Partial2bool _ -> Bool2partial False
Bool2partial _ -> Partial2bool False
Unit2bool _ -> Bool2unit
Bool2unit -> Unit2bool False
MkPartial _ -> MkTotal
MkTotal -> MkPartial False
MapFun mv cf -> mkMapFun mv $ invertConv cf
ResFun cf -> mkResFun $ invertConv cf
ArgFun cf -> mkArgFun $ invertConv cf
CompFun c1 c2 -> mkCompFun (invertConv c2) (invertConv c1)
_ -> IdOp
data MapFun = MapFst | MapSnd | MapPartial deriving Show
data LiftFun = LiftFst | LiftSnd deriving Show
{- the additional Bool indicates condition integration
Bool2bool and Partial2partial must be mapped to IdOp
if the conditions should be ignored.
Bool2Unit and MkTotal can propagate out conditions -}
data ConvFun =
IdOp
| Bool2partial Bool
| Partial2bool Bool
| Bool2bool
| Unit2bool Bool
| Bool2unit
| Partial2partial
| MkPartial Bool
| MkTotal
| CompFun ConvFun ConvFun
| MapFun MapFun ConvFun
| LiftFun LiftFun ConvFun
| LiftUnit FunType
| LiftPartial FunType
| ResFun ConvFun
| ArgFun ConvFun
deriving Show
isNotIdOp :: ConvFun -> Bool
isNotIdOp f = case f of
IdOp -> False
_ -> True
mkCompFun :: ConvFun -> ConvFun -> ConvFun
mkCompFun f1 f2 = case f1 of
IdOp -> f2
_ -> case f2 of
IdOp -> f1
_ -> CompFun f1 f2
mkMapFun :: MapFun -> ConvFun -> ConvFun
mkMapFun m f = case f of
IdOp -> IdOp
_ -> MapFun m f
mkLiftFun :: LiftFun -> ConvFun -> ConvFun
mkLiftFun lv c = case c of
IdOp -> IdOp
_ -> LiftFun lv c
mapFun :: MapFun -> Isa.Term
mapFun mf = case mf of
MapFst -> mapFst
MapSnd -> mapSnd
MapPartial -> mapPartial
compOp :: Isa.Term
compOp = con compV
convFun :: Cond -> ConvFun -> Isa.Term
convFun cnd cvf = case cvf of
IdOp -> idOp
Bool2partial b -> if b
then metaComp bool2partial $ integrateCondInBool cnd
else bool2partial
Partial2bool b -> if b
then metaComp (integrateCondInBool cnd) defOp
else defOp
Bool2bool -> integrateCondInBool cnd
Unit2bool b -> if b
then metaComp (integrateCondInBool cnd) constTrue else constTrue
Bool2unit -> constNil
Partial2partial -> integrateCondInPartial cnd
MkPartial b -> if b
then integrateCondInTotal cnd
else mkPartial
MkTotal -> makeTotal
LiftUnit rTy -> case rTy of
UnitType -> liftUnit2unit
BoolType -> liftUnit2bool
PartialVal _ -> liftUnit2partial
_ -> liftUnit
LiftPartial rTy ->
case rTy of
UnitType -> lift2unit
BoolType -> lift2bool
PartialVal _ -> lift2partial
_ -> mapPartial
CompFun f1 f2 -> metaComp (convFun cnd f1) $ convFun cnd f2
MapFun mf cv -> mkTermAppl (mapFun mf) $ convFun cnd cv
LiftFun lf cv -> let ccv = convFun cnd cv in case lf of
LiftFst -> metaComp (metaComp uncurryOp flipOp)
$ metaComp (metaComp (mkTermAppl compOp ccv) flipOp)
curryOp
LiftSnd -> metaComp uncurryOp $ metaComp (mkTermAppl compOp ccv)
curryOp
ArgFun cv -> mkTermAppl (termAppl flipOp compOp) $ convFun cnd cv
ResFun cv -> mkTermAppl compOp $ convFun cnd cv
mapFst, mapSnd, mapPartial, idOp, bool2partial, constNil, constTrue,
liftUnit2unit, liftUnit2bool, liftUnit2partial, liftUnit, lift2unit,
lift2bool, lift2partial, mkPartial, restrict :: Isa.Term
mapFst = conDouble "mapFst"
mapSnd = conDouble "mapSnd"
mapPartial = conDouble "mapPartial"
idOp = conDouble "id"
bool2partial = conDouble "bool2partial"
constNil = conDouble "constNil"
constTrue = conDouble "constTrue"
liftUnit2unit = conDouble "liftUnit2unit"
liftUnit2bool = conDouble "liftUnit2bool"
liftUnit2partial = conDouble "liftUnit2partial"
liftUnit = conDouble "liftUnit"
lift2unit = conDouble "lift2unit"
lift2bool = conDouble "lift2bool"
lift2partial = conDouble "lift2partial"
mkPartial = conDouble "makePartial"
restrict = conDouble "restrictOp"
existEqualOp :: Isa.Term
existEqualOp =
con $ VName "existEqualOp" $ Just $ AltSyntax "(_ =e=/ _)" [50, 51] 50
integrateCondInBool :: Cond -> Isa.Term
integrateCondInBool c = let b = cond2bool c in
if isTrue b then idOp else mkTermAppl (con conjV) b
integrateCondInPartial :: Cond -> Isa.Term
integrateCondInPartial c = let b = cond2bool c in
if isTrue b then idOp else
mkTermAppl (mkTermAppl flipOp restrict) b
metaComp :: Isa.Term -> Isa.Term -> Isa.Term
metaComp = mkTermAppl . mkTermAppl compOp
integrateCondInTotal :: Cond -> Isa.Term
integrateCondInTotal c = metaComp (integrateCondInPartial c) mkPartial
addCond :: Isa.Term -> Cond -> Cond
addCond = joinCond . Cond
cond2bool :: Cond -> Isa.Term
cond2bool c = case nub $ condToList c of
[] -> true
ncs -> foldr1 mkBinConj ncs
{- adjust actual argument to expected argument type of function
considering a definedness conditions -}
adjustArgType :: FunType -> FunType -> Result ConvFun
adjustArgType aTy ty = case (aTy, ty) of
(TupleType l, _) -> adjustArgType (foldl1 PairType l) ty
(_, TupleType l) -> adjustArgType aTy $ foldl1 PairType l
(BoolType, BoolType) -> return Bool2bool
(UnitType, UnitType) -> return IdOp
(PartialVal UnitType, BoolType) -> return $ Bool2partial True
(BoolType, PartialVal UnitType) -> return $ Partial2bool True
(UnitType, BoolType) -> return Bool2unit
(BoolType, UnitType) -> return $ Unit2bool True
(PartialVal a, PartialVal b) -> do
c <- adjustArgType a b
return $ mkCompFun Partial2partial c
(a, PartialVal b) -> do
c <- adjustArgType a b
return $ mkCompFun MkTotal c
(PartialVal a, b) -> do
c <- adjustArgType a b
return $ mkCompFun (MkPartial True) c
(PairType e1 e2, PairType a1 a2) -> do
c1 <- adjustArgType e1 a1
c2 <- adjustArgType e2 a2
return . mkCompFun (mkMapFun MapSnd c2) $ mkMapFun MapFst c1
(FunType a b, FunType c d) -> do
aC <- adjustArgType a c -- function a -> c (a fixed)
dC <- adjustArgType b d -- function d -> b (b fixed)
{- (d -> b) o (c -> d) o (a -> c) :: a -> b
do not integrate cond treatment via invertConv . invertConv -}
return . mkCompFun (mkResFun . invertConv $ invertConv dC)
. mkArgFun $ invertConv aC
(TypeVar _, _) -> return IdOp
(_, TypeVar _) -> return IdOp
(ApplType i1 l1, ApplType i2 l2) | i1 == i2 && length l1 == length l2 -> do
l <- mapM (uncurry adjustArgType) $ zip l1 l2
if any (isNotIdOp . invertConv) l
then fail "cannot adjust type application"
else return IdOp
_ -> fail $ "cannot adjust argument type\n" ++ show (aTy, ty)
unpackOp :: Isa.Term -> Bool -> Bool -> FunType -> ConvFun -> Isa.Term
unpackOp fTrm isPf pfTy ft fConv = let isaF = convFun None fConv in
if isPf then mkTermAppl
(mkTermAppl (conDouble $ case if pfTy then makePartialVal ft else ft of
UnitType -> "unpack2bool"
BoolType -> "unpackBool"
PartialVal _ -> "unpackPartial"
_ -> "unpack2partial") isaF) fTrm
else mkTermAppl isaF fTrm
-- True means function type result was partial
adjustMkApplOrig :: Isa.Term -> Cond -> Bool -> FunType -> FunType
-> IsaTermCond -> Result IsaTermCond
adjustMkApplOrig fTrm fCs isPf aTy rTy (ITC ty aTrm aCs) = do
((pfTy, fConv), (_, aConv)) <- adjustTypes aTy rTy ty
return . ITC (if isPf || pfTy then makePartialVal rTy else rTy)
(mkTermAppl (unpackOp fTrm isPf pfTy rTy fConv)
$ mkTermAppl (convFun None aConv) aTrm) $ joinCond fCs aCs
-- True means require result type to be partial
adjustTypes :: FunType -> FunType -> FunType
-> Result ((Bool, ConvFun), (FunType, ConvFun))
adjustTypes aTy rTy ty = case (aTy, ty) of
(TupleType l, _) -> adjustTypes (foldl1 PairType l) rTy ty
(_, TupleType l) -> adjustTypes aTy rTy $ foldl1 PairType l
(BoolType, BoolType) -> return ((False, IdOp), (ty, IdOp))
(UnitType, UnitType) -> return ((False, IdOp), (ty, IdOp))
(PartialVal _, BoolType) ->
return ((False, IdOp), (aTy, Bool2partial False))
(BoolType, PartialVal _) ->
return ((False, IdOp), (aTy, Partial2bool False))
(_, BoolType) -> return ((True, LiftUnit rTy), (ty, IdOp))
(BoolType, _) -> return ((False, IdOp), (aTy, Unit2bool False))
(PartialVal a, PartialVal b) -> do
q@(fp, (argTy, aTrm)) <- adjustTypes a rTy b
return $ case argTy of
PartialVal _ -> q
_ -> (fp, (PartialVal argTy, mkMapFun MapPartial aTrm))
(a, PartialVal b) -> do
q@(_, ap@(argTy, _)) <- adjustTypes a rTy b
return $ case argTy of
PartialVal _ -> q
_ -> ((True, LiftPartial rTy), ap)
(PartialVal a, b) -> do
q@(fp, (argTy, aTrm)) <- adjustTypes a rTy b
return $ case argTy of
PartialVal _ -> q
_ -> (fp, (PartialVal argTy, mkCompFun (MkPartial False) aTrm))
(PairType a c, PairType b d) -> do
((res2Ty, f2), (arg2Ty, a2)) <- adjustTypes c rTy d
((res1Ty, f1), (arg1Ty, a1)) <- adjustTypes a
(if res2Ty then makePartialVal rTy else rTy) b
return ((res1Ty || res2Ty,
mkCompFun (mkLiftFun LiftFst f1) $ mkLiftFun LiftSnd f2),
(PairType arg1Ty arg2Ty,
mkCompFun (mkMapFun MapSnd a2) $ mkMapFun MapFst a1))
(FunType a c, FunType b d) -> do
((_, aF), (aT, aC)) <- adjustTypes b c a
((cB, cF), (dT, dC)) <- adjustTypes c rTy d
if cB || isNotIdOp cF
then fail "cannot adjust result types of function type"
else return ((False, IdOp), (FunType aT dT,
mkCompFun aF $ mkCompFun (mkResFun dC) $ mkArgFun aC))
(TypeVar _, _) -> return ((False, IdOp), (ty, IdOp))
(_, TypeVar _) -> return ((False, IdOp), (aTy, IdOp))
(ApplType i1 l1, ApplType i2 l2) | i1 == i2 && length l1 == length l2 -> do
l <- mapM (\ (a, b) -> adjustTypes a rTy b) $ zip l1 l2
if any (fst . fst) l || any (isNotIdOp . snd . snd) l
then fail "cannot adjust type application"
else return ((False, IdOp), (ApplType i1 $ map (fst . snd) l, IdOp))
_ -> fail $ "cannot adjust types\n" ++ show (aTy, ty)
adjustMkAppl :: Isa.Term -> Cond -> Bool -> FunType -> FunType
-> IsaTermCond -> Result IsaTermCond
adjustMkAppl fTrm fCs isPf aTy rTy (ITC ty aTrm aCs) = do
aConv <- adjustArgType aTy ty
let (natrm, nacs) = applConv aConv (aTrm, aCs)
(nftrm, nfcs) = if isPf
then (mkTermAppl makeTotal fTrm, addCond (mkTermAppl defOp fTrm) fCs)
else (fTrm, fCs)
return $ ITC rTy (mkTermAppl nftrm natrm) $ joinCond nfcs nacs
applConv :: ConvFun -> (Isa.Term, Cond) -> (Isa.Term, Cond)
applConv cnv (t, c) = let
rt = mkTermAppl (convFun c cnv) t
r = (rt, c)
rb = (rt, None)
in case cnv of
IdOp -> (t, c)
Bool2partial b -> if b then rb else r
Partial2bool b -> if b then rb else r
Bool2bool -> rb
Unit2bool b -> if b then rb else r
Bool2unit -> (rt, addCond t c)
Partial2partial -> rb
MkPartial b -> if b then rb else r
MkTotal -> (rt, addCond (mkTermAppl defOp t) c)
CompFun f1 f2 -> applConv f1 $ applConv f2 (t, c)
MapFun mf cv -> case t of
Tuplex [t1, t2] _ -> let
(c1, c2) = case c of
PairCond p1 p2 -> (p1, p2)
_ -> (c, c)
in case mf of
MapFst -> let
(nt1, nc1) = applConv cv (t1, c1)
in (Tuplex [nt1, t2] NotCont, PairCond nc1 c2)
MapSnd -> let
(nt2, nc2) = applConv cv (t2, c2)
in (Tuplex [t1, nt2] NotCont, PairCond c1 nc2)
MapPartial -> r
_ -> r
_ -> r
mkArgFun :: ConvFun -> ConvFun
mkArgFun c = case c of
IdOp -> c
Bool2bool -> c
Partial2partial -> c
_ -> ArgFun c
mkResFun :: ConvFun -> ConvFun
mkResFun c = case c of
IdOp -> c
Bool2bool -> c
Partial2partial -> c
_ -> ResFun c
isEquallyLifted :: Isa.Term -> Isa.Term -> Maybe (Isa.Term, Isa.Term, Isa.Term)
isEquallyLifted l r = case (l, r) of
(App ft@(Const f _) la _,
App (Const g _) ra _)
| f == g && elem (new f) ["makePartial", "bool2partial"]
-> Just (ft, la, ra)
_ -> Nothing
isLifted :: Isa.Term -> Bool
isLifted t = case t of
App (Const f _) _ _ | new f == "makePartial" -> True
_ -> False
splitArg :: Isa.Term -> (Isa.Term, Isa.Term)
splitArg arg = case arg of
App (App (Const n _) p _) b _ | new n == "restrictOp" ->
case p of
App (Const pp _) t _ | new pp == "makePartial"
-> (b, t)
_ -> (mkBinConj b $ mkTermAppl defOp p, mkTermAppl makeTotal p)
_ -> (mkTermAppl defOp arg, mkTermAppl makeTotal arg)
flipS :: String
flipS = "flip"
flipOp :: Isa.Term
flipOp = conDouble flipS
mkTermAppl :: Isa.Term -> Isa.Term -> Isa.Term
mkTermAppl fun arg = case (fun, arg) of
(App (Const uc _) b _, Tuplex [l, r] _) | new uc == uncurryOpS ->
let res = mkTermAppl (mkTermAppl b l) r in case b of
Const bin _ | elem (new bin) [eq, "existEqualOp"] ->
case isEquallyLifted l r of
Just (_, la, ra) -> mkTermAppl (mkTermAppl (con eqV) la) ra
_ -> if isLifted l || isLifted r
then mkTermAppl (mkTermAppl (con eqV) l) r
else let
(lb, lt) = splitArg l
(rb, rt) = splitArg r
in if new bin == "existEqualOp" then
mkBinConj lb $ mkBinConj rb
$ mkTermAppl (mkTermAppl (con eqV) lt) rt
else res
_ -> res
(App (Const mp _) f _, Tuplex [a, b] c)
| new mp == "mapFst" -> Tuplex [mkTermAppl f a, b] c
| new mp == "mapSnd" -> Tuplex [a, mkTermAppl f b] c
(Const mp _, Tuplex [a, b] _)
| new mp == "ifImplOp" -> binImpl b a
(Const mp _, Tuplex [Tuplex [a, b] _, c] d)
| new mp == "whenElseOp" -> case isEquallyLifted a c of
Just (f, na, nc) -> mkTermAppl f $ If b na nc d
Nothing -> If b a c d
(App (Const mp _) f _, App (Const mp2 _) arg2 _)
| new mp == "mapPartial" && new mp2 == "makePartial" ->
mkTermAppl mkPartial $ mkTermAppl f arg2
(App (Const mp _) f c, _)
| new mp == "liftUnit2bool" -> let af = mkTermAppl f unitOp in
case arg of
Const ma _ | isTrue arg -> af
| new ma == cFalse -> false
_ -> If arg af false c
| new mp == "liftUnit2partial" -> let af = mkTermAppl f unitOp in
case arg of
Const ma _ | isTrue arg -> af
| new ma == cFalse -> noneOp
_ -> If arg af noneOp c
(App (Const mp _) _ _, _)
| new mp == "liftUnit2unit" -> arg
| new mp == "lift2unit" -> mkTermAppl defOp arg
(App (App (Const cmp _) f _) g c, _)
| new cmp == compS -> mkTermAppl f $ mkTermAppl g arg
| new cmp == curryOpS -> mkTermAppl f $ Tuplex [g, arg] c
| new cmp == flipS -> mkTermAppl (mkTermAppl f arg) g
(Const d _, App (Const sm _) a _)
| new d == defOpS && new sm == "makePartial" -> true
| new d == defOpS && new sm == "bool2partial"
|| new d == "bool2partial" && new sm == defOpS -> a
| new d == curryOpS && new sm == uncurryOpS -> a
(Const i _, _)
| new i == "bool2partial" ->
let tc = mkTermAppl mkPartial unitOp
in case arg of
Const j _ | isTrue arg -> tc
| new j == cFalse -> noneOp
_ -> termAppl fun arg -- If arg tc noneOp NotCont
| new i == "id" -> arg
| new i == "constTrue" -> true
| new i == "constNil" -> unitOp
(Const i _, Tuplex [] _)
| new i == defOpS -> false
_ -> termAppl fun arg
freshIndex :: State Int Int
freshIndex = do
i <- get
put $ i + 1
return i
type Simplifier = VName
-> Isa.Term -- variable
-> Isa.Term -- simplified application to variable
-> Isa.Term -- simplified argument
-> State Int Isa.Term
simpForOption :: Simplifier
simpForOption l v nF nArg =
return $ Case nArg
[ (conDouble "None", if new l == "lift2bool" then false else noneOp)
, (termAppl conSome v,
if new l == "mapPartial" then mkTermAppl mkPartial nF else nF)]
mkLetAppl :: [(Isa.Term, Isa.Term)] -> Isa.Term -> Isa.Term
mkLetAppl eqs inTrm = case inTrm of
App (Const mp _) arg _ | new mp == "makePartial" ->
mkTermAppl mkPartial $ Isa.Let eqs arg
_ -> Isa.Let eqs inTrm
simpForPairs :: Simplifier
simpForPairs l v2 nF nArg = do
n <- freshIndex
let v1 = mkFree $ "Xb" ++ show n
return $ mkLetAppl [(Tuplex [v1, v2] NotCont, nArg)] $
If v1 (if new l == "mapPartial" then mkTermAppl mkPartial nF else nF)
(if new l == "lift2bool" then false else noneOp) NotCont
simplify :: OldSimpKind -> Simplifier -> Isa.Term -> State Int Isa.Term
simplify simK simpF trm = case trm of
App (App (Const l _) f _) arg _
| simK /= NoSimpLift && elem (new l)
["lift2bool", "lift2partial", "mapPartial"] -> do
nArg <- simplify simK simpF arg
let lf = new l
res = simK == Lift2Restrict
if res && lf == "lift2partial" then return . mkTermAppl
(mkTermAppl restrict . mkTermAppl f $ mkTermAppl makeTotal nArg)
$ mkTermAppl defOp nArg
else if res && lf == "mapPartial" then return . mkTermAppl
(mkTermAppl restrict . mkTermAppl mkPartial
. mkTermAppl f $ mkTermAppl makeTotal nArg)
$ mkTermAppl defOp nArg
else do
n <- freshIndex
let pvar = mkFree $ "Xc" ++ show n
nF <- simplify simK simpF $ mkTermAppl f pvar
simpF l pvar nF nArg
App f arg c -> do
nF <- simplify simK simpF f
nArg <- simplify simK simpF arg
return $ App nF nArg c
Abs v t c -> do
nT <- simplify simK simpF t
return $ Abs v nT c
_ -> return trm
mkApp :: Env -> Set.Set String -> Bool -> Set.Set String
-> Set.Set VarDecl -> As.Term -> As.Term -> Result IsaTermCond
mkApp sign tyToks collectConds toks pVars f arg = do
fTr@(ITC fTy fTrm fCs) <-
transTerm sign tyToks collectConds toks pVars f
aTr <- transTerm sign tyToks collectConds toks pVars arg
let pv = case arg of -- dummy application of a unit argument
TupleTerm [] _ -> return fTr
_ -> mkError "wrong function type" f
adjstAppl = if collectConds then adjustMkAppl else adjustMkApplOrig
adjustPos (getRange [f, arg]) $ case fTy of
FunType a r -> adjstAppl fTrm fCs False a r aTr
PartialVal (FunType a r) -> adjstAppl fTrm fCs True a r aTr
PartialVal _ -> pv
BoolType -> pv
_ -> mkError "not a function type" f
-- * translation of lambda abstractions
isPatternType :: As.Term -> Bool
isPatternType trm = case trm of
QualVar (VarDecl _ _ _ _) -> True
TypedTerm t _ _ _ -> isPatternType t
TupleTerm ts _ -> all isPatternType ts
_ -> False
transPattern :: Env -> Set.Set String -> Set.Set String -> As.Term
-> Result (FunType, Isa.Term)
transPattern sign tyToks toks pat = do
ITC ty trm cs <- transTerm sign tyToks False toks Set.empty pat
case pat of
TupleTerm [] _ -> return (ty, mkFree "_")
_ -> if not (isPatternType pat) || isPartialVal ty
|| case cs of
None -> False
_ -> True then
fatal_error ("illegal pattern for Isabelle: " ++ showDoc pat "")
$ getRange pat
else return (ty, trm)
-- form Abs(pattern term)
abstraction :: Env -> Set.Set String -> Set.Set String
-> IsaTermCond -> As.Term -> Result IsaTermCond
abstraction sign tyToks toks (ITC ty body cs) pat = do
(pTy, nPat) <- transPattern sign tyToks toks pat
return $ ITC (FunType pTy ty) (Abs nPat body NotCont) cs
| nevrenato/Hets_Fork | Comorphisms/PPolyTyConsHOL2IsaUtils.hs | gpl-2.0 | 40,408 | 6 | 27 | 12,356 | 14,671 | 7,274 | 7,397 | 932 | 27 |
module TypeCheck(typeCheck,
Context, VariableName(..), Type(..), TypeVariable(..))
where
import Data.Char
import Data.Either
import Data.List
import Data.Maybe
import qualified Data.Map as M
import qualified Data.Set as S
import Control.Applicative
import Control.Monad
import Control.Monad.State
import Control.Monad.Except
import Stau
import StauTypes
type TypeCheckMonad = Either String
newtype VariableName = VariableName { unVariableName :: String }
deriving (Show, Eq, Ord)
data Type = TypeVariable TypeVariable
| IntType
| BoolType
| Custom String
| FunType [Type] Type
deriving (Eq, Ord)
instance Show Type where
show (TypeVariable (TV f i n)) = f ++ "_" ++ i : show n
show IntType = "Int"
show BoolType = "Bool"
show (Custom n) = n
show (FunType es e) = "(" ++ intercalate " -> " (map show (es ++ [e])) ++ ")"
type Context = M.Map VariableName Type
type Constraint = M.Map TypeVariable Type
data TypeVariable = TV String Char Int
deriving (Show, Eq, Ord)
data FunCheckState = FunCheckState {
typevariable :: TypeVariable
, context :: Context
, constructormap :: ConstructorMap
, constraints :: Constraint
}
-- helper functions
type ConstructorMap = M.Map String (Type, Constructor)
constructorMap :: [DataDecl] -> ConstructorMap
constructorMap decls =
buildMapsFrom (constructorName . snd)
(map (\(a, b) -> (Custom (dataDeclName a), b)) . pair $ assocsBy dataConstructors decls)
tcError :: String -> String -> TypeCheckMonad a
tcError name msg = throwError $ msg ++ ": `" ++ name ++ "'"
createMapFrom :: (Ord k) => (a -> k) -> (a -> b) -> [a] -> M.Map k b
createMapFrom f g xs = M.fromList $ zip (map f xs) (map g xs)
-- entry
typeCheck :: Module -> TypeCheckMonad Context
typeCheck m = do
globalContext <- initialModuleContext m
-- TODO: warn if user overrides prelude
-- TODO: check consmap validity
let consmap = constructorMap (moduleDataDecls m)
consprelude = M.fromList [("True", (BoolType, Constructor "True" [])),
("False", (BoolType, Constructor "False" []))]
consmap' = M.union consprelude consmap
context <$> flip execStateT (FunCheckState undefined globalContext consmap' M.empty) (do
forM_ (moduleFunctions m) $ \fun -> do
modify $ \s -> s{typevariable = TV (getFunName fun) 'a' 1}
ft <- runTypecheck fun
addConstraint (TV (getFunName fun) 'a' 0) ft
unify)
unifyType :: (TypeVariable, Type) -> StateT FunCheckState TypeCheckMonad ()
unifyType (tv, t) = do
ctxt <- context <$> get
forM_ (M.toList ctxt) (specifyType (tv, t))
specifyType :: (TypeVariable, Type) -> (VariableName, Type) -> StateT FunCheckState TypeCheckMonad ()
specifyType (tv, t) (vn, t'@(TypeVariable tv2)) =
when (tv2 == tv) $ do
nt <- unifyTypes t t'
modify $ \s -> s{context = M.insert vn nt (context s)}
specifyType (tv, t) (vn, FunType ps r) = do
r' <- case r of
TypeVariable tv2 ->
if tv2 == tv then unifyTypes t r else return r
_ -> return r
ps' <- forM ps $ \p -> case p of
TypeVariable tv2 ->
if tv2 == tv
then unifyTypes t p
else return p
_ -> return p
modify $ \s -> s{context = M.insert vn (FunType ps' r') (context s)}
specifyType _ _ = return ()
unifyTypes :: Type -> Type -> StateT FunCheckState TypeCheckMonad Type
unifyTypes t1 (TypeVariable _) = return t1
unifyTypes (TypeVariable _) t2 = return t2
unifyTypes (FunType p1 r1) (FunType p2 r2) = do
r <- unifyTypes r1 r2
ps <- zipWithM unifyTypes p1 p2
return $ FunType ps r
unifyTypes t1 t2
| t1 /= t2 = typeError "" t1 t2
| otherwise = return t2
unify :: StateT FunCheckState TypeCheckMonad ()
unify = do
cons <- constraints <$> get
mapM_ unifyType (M.toList cons)
typeError :: String -> Type -> Type -> StateT FunCheckState TypeCheckMonad a
typeError "" t1 t2 = throwError $ "expected `" ++ show t2 ++ "', inferred `" ++ show t1 ++ "'"
typeError name t1 t2 = throwError $ "on definition of `" ++ name ++ "': expected `" ++ show t2 ++ "', inferred `" ++ show t1 ++ "'"
initialModuleContext :: Module -> TypeCheckMonad Context
initialModuleContext m = do
funs <- createMapFrom fst snd <$> mapM initialContext (moduleFunctions m)
sigs <- createMapFrom fst snd <$> mapM initialSigContext (moduleSignatures m)
-- TODO: improve this error message
unless (S.null $ M.keysSet sigs S.\\ M.keysSet funs) $
throwError "Signature without function declaration"
return $ M.union sigs funs
initialFunTV :: Function -> TypeVariable
initialFunTV fun = TV (getFunName fun) 'a' 0
initialContext :: Function -> TypeCheckMonad (VariableName, Type)
initialContext fun = return (VariableName (getFunName fun), TypeVariable $ initialFunTV fun)
initialSigContext :: FunSig -> TypeCheckMonad (VariableName, Type)
initialSigContext funsig = do
types <- mapM (sigTypeToType (getFunSigName funsig)) (getFunSigTypes funsig)
ctxttype <- case types of
[] -> tcError (getFunSigName funsig) "Invalid type signature"
[x] -> return x
ts -> return $ FunType (init ts) (last ts)
return (VariableName (getFunSigName funsig), ctxttype)
-- TODO: function types
sigTypeToType :: String -> String -> TypeCheckMonad Type
sigTypeToType _ "Int" = return IntType
sigTypeToType _ "Bool" = return BoolType
sigTypeToType _ [] = throwError "Invalid type signature"
sigTypeToType fn xs | isLower (head xs) = return $ TypeVariable $ TV (fn ++ "_" ++ xs) (head xs) 0
| otherwise = return $ Custom xs
runTypecheck :: Function -> StateT FunCheckState TypeCheckMonad Type
runTypecheck fun = do
prevctxt <- context <$> get
paramtypes <- mapM paramType (getFunArgs fun)
funt <- expType (getFunExp fun)
paramtypes' <- zipWithM fetchParamType (getFunArgs fun) paramtypes
updContext prevctxt
funType paramtypes' funt
updContext :: Context -> StateT FunCheckState TypeCheckMonad ()
updContext ctxt = do
s <- get
put (s{context = ctxt})
fetchParamType :: ParamDecl -> Type -> StateT FunCheckState TypeCheckMonad Type
fetchParamType (VariableParam n) def = do
ctxt <- context <$> get
case M.lookup (VariableName n) ctxt of
Nothing -> return def
Just t' -> return t'
fetchParamType _ def = return def
funType :: [Type] -> Type -> StateT FunCheckState TypeCheckMonad Type
funType paramtypes t =
return $ mkFunType paramtypes t
mkFunType :: [Type] -> Type -> Type
mkFunType [] t = t
mkFunType ps t = FunType ps t
paramType :: ParamDecl -> StateT FunCheckState TypeCheckMonad Type
paramType (VariableParam n) = do
ntv <- nextTypeVariable
addToContext n (TypeVariable ntv)
paramType (ConstructorParam sn params) = do
consmap <- constructormap <$> get
case M.lookup sn consmap of
Nothing -> throwError $ "Not in scope: `" ++ sn ++ "'"
Just (dt, ct) -> do
types <- mapM typeNameToType (dataFieldTypes ct)
ptypes <- mapM paramType params
when (length types /= length ptypes) $
throwError $ "Invalid data fields for `" ++ sn ++ "'"
zipWithM_ checkType types ptypes
return dt
paramType WildcardParam = fmap TypeVariable nextTypeVariable
getParamType :: ConstructorMap -> ParamDecl -> Either String (Maybe Type)
getParamType _ WildcardParam = Right Nothing
getParamType _ (VariableParam _) = Right Nothing
getParamType consmap (ConstructorParam sn params) =
case M.lookup sn consmap of
Nothing -> Left $ "Not in scope: `" ++ sn ++ "'"
Just (dt, ct) -> if length params == length (dataFieldTypes ct)
then do
mapM_ (getParamType consmap) params
return $ Just dt
else Left $ "Invalid parameters for constructor `" ++ constructorName ct ++ "'"
nextTypeVariable :: (Functor m, Monad m) => StateT FunCheckState m TypeVariable
nextTypeVariable = do
tv <- typevariable <$> get
modify $ \f -> f{typevariable = incTypeVariable (typevariable f)}
return tv
incTypeVariable :: TypeVariable -> TypeVariable
incTypeVariable (TV fn 't' n) = TV fn 't' (succ n)
incTypeVariable (TV fn c n) = TV fn (succ c) n
addToContext :: String -> Type -> StateT FunCheckState TypeCheckMonad Type
addToContext tv t = do
ctxt <- context <$> get
case M.lookup (VariableName tv) ctxt of
Nothing -> do
modify $ \s -> s{context = M.insert (VariableName tv) t ctxt}
return t
-- TODO: allow shadowing
Just _ -> throwError $ "Shadowing variable `" ++ tv ++ "'"
-- No check for overriding for now.
addConstraint :: TypeVariable -> Type -> StateT FunCheckState TypeCheckMonad ()
addConstraint tv t = do
cons <- constraints <$> get
case M.lookup tv cons of
Just t' -> unless (TypeVariable tv == t') (checkType t t')
Nothing ->
modify $ \s -> s{constraints = M.insert tv t (constraints s)}
checkType :: Type -> Type -> StateT FunCheckState TypeCheckMonad ()
checkType (TypeVariable tv) t2 = addConstraint tv t2
checkType t1 (TypeVariable tv) = addConstraint tv t1
checkType t1@(FunType p1 r1) t2@(FunType p2 r2) = do
zipWithM_ checkType p1 p2
when (length p1 /= length p2) $ typeError "" t1 t2
checkType r1 r2
checkType t1 t2 | t1 == t2 = return ()
| otherwise = typeError "" t1 t2
expTypeNum :: Exp -> Exp -> StateT FunCheckState TypeCheckMonad Type
expTypeNum e1 e2 = do
et1 <- expType e1
et2 <- expType e2
checkType et1 IntType
checkType et2 IntType
return IntType
expTypeComp :: Exp -> Exp -> StateT FunCheckState TypeCheckMonad Type
expTypeComp e1 e2 = do
et1 <- expType e1
et2 <- expType e2
checkType et1 IntType
checkType et2 IntType
return BoolType
expType :: Exp -> StateT FunCheckState TypeCheckMonad Type
expType (Plus e1 e2) = expTypeNum e1 e2
expType (Minus e1 e2) = expTypeNum e1 e2
expType (Times e1 e2) = expTypeNum e1 e2
expType (Div e1 e2) = expTypeComp e1 e2
expType (CmpEq e1 e2) = expTypeComp e1 e2
expType (CmpLt e1 e2) = expTypeComp e1 e2
expType (CmpLe e1 e2) = expTypeComp e1 e2
expType (Int _) = return IntType
expType (Variable n) = do
ctxt <- context <$> get
case M.lookup (VariableName n) ctxt of
Nothing -> throwError $ "Not in scope: `" ++ n ++ "'"
Just t -> return t
expType (FunApp n []) = do
ctxt <- context <$> get
case M.lookup (VariableName n) ctxt of
Nothing -> throwError $ "Not in scope: `" ++ n ++ "'"
Just t -> return t
expType (FunApp n es) = do
etypes <- mapM expType es
ctxt <- context <$> get
rettype <- nextTypeVariable
let funtype = FunType etypes (TypeVariable rettype)
case M.lookup (VariableName n) ctxt of
Nothing -> throwError $ "Not in scope: `" ++ n ++ "'"
Just (TypeVariable p) -> do
-- TODO: add constraints to function type?
addConstraint p funtype
return (TypeVariable rettype)
Just t@(FunType params ret) -> do
zipWithM_ checkType etypes params
-- TODO: currying?
when (length params /= length es) $
typeError n funtype t
return ret
Just t -> typeError n funtype t
expType (DataCons n es) = do
consmap <- constructormap <$> get
case M.lookup n consmap of
Nothing -> throwError $ "Not in scope: `" ++ n ++ "'"
Just (dt, ct) -> do
types <- mapM typeNameToType (dataFieldTypes ct)
etypes <- mapM expType es
when (length types /= length etypes) $
throwError $ "Invalid data fields for `" ++ n ++ "'"
zipWithM_ checkType types etypes
return dt
expType (Brack e) = expType e
expType (StrictExp e) = expType e
expType (Negate e) = expType (Times (Int (-1)) e)
expType (IfThenElse e1 e2 e3) = do
et1 <- expType e1
et2 <- expType e2
et3 <- expType e3
checkType et1 BoolType
checkType et2 et3
return et2
expType (CaseOf e patterns) = do
consmap <- constructormap <$> get
let mctypes = map (getParamType consmap . caseParams) patterns
case lefts mctypes of
(p:_) -> throwError p
[] ->
case the (catMaybes $ rights mctypes) of
Nothing -> throwError "case pattern: not all cases have the same type"
Just t -> do
et <- expType e
checkType t et
exptypes <- mapM (\(Case p ex) -> withContext $ paramType p >> expType ex) patterns
matchAll exptypes
case exptypes of
[] -> throwError "Error: case of with no cases"
(t':_) -> return t'
withContext :: StateT FunCheckState TypeCheckMonad a -> StateT FunCheckState TypeCheckMonad a
withContext a = do
ctxt1 <- context <$> get
res <- a
s' <- get
put $ s'{context=ctxt1}
return res
-- TODO: function types
typeNameToType :: String -> StateT FunCheckState TypeCheckMonad Type
typeNameToType "Int" = return IntType
typeNameToType "Bool" = return BoolType
typeNameToType n = return $ Custom n
matchAll :: [Type] -> StateT FunCheckState TypeCheckMonad ()
matchAll [] = return ()
matchAll (t:ts) = matchAll' t ts
where matchAll' _ [] = return ()
matchAll' tr@(TypeVariable tv) (n:ns) = do
addConstraint tv n
matchAll' tr ns
matchAll' tr (n:ns) = do
checkType tr n
matchAll' tr ns
the :: (Eq a) => [a] -> Maybe a
the [] = Nothing
the (x:xs) | all (x==) xs = Just x
| otherwise = Nothing
| anttisalonen/lvm | src/stau/TypeCheck.hs | gpl-3.0 | 13,436 | 0 | 22 | 3,258 | 4,958 | 2,411 | 2,547 | 319 | 10 |
module GameState (
newGame,
getChild,
getChildren,
getPlayableCorners,
getLegalPlacements,
getPlayer,
) where
import Data.Bits
import Data.List
import Types
import Player
import Board
import Territory
import Placement
instance Show GameState where
show (State _ board _ _) = show board
newGame = State 0 emptyBoard initialCorners (allPieces,allPieces,allPieces,allPieces)
legalAt !(TerritoryCorner _ _ cornerBitmap) !(Placement _ _ _ _ placementBitmap) =
(placementBitmap .&. cornerBitmap) == placementBitmap
getPlacementsAt !(TerritoryCorner _ cornerType _) = getPlacementsFor cornerType
getChildren state =
let (State turn _ corners pieces) = state
getMy = getPlayers (fromTurn turn)
myCorners = getMy corners
myPieces = getMy pieces
getChildAt (TerritoryCorner coords _ _) = getChild state coords
in {-# SCC getChildren_loop #-} [
getChildAt corner placement |
corner <- myCorners,
piece <- myPieces,
placement <- getPlacementsAt corner piece,
legalAt corner placement
]
getPiecesAfterMove player (Placement piece _ _ _ _) = forPlayer player (filter (/= piece))
getChild (State turn board corners pieces) coords placement =
let player = fromTurn turn
turn' = turn + 1
board' = getBoardAfterMove board player coords placement
corners' = getCornersAfterMove board' player coords placement corners
pieces' = getPiecesAfterMove player placement pieces
in State turn' board' corners' pieces'
getLegalPlacements corner piece =
filter (legalAt corner) (getPlacementsAt corner piece)
getPlayableCorners piece (State turn _ corners pieces) =
let player = fromTurn turn
myCorners = getPlayers player corners
myPieces = getPlayers player pieces
hasPlacementsOf corner piece = any (legalAt corner) (getPlacementsAt corner piece)
playable corner = any (hasPlacementsOf corner) myPieces
in filter playable myCorners
getPlayer (State turn _ _ _) = fromTurn turn
| djudd/blokus | GameState.hs | gpl-3.0 | 2,097 | 0 | 11 | 498 | 606 | 305 | 301 | -1 | -1 |
-- | Extensions to the interface of 'Data.Map'.
module Extension.Data.Map (
module Data.Map
, adjustWithDefault
, queryMap
, invertMap
) where
import Data.Maybe (fromMaybe)
import qualified Data.Set as S
import Data.Map
-- | Adjusts a value at a specific key. When the key is not a member of the map,
-- the given default value is inserted at this key and adjusted.
adjustWithDefault :: Ord k => a -> (a -> a) -> k -> Map k a -> Map k a
adjustWithDefault e f = alter (maybe (Just . f $ e) (Just . f))
-- | Compute some query over the value of the map at a specific key, while
-- defaulting to a fixed value, if there is no value to query
queryMap :: Ord k => (a -> b) -> b -> k -> Map k a -> b
queryMap f e k = maybe e f . Data.Map.lookup k
-- | Invert a map.
invertMap :: Ord v => M.Map k v -> M.Map v k
invertMap = M.fromList . map (uncurry $ flip (,)) . M.toList
| meiersi/scyther-proof | src/Extension/Data/Map.hs | gpl-3.0 | 880 | 0 | 11 | 196 | 267 | 143 | 124 | 14 | 1 |
module ParseTests(parseTestResults) where
import Regexp
import ParseRegexp(parse)
import Tokenise
parseTestResults :: [([Token], Maybe Regexp, Maybe Regexp)]
parseTestResults = runParseTests parseTests
parseTests :: [([Token], Maybe Regexp)]
parseTests =
[([Text "abc"], Just $ Literal "abc"),
([Text "xyz", Dot], Just $ Sequence (Literal "xyz") AnyChar),
([Start, Text "a"], Just $ AtStart (Literal "a")),
([OpenBracket, Text "abc", CloseBracket], Just $ Literal "abc"),
([OpenBracket, Text "abc", CloseBracket, Text "xyz"],
Just $ Sequence (Literal "abc") (Literal "xyz")),
([OpenBracket, Text "ww", OpenBracket, Text "qq", CloseBracket,
CloseBracket],
Just $ Sequence (Literal "ww") (Literal "qq")),
([Text "ww", End], Just $ AtEnd (Literal "ww")),
([OpenBracket, Text "z", OpenBracket, Text "a", Text "x",
CloseBracket, CloseBracket, Text "b"],
Just $ Sequence (Sequence (Literal "z")
(Sequence (Literal "a") (Literal "x")))
(Literal "b")),
([OpenBracket, Text "a", CloseBracket, Text "b"],
Just $ Sequence (Literal "a") (Literal "b")),
([OpenBracket, Text "a", Text "b", CloseBracket, Plus],
Just $ OneOrMore (Sequence (Literal "a") (Literal "b"))),
([Text "a", QuestionMark], Just $ Optional $ Literal "a")
]
runParseTests :: [([Token], Maybe Regexp)] ->
[([Token], Maybe Regexp, Maybe Regexp)]
runParseTests [] = []
runParseTests ((tokens, expected):ps)
| actual == expected = runParseTests ps
| otherwise = (tokens, actual, expected):runParseTests ps
where actual = parse tokens
| srank/regexp | ParseTests.hs | gpl-3.0 | 1,617 | 0 | 14 | 324 | 683 | 375 | 308 | 35 | 1 |
{-# LANGUAGE Arrows #-}
module Main where
import System.IO
import Debug.Trace
import Control.Monad.Random
import FRP.Yampa
import SIR
type SIRAgentProc = SF [SIRState] SIRState
contactRate :: Double
contactRate = 5.0
infectionProb :: Double
infectionProb = 0.05
illnessDuration :: Double
illnessDuration = 15.0
agentCount :: Int
agentCount = 100
infectedCount :: Int
infectedCount = 10
rngSeed :: Int
rngSeed = 42
dt :: DTime
dt = 0.01
t :: Time
t = 150
main :: IO ()
main = do
hSetBuffering stdout NoBuffering
let g = mkStdGen rngSeed
setStdGen g
let as = initAgents agentCount infectedCount
let ass = runSimulationUntil g t dt as
let dyns = aggregateAllStates ass
let fileName = "SIR_YAMPA_DYNAMICS_" ++ show agentCount ++ "agents.m"
writeAggregatesToFile fileName dyns
runSimulationUntil :: (RandomGen g) => g -> Time -> DTime -> [SIRState] -> [[SIRState]]
runSimulationUntil g t dt as = embed (sirSimulation sfs as) ((), dts)
where
steps = floor $ t / dt
dts = replicate steps (dt, Nothing) -- keep input the same as initial one, will be ignored anyway
(rngs, _) = rngSplits g steps []
sfs = map (\(g', a) -> sirAgent g' a) (zip rngs as)
rngSplits :: (RandomGen g) => g -> Int -> [g] -> ([g], g)
rngSplits g 0 acc = (acc, g)
rngSplits g n acc = rngSplits g'' (n-1) (g' : acc)
where
(g', g'') = split g
sirSimulation :: [SIRAgentProc] -> [SIRState] -> SF () [SIRState]
sirSimulation sfs as =
pSwitch
(\_ sfs' -> map (\sf -> (as, sf)) sfs')
sfs
(sirSimulationSwitchingEvent >>> notYet) -- if we switch immediately we end up in endless switching, so always wait for 'next'
sirSimulationContinuation
where
sirSimulationSwitchingEvent :: SF ((), [SIRState]) (Event [SIRState])
sirSimulationSwitchingEvent = proc (_, newAs) -> do returnA -< (Event newAs)
sirSimulationContinuation :: [SIRAgentProc] -> [SIRState] -> SF () [SIRState]
sirSimulationContinuation sfs newAs = sirSimulation sfs newAs
sirAgent :: (RandomGen g) => g -> SIRState -> SIRAgentProc
sirAgent g Susceptible = susceptibleAgent g
sirAgent g Infected = infectedAgent g
sirAgent _ Recovered = recoveredAgent
susceptibleAgent :: (RandomGen g) => g -> SIRAgentProc
susceptibleAgent g = switch (susceptibleAgentInfectedEvent g) (const $ infectedAgent g)
where
susceptibleAgentInfectedEvent :: (RandomGen g) => g -> SF [SIRState] (SIRState, Event ())
susceptibleAgentInfectedEvent g = proc as -> do
makeContact <- occasionally g (1 / contactRate) () -< ()
a <- drawRandomElemSF g -< as
doInfect <- randomBoolSF g infectionProb -< ()
--if (trace ("makeContact = " ++ show makeContact ++ ", a = " ++ show a ++ ", doInfect = " ++ show doInfect) (isEvent makeContact))
--if (trace ("as = " ++ show as) (isEvent makeContact))
if isEvent makeContact
&& Infected == a
&& doInfect
then returnA -< (trace ("Infected") (Infected, Event ()))
else returnA -< (trace ("Susceptible") (Susceptible, NoEvent))
infectedAgent :: (RandomGen g) => g -> SIRAgentProc
infectedAgent g = switch infectedAgentRecoveredEvent (const recoveredAgent)
where
infectedAgentRecoveredEvent :: SF [SIRState] (SIRState, Event ())
infectedAgentRecoveredEvent = proc _ -> do
recEvt <- occasionally g illnessDuration () -< ()
let a = event Infected (const Recovered) recEvt
returnA -< (a, recEvt)
recoveredAgent :: SIRAgentProc
recoveredAgent = arr (const Recovered)
randomBoolSF :: (RandomGen g) => g -> Double -> SF () Bool
randomBoolSF g p = proc _ -> do
r <- noiseR ((0, 1) :: (Double, Double)) g -< ()
returnA -< (r <= p)
drawRandomElemSF :: (RandomGen g, Show a) => g -> SF [a] a
drawRandomElemSF g = proc as -> do
r <- noiseR ((0, 1) :: (Double, Double)) g -< ()
let len = length as
let idx = (fromIntegral $ len) * r
let a = as !! (floor idx)
returnA -< a | thalerjonathan/phd | coding/papers/FrABS/Haskell/prototyping/SIRYampa/src/Main.hs | gpl-3.0 | 3,950 | 5 | 16 | 865 | 1,382 | 722 | 660 | 91 | 2 |
readLine = putStrLn "123" >> getLine | cwlmyjm/haskell | AFP/L0223.hs | mpl-2.0 | 36 | 0 | 6 | 5 | 13 | 6 | 7 | 1 | 1 |
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE FunctionalDependencies #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell #-}
module CouchAuthProxy.UserToken where
import Control.Lens (makeLensesWith, camelCaseFields)
import Data.Aeson (ToJSON(toJSON), object, (.=), FromJSON(parseJSON), (.:), (.:?), Value(Object))
import Data.Maybe (catMaybes)
import Data.Text (Text)
data UserToken
= UserToken
{ userTokenId_ :: Text
, userTokenRev :: Maybe Text
, userTokenToken :: Text
}
instance ToJSON UserToken where
toJSON o =
let
kv = [ Just ("_id" .= userTokenId_ o)
, Just ("token" .= userTokenToken o)
, Just ("type" .= ("userToken" :: Text))
, renderRev <$> userTokenRev o
]
in
object $ catMaybes kv
where
renderRev rev =
"_rev" .= rev
instance FromJSON UserToken where
parseJSON (Object o) =
UserToken <$> (o .: "_id") <*> (o .:? "_rev") <*> (o .: "token")
parseJSON _ =
error "Invalid UserToken JSON"
makeLensesWith camelCaseFields ''UserToken
| asvyazin/my-books.purs | server/my-books/CouchAuthProxy/UserToken.hs | mpl-2.0 | 1,115 | 0 | 14 | 254 | 305 | 173 | 132 | 31 | 0 |
-- brittany { lconfig_columnAlignMode: { tag: ColumnAlignModeDisabled }, lconfig_indentPolicy: IndentPolicyLeft }
func
:: ( Trither
lkasdlkjalsdjlakjsdlkjasldkjalskdjlkajsd
lkasdlkjalsdjlakjsdlkjasldkjalskdjlkajsd
)
lkasdlkjalsdjlakjsdlkjasldkjalskdjlkajsd
-> asd
| lspitzner/brittany | data/Test379.hs | agpl-3.0 | 298 | 1 | 8 | 55 | 26 | 12 | 14 | 6 | 0 |
period a = (head plist) : (takeWhile (/= head plist) (tail plist))
where
plist = filter (/=2) $ r a
r a = map (\n -> (as1^n + ap1^n) `mod` a2) [0..]
where as1 = a - 1
ap1 = a + 1
a2 = a^2
prob120 = sum (map (maxlist.period) [3..1000])
where maxlist = foldl1 max
main = putStrLn $ show $ prob120 | jdavidberger/project-euler | prob120.hs | lgpl-3.0 | 348 | 4 | 12 | 117 | 197 | 98 | 99 | 9 | 1 |
{-# LANGUAGE TupleSections #-}
module Renderer
( renderGame
) where
import Control.Lens
import Control.Monad.Reader
import Control.Monad.State
import Data.IORef
import Data.List
import qualified Data.Vector.Storable as VS
import Foreign.C.Types
import Linear (V2(V2), V4(V4))
import Linear.Affine (Point(P))
import SDL hiding (get)
import qualified SDL.Raw.Types as Srt
import qualified SDL.TTF as Ttf
import System.Random
import Cache
import Camera
import Coordinate
import Engine
import Environment
import Game
import qualified Grid as G
import Object
import qualified Region as R
-- import Sprite
import Ui
import Ui.Menu
renderGame :: Engine ()
renderGame = do
-- Information needed to render
renderer <- asks envRenderer
-- Let's prepare a new fresh screen
rendererDrawColor renderer $= V4 0 0 0 0 -- black
clear renderer
-- Render various things
subRenderVoid
subRenderWorld
subRenderUi
-- Present to the screen
present renderer
subRenderUi :: Engine ()
subRenderUi = do
-- Information needed to render
renderer <- asks envRenderer
font <- asks envFont
game <- get
-- TODO: fix me
let (V2 _ height) = game ^. gameCamera . cameraWindowSize
forM_ (game ^. gameUi . uiVisible) $ \modalType -> do
case modalType of
(MkUiTypeMenu mt) -> do
forM (zip [0..] $ reverse $ uiMenuOptions mt) $ \(row, text) -> do
surface <- Ttf.renderTextShaded font text (Srt.Color 255 255 255 0) (Srt.Color 0 0 0 0)
V2 surfaceWidth surfaceHeight <- surfaceDimensions surface
texture <- createTextureFromSurface renderer surface
freeSurface surface
let dst = Rectangle (P $ V2 0 (height - surfaceHeight - (row * 15))) (V2 surfaceWidth surfaceHeight)
copyEx renderer texture Nothing (Just dst) 0 Nothing (V2 False False)
destroyTexture texture
-- _ -> return []
subRenderWorld :: Engine ()
subRenderWorld = do
-- Information needed to render
renderer <- asks envRenderer
tileset <- asks envTileset
tileSize <- asks envTileSize
cameraX <- use $ gameCamera . cameraCoordinate . coordinateX
cameraY <- use $ gameCamera . cameraCoordinate . coordinateY
viewport <- use $ gameCamera . cameraViewport
regionLinks <- use gameRegions
-- TODO: fix me
let (V2 cameraCoordMaxX cameraCoordMaxY) = V2 cameraX cameraY + (V2 fromIntegral fromIntegral <*> viewport)
regions <- embedGame $ mapM gameReadLink regionLinks
-- TODO: Abandon hopes whoever wants to update this monster
things <- concat <$> (forM regions $ \region -> do
let (scx, scy) = view (R.regionCoordinate . coordinates) region
let grid = view R.regionGrid region
let range = ( fromIntegral $ cameraX - scx
, fromIntegral $ cameraY - scy
, fromIntegral $ (cameraX - scx) + (cameraCoordMaxX - cameraX)
, fromIntegral $ (cameraY - scy) + (cameraCoordMaxY - cameraY)
)
forM (G.range range grid) $ \(x, y, v) -> do
rv <- embedGame $ gameReadLink v
return $ (\o -> (coordinate (scx + fromIntegral x) (scy + fromIntegral y), o)) $ rv
)
-- Collect renderables, because of zIndex
-- TODO: We might have to take "things" large than is visible on the screen if we have very large
-- multi-sprite objects that starts glitching the the edges of the screen.
renderables <- concat <$> (forM things $ \(coord, obj) -> do
{-
let perimeterSprite = case view objFloodFill obj of
0 -> spritePart 0 0 0 4 ZInAir
_ -> spritePart 0 0 0 3 ZInAir
-}
-- let spriteParts = perimeterSprite : objSprite obj
let spriteParts = objSprite obj
forM spriteParts $ \(coordSpriteRel, coordSpriteTile, zIndex) -> do
-- Bunch of positions to calculate
let srcTileX = fromIntegral $ coordSpriteTile ^. coordinateX
let srcTileY = fromIntegral $ coordSpriteTile ^. coordinateY
let dstRelX = fromIntegral $ coordSpriteRel ^. coordinateX
let dstRelY = fromIntegral $ coordSpriteRel ^. coordinateY
let dstTileRelX = fromIntegral $ coord ^. coordinateX - cameraX
let dstTileRelY = fromIntegral $ coord ^. coordinateY - cameraY
-- Final src and dst rectangles for SDL
let src = Rectangle (P $ (V2 (CInt srcTileX) srcTileY) * fromIntegral tileSize) (fromIntegral tileSize)
let dst = Rectangle (P $ V2 (CInt (dstTileRelX + dstRelX)) (dstTileRelY + dstRelY) * (fromIntegral tileSize)) (fromIntegral tileSize)
return (Just src, Just dst, zIndex)
)
-- Render!
forM_ (sortOn (\(_,_,a) -> a) renderables) $ \(src, dst, _) -> do
copyEx renderer tileset src dst 0 Nothing (V2 False False)
subRenderVoid :: Engine ()
subRenderVoid = do
renderer <- asks envRenderer
cacheRef <- asks envCache
cache <- liftIO $ readIORef cacheRef
(V2 width height) <- use $ gameCamera . cameraWindowSize
theCameraWindowSize <- use $ gameCamera . cameraWindowSize
(cameraX, cameraY) <- use $ gameCamera . cameraCoordinate . coordinates
-- TODO: ugly
let nicerCopy lyr rdr tx ty = copy rdr lyr Nothing $ Just $ Rectangle (P $ V2 tx ty) (V2 width height)
case view cacheStars cache of
[] -> do
layers <- replicateM 5 $ liftIO $ do
gx <- newStdGen
let pointsx = randomRs (0, width) gx
gy <- newStdGen
let pointsy = randomRs (0, height) gy
let points = map (P . uncurry V2) $ zip pointsx pointsy
let dark = VS.fromList $ take 700 points
let normal = VS.fromList $ take 300 points
let bright = VS.fromList $ take 50 points
layer <- createTexture renderer RGBA8888 TextureAccessTarget theCameraWindowSize
rendererRenderTarget renderer $= Just layer
rendererDrawColor renderer $= V4 0 0 0 0 -- transparent black
clear renderer
textureBlendMode layer $= BlendAdditive -- BlendAlphaBlend
rendererDrawColor renderer $= V4 35 35 35 200 -- white quite dark
drawPoints renderer dark
rendererDrawColor renderer $= V4 100 100 100 200 -- white kinda visible
drawPoints renderer normal
rendererDrawColor renderer $= V4 255 255 255 255 -- white too bright
drawPoints renderer bright
rendererRenderTarget renderer $= Nothing
copy renderer layer Nothing Nothing
return layer
liftIO $ modifyIORef cacheRef $ cacheStars .~ layers
layers -> do
forM_ (zip layers [1..]) $ \(layer, n) -> do
let x = negate (fromIntegral cameraX) `div` n `mod` width
let y = negate (fromIntegral cameraY) `div` n `mod` height
nicerCopy layer renderer (x-width) y -- left
nicerCopy layer renderer x (y-height) -- top
nicerCopy layer renderer x y -- middle
nicerCopy layer renderer x (y+height) -- bottom
nicerCopy layer renderer (x+width) y -- right
nicerCopy layer renderer (x-width) (y-height) -- top-left
nicerCopy layer renderer (x+width) (y-height) -- top-right
nicerCopy layer renderer (x-width) (y+height) -- bottom-left
nicerCopy layer renderer (x+width) (y+height) -- bottom-right
| nitrix/lspace | legacy/Renderer.hs | unlicense | 8,022 | 0 | 30 | 2,629 | 2,212 | 1,103 | 1,109 | -1 | -1 |
module Main where
main :: IO ()
main = print "HELLO"
| haroldcarr/learn-haskell-coq-ml-etc | haskell/topic/type-level/2017-08-justin-le-fixed-length-vector-types/app/Main.hs | unlicense | 55 | 0 | 6 | 13 | 22 | 12 | 10 | 3 | 1 |
import Test.HUnit
import P9x.Util(expectEqual_, testList)
import P9x.P91.KnightsTour
p91 = testList "P91" [
expectEqual_ [] (findKnightTours 0),
expectEqual_ [[(0, 0)]] (findKnightTours 1),
expectEqual_ [] (findKnightTours 2),
expectEqual_ [] (findKnightTours 3),
expectEqual_ [] (findKnightTours 4),
expectEqual_ [
(4,4),(2,3),(0,4),(1,2),(2,4),
(0,3),(1,1),(3,0),(4,2),(3,4),
(1,3),(0,1),(2,2),(4,3),(3,1),
(1,0),(0,2),(1,4),(3,3),(4,1),
(2,0),(3,2),(4,0),(2,1),(0,0)
] (head $ findKnightTours 5)
-- expectEqual_ 1728 (length $ findKnightTours 5)
]
main :: IO Counts
main = runTestTT $ TestList [p91] | dkandalov/katas | haskell/p99/src/p9x/p91/KnightsTour_Test.hs | unlicense | 684 | 2 | 10 | 144 | 398 | 239 | 159 | 18 | 1 |
{-#LANGUAGE OverloadedStrings#-}
module Data.P440.XML.Instances.ZSV where
import qualified Data.P440.Domain.ZSV as ZSV
import Data.P440.Domain.SimpleTypes
import Data.P440.Domain.ComplexTypes
import Data.P440.XML.XML
import qualified Data.P440.XML.Instances.SimpleTypes
import qualified Data.P440.XML.Instances.ComplexTypes as C
import qualified Data.P440.XML.Instances.ComplexTypesZS as C
instance ToNode ZSV.Файл where
toNode (ZSV.Файл идЭС версПрог телОтпр
должнОтпр фамОтпр запросВыпис) =
complex "Файл"
["ИдЭС" =: идЭС
,"ВерсПрог" =: версПрог
,"ТелОтпр" =: телОтпр
,"ДолжнОтпр" =: должнОтпр
,"ФамОтпр" =: фамОтпр]
[Single запросВыпис]
instance ToNode ZSV.ЗапросВыпис where
toNode (ZSV.ЗапросВыпис номЗапр стНКРФ видЗапр основЗапр типЗапр
признЗапр датаПодп свНО' свПл
банкИлиУБР поУказаннымИлиПоВсем руководитель) =
complex "ЗапросВыпис"
["НомЗапр" =: номЗапр
,"СтНКРФ" =: стНКРФ
,"ВидЗапр" =: видЗапр
,"ОсновЗапр" =: основЗапр
,"ТипЗапр" =: типЗапр
,"ПризнЗапр" =: признЗапр
,"ДатаПодп" =: датаПодп]
[Single $ C.свНО "СвНО" свНО'
,Single свПл
,Single банкИлиУБР
,Single поУказаннымИлиПоВсем
,Single $ C.рукНО "Руководитель" руководитель]
instance ToNode ZSV.ПоУказаннмыИлиПоВсем where
toNode (ZSV.ПоУказанным счетИлиКЭСП) =
complex "ПоУказанным"
[]
[Sequence счетИлиКЭСП]
toNode (ZSV.ПоВсем наДатуИлиЗаПериод) =
complex "ПоВсем"
[]
[Single наДатуИлиЗаПериод]
instance ToSequence ZSV.СчетИлиКЭСП where
toSequence (ZSV.Счет' счет) =
toSequence счет
toSequence (ZSV.КЭСП' кэсп) =
toSequence кэсп
instance ToNode ZSV.Счет where
toNode (ZSV.Счет номСч датаНач датаКон) =
complex_ "Счет"
["НомСч" =: номСч
,"ДатаНач" =: датаНач
,"ДатаКон" =: датаКон]
instance ToNode ZSV.КЭСП where
toNode (ZSV.КЭСП идКэсп датаНач датаКон) =
complex_ "Счет"
["ИдКЭСП" =: идКэсп
,"ДатаНач" =: датаНач
,"ДатаКон" =: датаКон]
| Macil-dev/440P-old | src/Data/P440/XML/Instances/ZSV.hs | unlicense | 3,206 | 0 | 10 | 857 | 1,530 | 781 | 749 | 62 | 0 |
-- | Hashing functions and HMAC DRBG definition
module Network.Haskoin.Crypto.Hash
( Hash512(getHash512)
, Hash256(getHash256)
, Hash160(getHash160)
, CheckSum32(getCheckSum32)
, bsToHash512
, bsToHash256
, bsToHash160
, hash512
, hash256
, hash160
, sha1
, doubleHash256
, bsToCheckSum32
, checkSum32
, hmac512
, hmac256
, split512
, join512
, hmacDRBGNew
, hmacDRBGUpd
, hmacDRBGRsd
, hmacDRBGGen
, WorkingState
) where
import Crypto.Hash
( Digest
, SHA512
, SHA256
, SHA1
, RIPEMD160
, hash
)
import Crypto.MAC.HMAC (hmac)
import Control.DeepSeq (NFData, rnf)
import Control.Monad ((<=<), guard)
import Data.Byteable (toBytes)
import Data.Maybe (fromMaybe)
import Data.Word (Word16)
import Data.String (IsString, fromString)
import Data.String.Conversions (cs)
import Text.Read (Lexeme(String, Ident), readPrec, lexP, parens, pfail)
import Data.Binary (Binary, get, put)
import Data.Binary.Get (getByteString)
import Data.Binary.Put (putByteString)
import Data.ByteString (ByteString)
import qualified Data.ByteString as BS
( null
, append
, cons
, concat
, take
, empty
, length
, replicate
, splitAt
)
import Network.Haskoin.Util
newtype CheckSum32 = CheckSum32 { getCheckSum32 :: ByteString }
deriving (Eq, Ord)
newtype Hash512 = Hash512 { getHash512 :: ByteString }
deriving (Eq, Ord)
newtype Hash256 = Hash256 { getHash256 :: ByteString }
deriving (Eq, Ord)
newtype Hash160 = Hash160 { getHash160 :: ByteString }
deriving (Eq, Ord)
instance NFData CheckSum32 where
rnf (CheckSum32 bs) = rnf bs
instance Show CheckSum32 where
showsPrec d (CheckSum32 bs) = showParen (d > 10) $
showString "CheckSum32 " . shows (encodeHex bs)
instance Read CheckSum32 where
readPrec = parens $ do
Ident "CheckSum32" <- lexP
String str <- lexP
maybe pfail return $ bsToCheckSum32 =<< decodeHex (cs str)
instance IsString CheckSum32 where
fromString =
fromMaybe e . (bsToCheckSum32 <=< decodeHex) . cs
where
e = error "Could not decode checksum"
instance Binary CheckSum32 where
get = CheckSum32 <$> getByteString 4
put (CheckSum32 bs) = putByteString bs
instance NFData Hash512 where
rnf (Hash512 bs) = rnf bs
instance Show Hash512 where
showsPrec d (Hash512 bs) = showParen (d > 10) $
showString "Hash512 " . shows (encodeHex bs)
instance Read Hash512 where
readPrec = parens $ do
Ident "Hash512" <- lexP
String str <- lexP
maybe pfail return $ bsToHash512 =<< decodeHex (cs str)
instance IsString Hash512 where
fromString =
fromMaybe e . (bsToHash512 <=< decodeHex) . cs
where
e = error "Could not decode 64-byte hash"
instance Binary Hash512 where
get = Hash512 <$> getByteString 64
put (Hash512 bs) = putByteString bs
instance NFData Hash256 where
rnf (Hash256 bs) = rnf bs
instance Show Hash256 where
showsPrec d (Hash256 bs) = showParen (d > 10) $
showString "Hash256 " . shows (encodeHex bs)
instance Read Hash256 where
readPrec = parens $ do
Ident "Hash256" <- lexP
String str <- lexP
maybe pfail return $ bsToHash256 =<< decodeHex (cs str)
instance IsString Hash256 where
fromString =
fromMaybe e . (bsToHash256 <=< decodeHex) . cs
where
e = error "Could not decode 32-byte hash"
instance Binary Hash256 where
get = Hash256 <$> getByteString 32
put (Hash256 bs) = putByteString bs
instance NFData Hash160 where
rnf (Hash160 bs) = rnf bs
instance Show Hash160 where
showsPrec d (Hash160 bs) = showParen (d > 10) $
showString "Hash160 " . shows (encodeHex bs)
instance Read Hash160 where
readPrec = parens $ do
Ident "Hash160" <- lexP
String str <- lexP
maybe pfail return $ bsToHash160 =<< decodeHex (cs str)
instance IsString Hash160 where
fromString =
fromMaybe e . (bsToHash160 <=< decodeHex) . cs
where
e = error "Could not decode 20-byte hash"
instance Binary Hash160 where
get = Hash160 <$> getByteString 20
put (Hash160 bs) = putByteString bs
bsToHash512 :: ByteString -> Maybe Hash512
bsToHash512 bs = guard (BS.length bs == 64) >> return (Hash512 bs)
bsToHash256 :: ByteString -> Maybe Hash256
bsToHash256 bs = guard (BS.length bs == 32) >> return (Hash256 bs)
bsToHash160 :: ByteString -> Maybe Hash160
bsToHash160 bs = guard (BS.length bs == 20) >> return (Hash160 bs)
-- | Compute SHA-512.
hash512 :: ByteString -> Hash512
hash512 = Hash512 . (toBytes :: Digest SHA512 -> ByteString) . hash
-- | Compute SHA-256.
hash256 :: ByteString -> Hash256
hash256 = Hash256 . (toBytes :: Digest SHA256 -> ByteString) . hash
-- | Compute RIPEMD-160.
hash160 :: ByteString -> Hash160
hash160 = Hash160 . (toBytes :: Digest RIPEMD160 -> ByteString) . hash
-- | Compute SHA1
sha1 :: ByteString -> Hash160
sha1 = Hash160 . (toBytes :: Digest SHA1 -> ByteString) . hash
-- | Compute two rounds of SHA-256.
doubleHash256 :: ByteString -> Hash256
doubleHash256 = hash256 . getHash256 . hash256
{- CheckSum -}
bsToCheckSum32 :: ByteString -> Maybe CheckSum32
bsToCheckSum32 bs = guard (BS.length bs == 4) >> return (CheckSum32 bs)
-- | Computes a 32 bit checksum.
checkSum32 :: ByteString -> CheckSum32
checkSum32 bs =
CheckSum32 $ BS.take 4 bs'
where
Hash256 bs' = doubleHash256 bs
{- HMAC -}
-- | Computes HMAC over SHA-512.
hmac512 :: ByteString -> ByteString -> Hash512
hmac512 key msg =
Hash512 $ hmac f 128 key msg
where
f bs = let Hash512 bs' = hash512 bs in bs'
-- | Computes HMAC over SHA-256.
hmac256 :: ByteString -> ByteString -> Hash256
hmac256 key msg =
Hash256 $ hmac f 64 key msg
where
f bs = let Hash256 bs' = hash256 bs in bs'
-- | Split a 'Hash512' into a pair of 'Hash256'.
split512 :: Hash512 -> (Hash256, Hash256)
split512 (Hash512 bs) =
(Hash256 a, Hash256 b)
where
(a, b) = BS.splitAt 32 bs
-- | Join a pair of 'Hash256' into a 'Hash512'.
join512 :: (Hash256, Hash256) -> Hash512
join512 (Hash256 a, Hash256 b) = Hash512 $ a `BS.append` b
{- 10.1.2 HMAC_DRBG with HMAC-SHA256
http://csrc.nist.gov/publications/nistpubs/800-90A/SP800-90A.pdf
Constants are based on recommentations in Appendix D section 2 (D.2)
-}
type WorkingState = (ByteString, ByteString, Word16)
type AdditionalInput = ByteString
type ProvidedData = ByteString
type EntropyInput = ByteString
type Nonce = ByteString
type PersString = ByteString
-- 10.1.2.2 HMAC DRBG Update FUnction
hmacDRBGUpd :: ProvidedData -> ByteString -> ByteString
-> (ByteString, ByteString)
hmacDRBGUpd info k0 v0
| BS.null info = (k1, v1) -- 10.1.2.2.3
| otherwise = (k2, v2) -- 10.1.2.2.6
where
-- 10.1.2.2.1
Hash256 k1 = hmac256 k0 $ v0 `BS.append` (0 `BS.cons` info)
-- 10.1.2.2.2
Hash256 v1 = hmac256 k1 v0
-- 10.1.2.2.4
Hash256 k2 = hmac256 k1 $ v1 `BS.append` (1 `BS.cons` info)
-- 10.1.2.2.5
Hash256 v2 = hmac256 k2 v1
-- 10.1.2.3 HMAC DRBG Instantiation
hmacDRBGNew :: EntropyInput -> Nonce -> PersString -> WorkingState
hmacDRBGNew seed nonce info
| (BS.length seed + BS.length nonce) * 8 < 384 = error $
"Entropy + nonce input length must be at least 384 bit"
| (BS.length seed + BS.length nonce) * 8 > 1000 = error $
"Entropy + nonce input length can not be greater than 1000 bit"
| BS.length info * 8 > 256 = error $
"Maximum personalization string length is 256 bit"
| otherwise = (k1, v1, 1) -- 10.1.2.3.6
where
s = BS.concat [seed, nonce, info] -- 10.1.2.3.1
k0 = BS.replicate 32 0 -- 10.1.2.3.2
v0 = BS.replicate 32 1 -- 10.1.2.3.3
(k1,v1) = hmacDRBGUpd s k0 v0 -- 10.1.2.3.4
-- 10.1.2.4 HMAC DRBG Reseeding
hmacDRBGRsd :: WorkingState -> EntropyInput -> AdditionalInput -> WorkingState
hmacDRBGRsd (k, v, _) seed info
| BS.length seed * 8 < 256 = error $
"Entropy input length must be at least 256 bit"
| BS.length seed * 8 > 1000 = error $
"Entropy input length can not be greater than 1000 bit"
| otherwise = (k0, v0, 1) -- 10.1.2.4.4
where
s = seed `BS.append` info -- 10.1.2.4.1
(k0, v0) = hmacDRBGUpd s k v -- 10.1.2.4.2
-- 10.1.2.5 HMAC DRBG Generation
hmacDRBGGen :: WorkingState -> Word16 -> AdditionalInput
-> (WorkingState, Maybe ByteString)
hmacDRBGGen (k0, v0, c0) bytes info
| bytes * 8 > 7500 = error "Maximum bits per request is 7500"
| c0 > 10000 = ((k0, v0, c0), Nothing) -- 10.1.2.5.1
| otherwise = ((k2, v3, c1), Just res) -- 10.1.2.5.8
where
(k1, v1) | BS.null info = (k0, v0)
| otherwise = hmacDRBGUpd info k0 v0 -- 10.1.2.5.2
(tmp, v2) = go (fromIntegral bytes) k1 v1 BS.empty -- 10.1.2.5.3/4
res = BS.take (fromIntegral bytes) tmp -- 10.1.2.5.5
(k2, v3) = hmacDRBGUpd info k1 v2 -- 10.1.2.5.6
c1 = c0 + 1 -- 10.1.2.5.7
go l k v acc | BS.length acc >= l = (acc,v)
| otherwise = let vn = getHash256 $ hmac256 k v
in go l k vn (acc `BS.append` vn)
| tphyahoo/haskoin | haskoin-core/Network/Haskoin/Crypto/Hash.hs | unlicense | 9,339 | 0 | 13 | 2,380 | 2,862 | 1,515 | 1,347 | 227 | 1 |
-- Copyright 2020-2021 Google LLC
--
-- 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.
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE CPP #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE QuantifiedConstraints #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE PolyKinds #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE UndecidableInstances #-}
-- | Representational subtyping relations and variance roles.
module Data.Type.Attenuation
( -- * Attenuation
Attenuation, type (:⊆:), attenuateWith, coercible
, trans, repr, coer, iso, inst
-- ** Representationality
, Representational, Representational0, Representational1, Variance
-- ** Functor and Contravariant
, co, contra
-- ** Bifunctor
, fstco, sndco
-- ** (->)
, domain, codomain
-- ** Initial and Final Objects
, attVoid, attAny
-- * Attenuable
, Attenuable(..), type (⊆), attenuate
, withAttenuation
-- ** Entailments
, contravariance, transitivity
) where
import Prelude hiding ((.))
import Control.Category (Category(..))
import Data.Coerce (Coercible, coerce)
import Data.Functor.Contravariant (Contravariant(..))
import Data.Type.Coercion (Coercion(..), sym)
import Data.Type.Equality ((:~:)(..), gcastWith)
import Data.Void (Void)
import GHC.Exts (Any)
import Data.Constraint ((:-)(Sub), Dict(..))
#if MIN_VERSION_base(4,15,0)
import Unsafe.Coerce (unsafeEqualityProof, UnsafeEquality(..))
#else
import Unsafe.Coerce (unsafeCoerce)
#endif
import Data.Type.Attenuation.Internal
-- | An operator form of 'Attenuation', by analogy to (':~:').
type (:⊆:) = Attenuation
-- | Coerce along an 'Attenuation'.
--
-- This is really, truly a coercion when it reaches Core.
attenuateWith :: Attenuation a b -> a -> b
attenuateWith (Attenuation Coercion) = coerce
-- | Any coercible types have an 'Attenuation'.
coercible :: Coercible a b => Attenuation a b
coercible = Attenuation Coercion
-- | Any type is unidirectionally coercible to itself.
repr :: (a :~: b) -> Attenuation a b
repr eq = gcastWith eq refl
-- | Bidirectional coercions can be weakened to unidirectional coercions.
coer :: Coercion a b -> Attenuation a b
coer = Attenuation
-- | Lift an 'Attenuation' contravariantly over a type constructor @f@.
--
-- Regarding the 'Contravariant' constraint, see 'co', and interchange mentions
-- of covariance and contravariance.
contra :: (Contravariant f, Representational f) => Variance (f b) (f a) a b
contra (Attenuation c) = Attenuation (sym $ rep c)
-- | 'Attenuation's across type constructors can be instantiated.
--
-- This means 'Attenuation's across type constructors lift equality of type
-- parameters to 'Attenuation' of the applied result.
--
-- This is analogous to how @Coercible f g@ works.
inst :: Attenuation f g -> Attenuation (f x) (g x)
inst (Attenuation Coercion) = Attenuation Coercion
-- | 'Attenuation' of 'Void' to any type.
--
-- If you have 'Void' appearing covariantly in a type, you can replace it with
-- any other lifted type with a coercion, because the value can't contain any
-- non-bottom 'Void' values (there are none), and any value that /is/ bottom
-- can "work" (i.e. throw or fail to terminate) just as well at any other
-- lifted type.
--
-- For example, if you have a @[Doc Void]@ (from
-- <https://hackage.haskell.org/package/pretty pretty>), you know it doesn't
-- have any annotations (or they're errors), so you can use it as @[Doc a]@
-- without actually traversing the list and @Doc@ structure to apply
-- 'Data.Void.absurd' to all of the 'Void's.
attVoid :: forall a. Attenuation Void a
attVoid = Attenuation $
#if MIN_VERSION_base(4,15,0)
case unsafeEqualityProof :: UnsafeEquality a Void of UnsafeRefl -> Coercion
#else
(unsafeCoerce (Coercion :: Coercion a a) :: Coercion Void a)
#endif
-- | 'Attenuation' of any type to 'Any'.
--
-- Similarly to 'attVoid', you can weaken any type to 'Any' for free, since any
-- value is a valid value of type 'Any'.
attAny :: forall a. Attenuation a Any
attAny = Attenuation $
#if MIN_VERSION_base(4,15,0)
case unsafeEqualityProof :: UnsafeEquality a Any of UnsafeRefl -> Coercion
#else
(unsafeCoerce (Coercion :: Coercion a a) :: Coercion a Any)
#endif
-- | An operator form of 'Attenuable'.
type (⊆) = Attenuable
-- | Coerce from a representational subtype @a@ to its supertype @b@.
attenuate :: Attenuable a b => a -> b
attenuate = attenuateWith attenuation
-- Type inference aid for use in entailments: otherwise it's ambiguous what
-- 'Attenuation' we want to promote with 'withAttenuation'.
toDict :: Attenuation a b -> Dict (Attenuable a b)
toDict att = withAttenuation att Dict
-- | 'Contravariant' functors map attenuation contravariantly.
contravariance
:: forall f a b
. (Representational f, Contravariant f)
=> Attenuable a b :- Attenuable (f b) (f a)
contravariance = Sub (toDict (contra attenuation))
-- | 'Attenuation's are transitive.
transitivity
:: forall b a c. (Attenuable b c, Attenuable a b) :- Attenuable a c
transitivity = Sub (toDict $ attenuation @b @c . attenuation @a @b)
-- | If 'Attenuation's in both directions exist, they're actually a 'Coercion'.
iso :: Attenuation a b -> Attenuation b a -> Coercion a b
iso (Attenuation c) _ = c
| google/hs-attenuation | attenuation/src/Data/Type/Attenuation.hs | apache-2.0 | 6,036 | 0 | 10 | 1,122 | 934 | 559 | 375 | -1 | -1 |
{- |
Module : Codec.Goat.ValueFrame
Description : Top-level header for value compression
Copyright : (c) Daniel Lovasko, 2016-2017
License : BSD3
Maintainer : Daniel Lovasko <daniel.lovasko@gmail.com>
Stability : stable
Portability : portable
-}
module Codec.Goat.ValueFrame
( ValueFrame(..)
, valueDecode
, valueEncode
) where
import Codec.Goat.ValueFrame.Decode
import Codec.Goat.ValueFrame.Encode
import Codec.Goat.ValueFrame.Types
| lovasko/goat | src/Codec/Goat/ValueFrame.hs | bsd-2-clause | 452 | 0 | 5 | 66 | 44 | 31 | 13 | 7 | 0 |
module Helpers.Profile
( profileForm
, saveProfile
) where
import Import
data ProfileForm = ProfileForm
{ pfFullname :: Maybe Text
, pfUsername :: Maybe Text
, pfEmail :: Maybe Text
}
profileForm :: User -> Form ProfileForm
profileForm u = renderBootstrap $ ProfileForm
<$> aopt textField "Full name" (Just $ userFullname u)
<*> aopt textField "User name" (Just $ userUsername u)
<*> aopt emailField "Email"
{ fsTooltip = Just "never displayed, only used to find your gravatar"
} (Just $ userEmail u)
saveProfile :: UserId -> ProfileForm -> Handler ()
saveProfile uid pf = do
runDB $ update uid
[ UserFullname =. pfFullname pf
, UserUsername =. pfUsername pf
, UserEmail =. pfEmail pf
]
redirect ProfileR
| pbrisbin/renters-reality | Helpers/Profile.hs | bsd-2-clause | 818 | 0 | 11 | 229 | 227 | 115 | 112 | 22 | 1 |
{-# LANGUAGE RecordWildCards #-}
module NW.Random where
import Control.Monad.Primitive
import qualified Crypto.Hash.SHA1 as SHA1
import Data.Bits
import qualified Data.ByteString.Lazy as B
import Data.List (foldl', nub, transpose)
import Data.Time.Calendar
import Data.Time.Clock
import qualified Data.Vector as V
import Data.Word
import System.Random.MWC
import NW.Util
data NWSeed
= SeedEmpty
| SeedManual [Word32]
| SeedToday
| SeedRandom
deriving (Eq, Show)
-- | For SeedManual, we limit [Word32] to 258 elements, because that is the
-- maximum number of elements System.Random.MWC deals with.
mkGen :: NWSeed -> IO GenIO
mkGen s = case s of
SeedEmpty -> initialize $ V.empty
SeedManual ns -> initialize $ initialize' ns
SeedToday -> initialize
. initialize'
. ((:[]) . fromIntegral . toModifiedJulianDay . utctDay)
=<< getCurrentTime
SeedRandom -> createSystemRandom
-- | The MWC RNG internally uses a state of 256 Word32's (`ws`), an index value
-- `i` that wraps around 0-255 (a single 'byte' in C), and a mutable constant
-- value `c` that changes with each iteration of the RNG. For simplicity, both
-- `i` and `c` are Word32 values.
initialize' :: [Word32] -> V.Vector Word32
initialize' ns
| any (==0) wsc = error "one or more values in either `ws` or `c` is 0"
| length (nub ws) /= length ws = error "some values in `ws` are the same"
| otherwise = set_i_c
. V.fromList . xorJoin
$ map (shaInflate B.empty . B.pack . octetsLE) ws
where
xorJoin :: [[Word32]] -> [Word32]
xorJoin = map (foldl' xor 0) . transpose
ws = take 256 ns
wsc = ws ++ drop 257 ns
ic = drop 256 ns
set_i_c v
| length ns == 258 = v V.++ (V.fromList ic)
| otherwise = v
shaInflate :: B.ByteString -> B.ByteString -> [Word32]
shaInflate acc bs
| B.length acc >= (256 * 4) = take 256 $ toW32s acc
| otherwise = shaInflate
(B.append acc . B.fromStrict $ SHA1.hashlazy bs)
(B.fromStrict $ SHA1.hashlazy bs)
toW32s :: B.ByteString -> [Word32]
toW32s = map fromOctetsLE . chop 4 . B.unpack
warmup :: Int -> GenIO -> IO Word64
warmup n rng
| n < 1 = error "n must be at least 1"
| otherwise = do
runs <- mapM (\_ -> uniform rng :: IO Word64) [1..n]
return $ last runs
-- | Randomly sample n elements from a list.
rndSample :: PrimMonad m => Int -> [a] -> Gen (PrimState m) -> m [a]
rndSample 0 _ _ = return []
rndSample _ [] _ = return []
rndSample count xs gen
| count < 0 = error "count must be at least 0"
| otherwise = do
idx <- uniformR (0, (length xs) - 1) gen
rest <- rndSample (count - 1) (snd $ removeAt idx xs) gen
return ((xs !! idx) : rest)
-- | Randomly select a single element from a list.
rndSelect :: PrimMonad m => [a] -> Gen (PrimState m) -> m a
rndSelect xs rng
| null xs = error "choose: list is empty"
| otherwise = do
idx <- uniformR (0, length xs - 1) rng
return $ xs !! idx
removeAt :: Int -> [a] -> (a, [a])
removeAt n = (\(a, b) -> (head b, a ++ tail b)) . splitAt n
octetsLE :: Word32 -> [Word8]
octetsLE w = map (fromIntegral . uncurry shiftR)
$ zip (repeat w) [0, 8, 16, 24]
octetsBE :: Word32 -> [Word8]
octetsBE = reverse . octetsLE
fromOctetsBE :: [Word8] -> Word32
fromOctetsBE = foldl' accum 0
where
accum a o = (a `shiftL` 8) .|. fromIntegral o
fromOctetsLE :: [Word8] -> Word32
fromOctetsLE = fromOctetsBE . reverse
randApply
:: PrimMonad m
=> a
-> (a -> a)
-> (Int, Int)
-> Gen (PrimState m)
-> m a
randApply a f (x, y) rng
| x < 1 = error "randApply: numerator x is less than 1"
| y < 2 = error "randApply: denominator d is less than 2"
| x >= y = error "randApply: numerator is greater than denominator"
| otherwise = do
r <- uniformR (0, y - 1) rng
if (r < x)
then return (f a)
else return a
-- | Simulate an n-sided die, by randomly choosing a number from the interval
-- [1, n]. If n is 2, it is like a coin flip.
roll :: PrimMonad m => Int -> Gen (PrimState m) -> m Int
roll n
| n < 2 = error "roll argument less than 2"
| otherwise = uniformR (1, n)
| listx/netherworld | src/NW/Random.hs | bsd-2-clause | 3,970 | 46 | 15 | 841 | 1,483 | 768 | 715 | 104 | 4 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.