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 Rebase.Data.Text.Internal
(
module Data.Text.Internal
)
where
import Data.Text.Internal
|
nikita-volkov/rebase
|
library/Rebase/Data/Text/Internal.hs
|
mit
| 98 | 0 | 5 | 12 | 23 | 16 | 7 | 4 | 0 |
-- vim: ts=2:sw=2:sts=2
{-# LANGUAGE FlexibleInstances, MultiParamTypeClasses, DeriveDataTypeable, TypeSynonymInstances #-}
module XMonad.Config.Amer.Layout (
MyTransformers(..)
) where
import XMonad (Typeable, Window)
import XMonad.Layout (Full(..))
import XMonad.Layout.NoBorders (noBorders)
import XMonad.Layout.Spacing (smartSpacing)
import XMonad.Hooks.ManageDocks (avoidStruts)
import XMonad.Layout.LayoutModifier (ModifiedLayout(..))
import XMonad.Layout.MultiToggle (Transformer(..))
data MyTransformers = STRUTS
| GAPS
deriving (Read, Show, Eq, Typeable)
instance Transformer MyTransformers Window where -- (const x)
transform STRUTS x k = k (avoidStruts x) (\(ModifiedLayout _ x') -> x')
-- TODO: inherit value from global conf? How to extend myCfg in-place on the fly?
transform GAPS x k = k (smartSpacing 8 x) (\(ModifiedLayout _ x') -> x')
|
amerlyq/airy
|
xmonad/cfg/Layout.hs
|
mit
| 961 | 0 | 10 | 207 | 228 | 135 | 93 | 16 | 0 |
{-
HAAP: Haskell Automated Assessment Platform
This module provides functions for processing Literate Haskell source code files.
-}
{-# LANGUAGE BangPatterns, FlexibleContexts #-}
module HAAP.Code.Literate.Haskell
(
lhs2hs, lhs2lhs, compileLHS
) where
import HAAP.Core
import HAAP.IO
import HAAP.Shelly
import HAAP.Pretty
import HAAP.Plugin
import Data.Generics
import Data.List as List
import Data.Maybe
import qualified Data.Map as Map
import Data.Map (Map(..))
import qualified Data.Text as T
import Language.Haskell.Exts
import System.FilePath.Find as FilePath
import System.FilePath
import Control.Monad.IO.Class
--import Control.Monad.Except
import System.IO
import Control.Monad
import Data.List
import System.FilePath
import System.Directory
import Safe
import qualified Shelly as Sh
import Shelly (Sh(..))
-- | Select only the Haskell code from a lhs file
-- the output is hs
lhs2hs :: FilePath -> FilePath -> Sh ()
lhs2hs file outfile = run True True file outfile --(addExtension (dropExtension file) "hs")
-- | Select only the latex code from a lhs file
-- the result is still lhs and not tex
lhs2lhs :: FilePath -> FilePath -> Sh ()
lhs2lhs file outfile = run True False file outfile
run doHaddock doCode file resfile =
do
when (not $ endsWith ".lhs" file) $ do
liftIO $ putStrLn "You should invoke .lhs-files!"
when (doHaddock) $ do
liftIO $ putStrLn $ "Performing Haddock-Transformation on " ++ file
c <- shReadFile' file
shWriteFile' resfile (perform (haddock doCode) c)
endsWith x = elem x . tails
perform f = T.unlines. map T.pack . f . map T.unpack . T.lines
haddock:: Bool -> [String] -> [String]
haddock doCode [] = []
haddock doCode a@(x:xs)
| startsWith "\\begin{code}" x = let (p1,p2) = splitCond (startsWith "\\end{code}") xs in
(if doCode then p1 else []) ++ haddock doCode (tailSafe p2)
| x == [] = []:haddock doCode xs
| doCode && headNote "haddock2" x == '>' = tailSafe x:haddock doCode xs
--tex code
| doCode && startsWith "%%Haddock:" x =
let (p1,p2) = splitCond (not.startsWith "%%Haddock:") a in
"{-|":map (tailSafe . dropWhile (/=':')) p1 ++ "-}":haddock doCode p2
| otherwise = (if doCode then [] else [x]) ++ haddock doCode xs
startsWith [] _ = True
startsWith _ [] = False
startsWith (x:xs) (y:ys) = x == y && startsWith xs ys
splitCond::(a->Bool)->[a]->([a],[a])
splitCond p [] = ([],[])
splitCond p (x:xs)
| p x = ([], x:xs)
| otherwise = let (p1,p2) = splitCond p xs in (x:p1,p2)
compileLHS :: (MonadIO m,HaapStack t m) => FilePath -> Haap t m Bool
compileLHS path = do
let dir = takeDirectory path
let file = takeFileName path
let texfile = replaceExtension file "tex"
let pdffile = replaceExtension file "pdf"
!shok <- runBaseSh $ liftM (either (const False) (const True)) $ orEitherSh $ Sh.escaping False $ do
--liftIO $ putStrLn $ dir
--liftIO $ putStrLn $ file
shCd dir
shRm pdffile
shCommand_ "lhs2tex" [file++">"++texfile]
shCommand_ "pdflatex" ["-interaction=nonstopmode",texfile]
--runBaseIO' $ ioCommand_ "pdflatex" ["-interaction=nonstopmode",dir </> texfile]
!texok <- runBaseIO' $ doesFileExist $ dir </> pdffile
return $! shok && texok
|
hpacheco/HAAP
|
src/HAAP/Code/Literate/Haskell.hs
|
mit
| 3,350 | 0 | 16 | 738 | 1,127 | 582 | 545 | 73 | 3 |
module Lessons.Lesson6 where
import Geometry
quadrilateral [a,b,c,d] | across c (a,b) d = (d,b,c,a)
| across a (b,c) d = (a,b,d,c)
| otherwise = (a,b,c,d)
|
alphalambda/k12math
|
prog/lib/geo/Lessons/Lesson6.hs
|
mit
| 206 | 0 | 9 | 76 | 115 | 66 | 49 | 5 | 1 |
-- Algorithms/Sorting/Insertion Sort - Part 1
module Main where
import qualified HackerRank.Algorithms.InsertionSortPart1 as M
main :: IO ()
main = M.main
|
4e6/sandbox
|
haskell/hackerrank/InsertionSortPart1.hs
|
mit
| 158 | 0 | 6 | 24 | 31 | 20 | 11 | 4 | 1 |
{-# htermination minFM :: Ord a => FiniteMap [a] b -> Maybe [a] #-}
import FiniteMap
|
ComputationWithBoundedResources/ara-inference
|
doc/tpdb_trs/Haskell/full_haskell/FiniteMap_minFM_4.hs
|
mit
| 85 | 0 | 3 | 16 | 5 | 3 | 2 | 1 | 0 |
-- |Netrium is Copyright Anthony Waite, Dave Hewett, Shaun Laurens & Contributors 2009-2018, and files herein are licensed
-- |under the MIT license, the text of which can be found in license.txt
--
-- The definition of the basic contract language
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
module Contract (
-- * Contracts
-- ** The contract type and primitives
Contract(..),
zero, one,
and, give, party,
or, cond,
scale, ScaleFactor,
when, anytime, until,
read, letin,
-- ** Tradable items
Tradeable(..),
Commodity(..), Unit(..), Location(..), Duration(..),
Currency(..), CashFlowType(..), Portfolio(..),
-- ** Choice identifiers
ChoiceId, PartyName,
-- * Observables
Obs,
konst, var, primVar, primCond,
Time,
at, before, after, between,
ifthen, negate, max, min, abs,
(%==),
(%>), (%>=), (%<), (%<=),
(%&&), (%||),
(%+), (%-), (%*), (%/),
) where
import Observable
( Time
, Obs, konst, var, primVar, primCond, at, before, after, between
, (%==), (%>), (%>=), (%<), (%<=)
, (%&&), (%||), (%+), (%-), (%*), (%/)
, ifthen, negate, max, min, abs
, parseObsCond, parseObsReal, printObs )
import Display
import XmlUtils
import Prelude hiding (product, read, until, and, or, min, max, abs, not, negate)
import Control.Monad hiding (when)
import Text.XML.HaXml.Namespaces (localName)
import Text.XML.HaXml.Types (QName(..))
import Text.XML.HaXml.XmlContent
-- * Contract type definition
-- | A canonical tradeable element, physical or financial
data Tradeable = Physical Commodity Unit Location (Maybe Duration) (Maybe Portfolio)
| Financial Currency CashFlowType (Maybe Portfolio)
deriving (Eq, Show)
-- | A duration is a span of time, measured in seconds.
--
newtype Duration = Duration Int {- in sec -} deriving (Eq, Show, Num)
-- | Commodity, e.g. Gas, Electricity
newtype Commodity = Commodity String deriving (Eq, Show)
-- | Unit, e.g. tonnes, MWh
newtype Unit = Unit String deriving (Eq, Show)
-- | Location, e.g. UK, EU
newtype Location = Location String deriving (Eq, Show)
-- | Currency, e.g. EUR, USD, GBP
newtype Currency = Currency String deriving (Eq, Show)
-- | Cashflow type, e.g. cash, premium
newtype CashFlowType = CashFlowType String deriving (Eq, Show)
-- | Portfolio name
newtype Portfolio = Portfolio String deriving (Eq, Show)
-- | Scaling factor (used to scale the 'One' contract)
type ScaleFactor = Double
-- | Choice label, used for options
type ChoiceId = String
-- | Name of a third party mentioned in a contract
type PartyName = String
-- | The main contract data type
--
data Contract
= Zero
| One Tradeable
| Give Contract
| Party PartyName Contract
| And Contract Contract
| Or ChoiceId Contract Contract
| Cond (Obs Bool) Contract Contract
| Scale (Obs Double) Contract
| Read Var (Obs Double) Contract
| When (Obs Bool) Contract
| Anytime ChoiceId (Obs Bool) Contract
| Until (Obs Bool) Contract
deriving (Eq, Show)
-- | A variable
type Var = String
-- | The @zero@ contract has no rights and no obligations.
zero :: Contract
zero = Zero
-- | If you acquire @one t@ you immediately recieve one unit of the
-- 'Tradeable' @t@.
one :: Tradeable -> Contract
one = One
-- | Swap the rights and obligations of the party and counterparty.
give :: Contract -> Contract
give = Give
-- | Make a contract with a named 3rd party as the counterparty.
party :: PartyName -> Contract -> Contract
party = Party
-- | If you acquire @c1 `and` c2@ you immediately acquire /both/ @c1@ and @c2@.
and :: Contract -> Contract -> Contract
and = And
-- | If you acquire @c1 `or` c2@ you immediately acquire your choice of
-- /either/ @c1@ or @c2@.
or :: ChoiceId -> Contract -> Contract -> Contract
or = Or
--TODO: document the ChoiceId
-- | If you acquire @cond obs c1 c2@ then you acquire @c1@ if the observable
-- @obs@ is true /at the moment of acquistion/, and @c2@ otherwise.
cond :: Obs Bool -> Contract -> Contract -> Contract
cond = Cond
-- | If you acquire @scale obs c@, then you acquire @c@ at the same moment
-- except that all the subsequent trades of @c@ are multiplied by the value
-- of the observable @obs@ /at the moment of acquistion/.
scale :: Obs ScaleFactor -> Contract -> Contract
scale = Scale
read :: Var -> Obs Double -> Contract -> Contract
read = Read
{-# DEPRECATED read "Use 'letin' instead." #-}
-- | If you acquire @when obs c@, you must acquire @c@ as soon as observable
-- @obs@ subsequently becomes true.
when :: Obs Bool -> Contract -> Contract
when = When
-- | Once you acquire @anytime obs c@, you /may/ acquire @c@ at any time the
-- observable @obs@ is true.
anytime :: ChoiceId -> Obs Bool -> Contract -> Contract
anytime = Anytime
-- | Once acquired, @until obs c@ is exactly like @c@ except that it /must be
-- abandoned/ when observable @obs@ becomes true.
until :: Obs Bool -> Contract -> Contract
until = Until
-- | Observe the value of an observable now and save its value to use later.
--
-- Currently this requires a unique variable name.
--
-- Example:
--
-- > letin "count" (count-1) $ \count' ->
-- > ...
--
letin :: String -- ^ A unique variable name
-> Obs Double -- ^ The observable to observe now
-> (Obs Double -> Contract) -- ^ The contract using the observed value
-> Contract
letin vname obs c = read vname obs (c (var vname))
-- Display tree instances
instance Display Contract where
toTree Zero = Node "zero" []
toTree (One t) = Node "one" [Node (show t) []]
toTree (Give c) = Node "give" [toTree c]
toTree (Party p c) = Node ("party " ++ p)[toTree c]
toTree (And c1 c2) = Node "and" [toTree c1, toTree c2]
toTree (Or cid c1 c2) = Node ("or " ++ cid) [toTree c1, toTree c2]
toTree (Cond o c1 c2) = Node "cond" [toTree o, toTree c1, toTree c2]
toTree (Scale o c) = Node "scale" [toTree o, toTree c]
toTree (Read n o c) = Node ("read " ++ n) [toTree o, toTree c]
toTree (When o c) = Node "when" [toTree o, toTree c]
toTree (Anytime cid o c) = Node ("anytime" ++ cid) [toTree o, toTree c]
toTree (Until o c) = Node "until" [toTree o, toTree c]
-- XML instances
instance HTypeable Tradeable where
toHType _ = Defined "Tradeable" [] []
instance XmlContent Tradeable where
parseContents = do
e@(Elem t _ _) <- element ["Physical","Financial"]
commit $ interior e $ case localName t of
"Physical" -> liftM5 Physical parseContents parseContents
parseContents parseContents
parseContents
"Financial" -> liftM3 Financial parseContents parseContents
parseContents
x -> fail $ "cannot parse " ++ x
toContents (Physical c u l d p) =
[mkElemC "Physical" (toContents c ++ toContents u
++ toContents l ++ toContents d
++ toContents p)]
toContents (Financial c t p) =
[mkElemC "Financial" (toContents c ++ toContents t
++ toContents p)]
instance HTypeable Duration where
toHType _ = Defined "Duration" [] []
instance XmlContent Duration where
parseContents = inElement "Duration" (liftM Duration readText)
toContents (Duration sec) = [mkElemC "Duration" (toText (show sec))]
instance HTypeable Commodity where
toHType _ = Defined "Commodity" [] []
instance XmlContent Commodity where
parseContents = inElement "Commodity" (liftM Commodity text)
toContents (Commodity name) = [mkElemC "Commodity" (toText name)]
instance HTypeable Unit where
toHType _ = Defined "Unit" [] []
instance XmlContent Unit where
parseContents = inElement "Unit" (liftM Unit text)
toContents (Unit name) = [mkElemC "Unit" (toText name)]
instance HTypeable Location where
toHType _ = Defined "Location" [] []
instance XmlContent Location where
parseContents = inElement "Location" (liftM Location text)
toContents (Location name) = [mkElemC "Location" (toText name)]
instance HTypeable Currency where
toHType _ = Defined "Currency" [] []
instance XmlContent Currency where
parseContents = inElement "Currency" (liftM Currency text)
toContents (Currency name) = [mkElemC "Currency" (toText name)]
instance HTypeable CashFlowType where
toHType _ = Defined "CashFlowType" [] []
instance XmlContent CashFlowType where
parseContents = inElement "CashFlowType" (liftM CashFlowType text)
toContents (CashFlowType name) = [mkElemC "CashFlowType" (toText name)]
instance HTypeable Portfolio where
toHType _ = Defined "Portfolio" [] []
instance XmlContent Portfolio where
parseContents = inElement "Portfolio" (liftM Portfolio text)
toContents (Portfolio name) = [mkElemC "Portfolio" (toText name)]
instance HTypeable Contract where
toHType _ = Defined "Contract" [] []
instance XmlContent Contract where
parseContents = do
e@(Elem t _ _) <- element ["Zero","When","Until","Scale","Read"
,"Or","One","Give","Party","Cond","Anytime","And"]
commit $ interior e $ case localName t of
"Zero" -> return Zero
"One" -> liftM One parseContents
"Give" -> liftM Give parseContents
"Party" -> liftM2 Party (attrStr (N "name") e) parseContents
"And" -> liftM2 And parseContents parseContents
"Or" -> liftM3 Or (attrStr (N "choiceid") e) parseContents parseContents
"Cond" -> liftM3 Cond parseObsCond parseContents parseContents
"Scale" -> liftM2 Scale parseObsReal parseContents
"Read" -> liftM3 Read (attrStr (N "var") e) parseObsReal parseContents
"When" -> liftM2 When parseObsCond parseContents
"Anytime" -> liftM3 Anytime (attrStr (N "choiceid") e) parseObsCond parseContents
"Until" -> liftM2 Until parseObsCond parseContents
x -> fail $ "cannot parse " ++ x
toContents Zero = [mkElemC "Zero" []]
toContents (One t) = [mkElemC "One" (toContents t)]
toContents (Give c) = [mkElemC "Give" (toContents c)]
toContents (Party p c) = [mkElemAC (N "Party") [(N "name", str2attr p)]
(toContents c)]
toContents (And c1 c2) = [mkElemC "And" (toContents c1 ++ toContents c2)]
toContents (Or cid c1 c2) = [mkElemAC (N "Or") [(N "choiceid", str2attr cid)]
(toContents c1 ++ toContents c2)]
toContents (Cond o c1 c2) = [mkElemC "Cond" (printObs o : toContents c1 ++ toContents c2)]
toContents (Scale o c) = [mkElemC "Scale" (printObs o : toContents c)]
toContents (Read n o c) = [mkElemAC (N "Read") [(N "var", str2attr n)]
(printObs o : toContents c)]
toContents (When o c) = [mkElemC "When" (printObs o : toContents c)]
toContents (Anytime cid o c) = [mkElemAC (N "Anytime") [(N "choiceid", str2attr cid)]
(printObs o : toContents c)]
toContents (Until o c) = [mkElemC "Until" (printObs o : toContents c)]
|
netrium/Netrium
|
src/Contract.hs
|
mit
| 11,527 | 0 | 16 | 3,053 | 3,218 | 1,742 | 1,476 | 197 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Main
( main
) where
import Text.Regex.Base.RegexLike
import Text.Regex.PCRE.ByteString
import Data.Traversable
import qualified Data.ByteString as BS
main :: IO ()
main = do
let rawSample = "[VER:v=12.45|stuff1|stuff2|stuff3[X], extra1, extra2, extra 3]"
Right re <- compile blankCompOpt blankExecOpt "\\[VER:v=(\\d+\\.\\d+)((\\|[a-z0-9]+(\\[X\\])?)+)(, .*)*\\]"
Right (Just r) <- execute re rawSample
forM r $ \(offset, len) ->
print (BS.take len $ BS.drop offset rawSample)
pure ()
|
Javran/misc
|
regex-playground/src/Main.hs
|
mit
| 547 | 0 | 13 | 87 | 150 | 78 | 72 | 15 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE ViewPatterns #-}
module Hpack.Syntax.BuildTools (
BuildTools(..)
, ParseBuildTool(..)
, SystemBuildTools(..)
) where
import Data.Text (Text)
import qualified Data.Text as T
import Data.Semigroup (Semigroup(..))
import Data.Bifunctor
import Control.Applicative
import qualified Distribution.Package as D
import Data.Map.Lazy (Map)
import qualified Data.Map.Lazy as Map
import qualified Distribution.Types.ExeDependency as D
import qualified Distribution.Types.UnqualComponentName as D
import qualified Distribution.Types.LegacyExeDependency as D
import Data.Aeson.Config.FromValue
import Hpack.Syntax.DependencyVersion
import Hpack.Syntax.Dependencies (parseDependency)
import Hpack.Syntax.ParseDependencies
data ParseBuildTool = QualifiedBuildTool String String | UnqualifiedBuildTool String
deriving (Show, Eq)
newtype BuildTools = BuildTools {
unBuildTools :: [(ParseBuildTool, DependencyVersion)]
} deriving (Show, Eq, Semigroup, Monoid)
instance FromValue BuildTools where
fromValue = fmap BuildTools . parseDependencies parse
where
parse :: Parse ParseBuildTool DependencyVersion
parse = Parse {
parseString = buildToolFromString
, parseListItem = objectDependency
, parseDictItem = dependencyVersion
, parseName = nameToBuildTool
}
nameToBuildTool :: Text -> ParseBuildTool
nameToBuildTool (T.unpack -> name) = case break (== ':') name of
(executable, "") -> UnqualifiedBuildTool executable
(package, executable) -> QualifiedBuildTool package (drop 1 executable)
buildToolFromString :: Text -> Parser (ParseBuildTool, DependencyVersion)
buildToolFromString s = parseQualifiedBuildTool s <|> parseUnqualifiedBuildTool s
parseQualifiedBuildTool :: Monad m => Text -> m (ParseBuildTool, DependencyVersion)
parseQualifiedBuildTool = fmap fromCabal . cabalParse "build tool" . T.unpack
where
fromCabal :: D.ExeDependency -> (ParseBuildTool, DependencyVersion)
fromCabal (D.ExeDependency package executable version) = (
QualifiedBuildTool (D.unPackageName package) (D.unUnqualComponentName executable)
, DependencyVersion Nothing $ versionConstraintFromCabal version
)
parseUnqualifiedBuildTool :: Monad m => Text -> m (ParseBuildTool, DependencyVersion)
parseUnqualifiedBuildTool = fmap (first UnqualifiedBuildTool) . parseDependency "build tool"
newtype SystemBuildTools = SystemBuildTools {
unSystemBuildTools :: Map String VersionConstraint
} deriving (Show, Eq, Semigroup, Monoid)
instance FromValue SystemBuildTools where
fromValue = fmap (SystemBuildTools . Map.fromList) . parseDependencies parse
where
parse :: Parse String VersionConstraint
parse = Parse {
parseString = parseSystemBuildTool
, parseListItem = (.: "version")
, parseDictItem = versionConstraint
, parseName = T.unpack
}
parseSystemBuildTool :: Monad m => Text -> m (String, VersionConstraint)
parseSystemBuildTool = fmap fromCabal . cabalParse "system build tool" . T.unpack
where
fromCabal :: D.LegacyExeDependency -> (String, VersionConstraint)
fromCabal (D.LegacyExeDependency name version) = (name, versionConstraintFromCabal version)
|
haskell-tinc/hpack
|
src/Hpack/Syntax/BuildTools.hs
|
mit
| 3,490 | 0 | 14 | 722 | 787 | 449 | 338 | 64 | 0 |
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TypeFamilies #-}
-------------------------------------------
-- |
-- Module : Web.Stripe.Charge
-- Copyright : (c) David Johnson, 2014
-- Maintainer : [email protected]
-- Stability : experimental
-- Portability : POSIX
--
-- < https:/\/\stripe.com/docs/api#charges >
--
-- @
-- {-\# LANGUAGE OverloadedStrings \#-}
-- import Web.Stripe
-- import Web.Stripe.Customer
-- import Web.Stripe.Charge
--
-- main :: IO ()
-- main = do
-- let config = StripeConfig (StripeKey "secret_key")
-- credit = CardNumber "4242424242424242"
-- em = ExpMonth 12
-- ey = ExpYear 2015
-- cvc = CVC "123"
-- cardinfo = (newCard credit em ey) { newCardCVC = Just cvc }
-- result <- stripe config createCustomer
-- -&- cardinfo
-- case result of
-- (Left stripeError) -> print stripeError
-- (Customer { customerId = cid }) ->
-- do result <- stripe config $ createCharge (Amount 100) USD
-- -&- cid
-- case result of
-- Left stripeError -> print stripeError
-- Right charge -> print charge
-- @
module Web.Stripe.Charge
( -- * API
---- * Create Charges
CreateCharge
, createCharge
---- * Get Charge(s)
, GetCharge
, getCharge
, GetCharges
, getCharges
---- * Update Charge
, UpdateCharge
, updateCharge
---- * Capture Charge
, CaptureCharge
, captureCharge
-- * Types
, Amount (..)
, ApplicationFeeAmount(..)
, CardNumber (..)
, Capture (..)
, Charge (..)
, ChargeId (..)
, Created (..)
, Currency (..)
, CustomerId (..)
, Customer (..)
, CVC (..)
, Description (..)
, Email (..)
, EndingBefore (..)
, ExpandParams (..)
, ExpMonth (..)
, ExpYear (..)
, Limit (..)
, MetaData (..)
, NewCard (..)
, ReceiptEmail (..)
, StartingAfter (..)
, StatementDescription (..)
, StripeList (..)
, TokenId (..)
) where
import Web.Stripe.StripeRequest (Method (GET, POST),
StripeHasParam, ToStripeParam(..),
StripeRequest (..), StripeReturn,
mkStripeRequest)
import Web.Stripe.Util ((</>))
import Web.Stripe.Types (Amount(..), ApplicationFeeAmount(..),
CVC (..),
Capture(..),
CardNumber (..), Charge (..),
ChargeId (..), Created(..),
Currency (..), Customer(..),
CustomerId (..), Description(..),
EndingBefore(..), ExpMonth (..),
ExpYear (..), Limit(..), MetaData(..),
NewCard(..), Email (..),
StartingAfter(..),
ReceiptEmail(..),
StatementDescription(..),
ExpandParams(..),
StripeList (..), TokenId (..))
import Web.Stripe.Types.Util (getChargeId)
------------------------------------------------------------------------------
-- | Create a `Charge`
createCharge
:: Amount -- ^ `Amount` to charge
-> Currency -- ^ `Currency` for charge
-> StripeRequest CreateCharge
createCharge
amount
currency = request
where request = mkStripeRequest POST url params
url = "charges"
params = toStripeParam amount $
toStripeParam currency $
[]
data CreateCharge
type instance StripeReturn CreateCharge = Charge
instance StripeHasParam CreateCharge ExpandParams
instance StripeHasParam CreateCharge CustomerId
instance StripeHasParam CreateCharge NewCard
instance StripeHasParam CreateCharge TokenId
instance StripeHasParam CreateCharge Description
instance StripeHasParam CreateCharge MetaData
instance StripeHasParam CreateCharge Capture
instance StripeHasParam CreateCharge StatementDescription
instance StripeHasParam CreateCharge ReceiptEmail
instance StripeHasParam CreateCharge ApplicationFeeAmount
------------------------------------------------------------------------------
-- | Retrieve a `Charge` by `ChargeId`
getCharge
:: ChargeId -- ^ The `Charge` to retrive
-> StripeRequest GetCharge
getCharge
chargeid = request
where request = mkStripeRequest GET url params
url = "charges" </> getChargeId chargeid
params = []
data GetCharge
type instance StripeReturn GetCharge = Charge
instance StripeHasParam GetCharge ExpandParams
------------------------------------------------------------------------------
-- | A `Charge` to be updated
updateCharge
:: ChargeId -- ^ The `Charge` to update
-> StripeRequest UpdateCharge
updateCharge
chargeid = request
where request = mkStripeRequest POST url params
url = "charges" </> getChargeId chargeid
params = []
data UpdateCharge
type instance StripeReturn UpdateCharge = Charge
instance StripeHasParam UpdateCharge Description
instance StripeHasParam UpdateCharge MetaData
------------------------------------------------------------------------------
-- | a `Charge` to be captured
captureCharge
:: ChargeId -- ^ The `ChargeId` of the `Charge` to capture
-> StripeRequest CaptureCharge
captureCharge
chargeid = request
where request = mkStripeRequest POST url params
url = "charges" </> getChargeId chargeid </> "capture"
params = []
data CaptureCharge
type instance StripeReturn CaptureCharge = Charge
instance StripeHasParam CaptureCharge Amount
instance StripeHasParam CaptureCharge ReceiptEmail
------------------------------------------------------------------------------
-- | Retrieve all `Charge`s
getCharges
:: StripeRequest GetCharges
getCharges = request
where request = mkStripeRequest GET url params
url = "charges"
params = []
data GetCharges
type instance StripeReturn GetCharges = StripeList Charge
instance StripeHasParam GetCharges ExpandParams
instance StripeHasParam GetCharges Created
instance StripeHasParam GetCharges CustomerId
instance StripeHasParam GetCharges (EndingBefore ChargeId)
instance StripeHasParam GetCharges Limit
instance StripeHasParam GetCharges (StartingAfter ChargeId)
|
dmjio/stripe
|
stripe-core/src/Web/Stripe/Charge.hs
|
mit
| 6,989 | 0 | 9 | 2,224 | 1,059 | 654 | 405 | -1 | -1 |
{-# LANGUAGE OverloadedStrings #-}
module Document.Tests.TrainStation
( test_case )
where
-- Modules
import Document.Tests.Suite -- (verify,find_errors,proof_obligation)
import Logic.Expr
import qualified Logic.Expr.Const as Expr
import Logic.Expr.Parser
import Logic.Proof
import Logic.QuasiQuote
import Logic.Theories.SetTheory
import Logic.Theories.FunctionTheory
import Logic.Theories.Arithmetic
-- Libraries
import Control.Lens hiding (elements,universe,indices)
import Control.Lens.Misc hiding (combine)
import Control.Monad.State
import qualified Data.List.NonEmpty as NE
import Data.Map as M hiding ( map )
import Test.UnitTest
test_case :: TestCase
test_case = test
test :: TestCase
test = test_cases
"train station example"
[ part0
, part1
, part2
, part3
, part4
, part5
]
part0 :: TestCase
part0 = test_cases
"part 0"
[ (aCase "test 0, syntax" case0 $ Right [machine0])
, (stringCase "test 21, multiple imports of sets" case21 result21)
]
part1 :: TestCase
part1 = test_cases
"part 1"
[ (poCase "test 1, verification" case1 result1)
, (stringCase "test 2, proof obligation, enter/fis, in" case2 result2)
, (stringCase "test 20, proof obligation, enter/fis, loc" case20 result20)
, (stringCase "test 3, proof obligation, leave/fis, in'" case3 result3)
, (stringCase "test 19, proof obligation, leave/fis, loc'" case19 result19)
, (stringCase "test 4, proof obligation, leave/sch" case4 result4)
]
part2 :: TestCase
part2 = test_cases
"part 2"
[ (stringCase "test 5, proof obligation, leave/en/tr0/WFIS" case5 result5)
, (stringCase "test 23, proof obligation, leave/en/tr0/EN" case23 result23)
, (stringCase "test 24, proof obligation, leave/en/tr0/NEG" case24 result24)
, (aCase "test 7, undeclared symbol" case7 result7)
, (aCase "test 8, undeclared event (wrt transient)" case8 result8)
, (aCase "test 9, undeclared event (wrt c sched)" case9 result9)
]
part3 :: TestCase
part3 = test_cases
"part 3"
[ (aCase "test 10, undeclared event (wrt indices)" case10 result10)
, (aCase "test 11, undeclared event (wrt assignment)" case11 result11)
, (stringCase "test 12, proof obligation leave/INV/inv2" case12 result12)
]
part4 :: TestCase
part4 = test_cases
"part 4"
[ (stringCase "test 13, verification, name clash between dummy and index" case13 result13)
, (poCase "test 14, verification, non-exhaustive case analysis" case14 result14)
, (poCase "test 15, verification, incorrect new assumption" case15 result15)
]
part5 :: TestCase
part5 = test_cases
"part 5"
[ (poCase "test 16, verification, proof by parts" case16 result16)
, (stringCase "test 17, ill-defined types" case17 result17)
, (stringCase "test 18, assertions have type bool" case18 result18)
, (stringCase "test 22, missing witness" case22 result22)
]
train_sort :: Sort
train_sort = z3Sort "\\TRAIN" "sl$TRAIN" 0
train_type :: Type
train_type = Gen train_sort []
loc_sort :: Sort
loc_sort = z3Sort "\\LOC" "sl$LOC" 0
loc_type :: Type
loc_type = Gen loc_sort []
blk_sort :: Sort
blk_sort = z3Sort "\\BLK" "sl$BLK" 0
blk_type :: Type
blk_type = Gen blk_sort []
universe :: Type -> Expr
train_def :: Def
loc_def :: Def
block_def :: Def
universe t = (zlift (set_type t) ztrue)
train_def = z3Def [] "sl$TRAIN" [] (set_type train_type) (universe train_type)
loc_def = z3Def [] "sl$LOC" [] (set_type loc_type) (universe loc_type)
block_def = z3Def [] "sl$BLK" [] (set_type blk_type) (universe blk_type)
_ent :: ExprP
_ext :: ExprP
_plf :: ExprP
ent_var :: Var
ext_var :: Var
plf_var :: Var
(_ent,ent_var) = (Expr.var "ent" $ blk_type)
(_ext,ext_var) = (Expr.var "ext" $ blk_type)
(_plf,plf_var) = (Expr.var "PLF" $ set_type blk_type)
trainName :: Name
trainName = fromString'' "train0"
machine0 :: MachineAST
machine0 = newMachine trainName $ do
theory .= (empty_theory trainName)
{ _extends = symbol_table
[ function_theory
, set_theory
, basic_theory
, arithmetic
]
, _theory'Defs = symbol_table
[ train_def
, loc_def
, block_def ]
, _types = symbol_table
[ train_sort
, loc_sort
, blk_sort
]
, _theory'Dummies = symbol_table
$ (map (\t -> z3Var t $ train_type)
[ "t","t_0","t_1","t_2","t_3" ]
++ map (\t -> z3Var t $ blk_type)
[ "p","q" ])
, _fact = fromList
[ ("axm0", axm0)
, ("asm2", axm2)
, ("asm3", axm3)
, ("asm4", axm4)
, ("asm5", axm5)
]
, _consts = symbol_table
[ ent_var
, ext_var
, plf_var
]
}
inits .= fromList (zip inLbls
$ [ c [expr| loc = \emptyfun |]
, c [expr| in = \emptyset |] ] )
variables .= vars
event_table .= newEvents [("enter", enter_evt), ("leave", leave_evt)]
props .= props0
where
inLbls = map (label . ("in" ++) . show . (1 -)) [0..]
axm0 = c [expr| \BLK = \{ent,ext\} \bunion PLF |]
axm2 = c [expr| \neg ent = ext \land \neg ent \in PLF \land \neg ext \in PLF |]
axm3 = c [expr| \qforall{p}{}{ \neg p = ext \equiv p \in \{ent\} \bunion PLF } |]
axm4 = c [expr| \qforall{p}{}{ \neg p = ent \equiv p \in \{ext\} \bunion PLF } |]
axm5 = c [expr| \qforall{p}{}{ p = ent \lor p = ext \equiv \neg p \in PLF } |]
vars :: Map Name Var
vars = symbol_table [in_decl,loc_decl]
c :: Ctx
c = ctxWith [set_theory,function_theory] $ do
[carrier| \TRAIN |]
[carrier| \LOC |]
[carrier| \BLK |]
[var| ent, ext : \BLK |]
[var| PLF : \set [\BLK] |]
primable $ do
[var| loc : \TRAIN \pfun \BLK |]
[var| in : \set [\TRAIN] |]
[var| t : \TRAIN |]
props0 :: PropertySet
props0 = create $ do
constraint .= fromList
[ ( "co0"
, Co [t_decl]
$ c $ [expr| \neg t \in in \land t \in in' \implies loc'.t = ent |] . (is_step .~ True))
, ( "co1"
, Co [t_decl]
$ c $ [expr| t \in in \land loc.t = ent \land \neg loc.t \in PLF
\implies t \in in'
\land (loc'.t \in PLF \1\lor loc'.t = ent) |] . (is_step .~ True) )
]
transient .= fromList
[ ( "tr0"
, Tr
(symbol_table [t_decl])
(c $ [expr| t \in in |].(free_dummies .~ True)) (NE.fromList ["leave"])
(TrHint (fromList [(fromString'' "t",(train_type, c $ [expr| t' = t |] . (is_step .~ True)))]) Nothing) )
]
inv .= fromList
[ ("inv2", c [expr| \dom.loc = in |])
, ("inv1", c [expr| \qforall{t}{t \in in}{loc.t \in \BLK} |])
]
safety .= fromList
[]
enter_evt :: Event
enter_evt = flip execState empty_event $ do
indices .= symbol_table [t_decl]
coarse_sched .= fromList
[ ("default", zfalse )]
raw_guards .= fromList
[ ("grd1", c [expr| \neg t \in in |])
]
actions .= fromList
[ ("a1", BcmSuchThat (M.elems vars)
(c $ [expr| in' = in \bunion \{ t \} |] . (is_step .~ True)))
, ("a2", BcmSuchThat (M.elems vars)
(c $ [expr| loc' = loc \1| t \fun ent |] . (is_step .~ True)))
]
leave_evt :: Event
leave_evt = flip execState empty_event $ do
indices .= symbol_table [t_decl]
coarse_sched .= singleton "c0" (c [expr| t \in in |])
raw_guards .= fromList
[ ("grd0", c [expr| loc.t = ext \1\land t \in in |] )
]
actions .= fromList
[ ("a0", BcmSuchThat (M.elems vars)
(c $ [expr| in' = in \1\setminus \{ t \} |] . (is_step .~ True)))
, ("a3", BcmSuchThat (M.elems vars)
(c $ [expr| loc' = \{t\} \domsub loc |] . (is_step .~ True)))
]
t_decl :: Var
in_decl :: Var
loc_decl :: Var
(_, t_decl) = Expr.var "t" train_type
(_, _, in_decl) = prog_var "in" (set_type train_type)
(_, _, loc_decl) = prog_var "loc" (fun_type train_type blk_type)
data AxiomOption = WithPFun
deriving Eq
path0 :: FilePath
path0 = [path|Tests/train-station.tex|]
case0 :: IO (Either [Error] [MachineAST])
case0 = (traverse.traverse %~ view' syntax) <$> parse path0
result1 :: String
result1 = unlines
[ " o train0/INIT/INV/inv1"
, " o train0/INIT/INV/inv2/goal"
, " o train0/INIT/INV/inv2/hypotheses"
, " o train0/INIT/INV/inv2/relation"
, " o train0/INIT/INV/inv2/step 1"
, " o train0/INIT/INV/inv2/step 2"
, " o train0/INIT/INV/inv2/step 3"
, " o train0/INV/WD"
, " o train0/SKIP/CO/co0"
, " o train0/SKIP/CO/co1"
, " o train0/co0/CO/WD"
, " o train0/co1/CO/WD"
, " o train0/enter/CO/co0/case 1/goal"
, " o train0/enter/CO/co0/case 1/hypotheses"
, " o train0/enter/CO/co0/case 1/relation"
, " o train0/enter/CO/co0/case 1/step 1"
, " o train0/enter/CO/co0/case 1/step 2"
, " o train0/enter/CO/co0/case 2/goal"
, " o train0/enter/CO/co0/case 2/hypotheses"
, " o train0/enter/CO/co0/case 2/relation"
, " o train0/enter/CO/co0/case 2/step 1"
, " o train0/enter/CO/co0/case 2/step 2"
, " o train0/enter/CO/co0/case 2/step 3"
, " o train0/enter/CO/co0/case 2/step 4"
, " o train0/enter/CO/co0/completeness"
, " o train0/enter/CO/co1/completeness"
, " o train0/enter/CO/co1/new assumption"
, " o train0/enter/CO/co1/part 1/goal"
, " o train0/enter/CO/co1/part 1/hypotheses"
, " o train0/enter/CO/co1/part 1/relation"
, " o train0/enter/CO/co1/part 1/step 1"
, " o train0/enter/CO/co1/part 1/step 2"
, " o train0/enter/CO/co1/part 2/case 1/goal"
, " o train0/enter/CO/co1/part 2/case 1/hypotheses"
, " o train0/enter/CO/co1/part 2/case 1/relation"
, " o train0/enter/CO/co1/part 2/case 1/step 1"
, " o train0/enter/CO/co1/part 2/case 1/step 2"
, " o train0/enter/CO/co1/part 2/case 2/assertion/hyp6/easy"
, " o train0/enter/CO/co1/part 2/case 2/main goal/goal"
, " o train0/enter/CO/co1/part 2/case 2/main goal/hypotheses"
, " o train0/enter/CO/co1/part 2/case 2/main goal/relation"
, " o train0/enter/CO/co1/part 2/case 2/main goal/step 1"
, " o train0/enter/CO/co1/part 2/case 2/main goal/step 2"
, " o train0/enter/CO/co1/part 2/case 2/main goal/step 3"
, " o train0/enter/CO/co1/part 2/completeness"
, " o train0/enter/FIS/in@prime"
, " o train0/enter/FIS/loc@prime"
, " o train0/enter/INV/inv1"
, " o train0/enter/INV/inv2/goal"
, " o train0/enter/INV/inv2/hypotheses"
, " o train0/enter/INV/inv2/relation"
, " o train0/enter/INV/inv2/step 1"
, " o train0/enter/INV/inv2/step 2"
, " o train0/enter/INV/inv2/step 3"
, " o train0/enter/INV/inv2/step 4"
, " o train0/enter/INV/inv2/step 5"
, " o train0/enter/SCH/grd1"
, " o train0/leave/CO/co0/assertion/hyp6/goal"
, " o train0/leave/CO/co0/assertion/hyp6/hypotheses"
, " o train0/leave/CO/co0/assertion/hyp6/relation"
, " o train0/leave/CO/co0/assertion/hyp6/step 1"
, " o train0/leave/CO/co0/assertion/hyp6/step 2"
, " o train0/leave/CO/co0/assertion/hyp6/step 3"
, " o train0/leave/CO/co0/main goal/goal"
, " o train0/leave/CO/co0/main goal/hypotheses"
, " o train0/leave/CO/co0/main goal/relation"
, " o train0/leave/CO/co0/main goal/step 1"
, " o train0/leave/CO/co0/main goal/step 2"
, " o train0/leave/CO/co0/main goal/step 3"
, " o train0/leave/CO/co0/main goal/step 4"
, " o train0/leave/CO/co0/new assumption"
, " o train0/leave/CO/co1/goal"
, " o train0/leave/CO/co1/hypotheses"
, " o train0/leave/CO/co1/relation"
, " o train0/leave/CO/co1/step 1"
, " o train0/leave/CO/co1/step 2"
, " o train0/leave/CO/co1/step 3"
, " o train0/leave/CO/co1/step 4"
, " o train0/leave/CO/co1/step 5"
, " o train0/leave/CO/co1/step 6"
, " o train0/leave/CO/co1/step 7"
, " o train0/leave/CO/co1/step 8"
, " o train0/leave/FIS/in@prime"
, " o train0/leave/FIS/loc@prime"
, " o train0/leave/INV/inv1"
, " o train0/leave/INV/inv2/goal"
, " o train0/leave/INV/inv2/hypotheses"
, " o train0/leave/INV/inv2/relation"
, " o train0/leave/INV/inv2/step 1"
, " o train0/leave/INV/inv2/step 2"
, " o train0/leave/INV/inv2/step 3"
, " o train0/leave/INV/inv2/step 4"
, " xxx train0/leave/SCH/grd0"
, " o train0/leave/WD/GRD"
, " o train0/tr0/TR/WFIS/t/t@prime"
, " o train0/tr0/TR/leave/EN"
, " o train0/tr0/TR/leave/NEG"
, "passed 96 / 97"
]
case1 :: IO (String, Map Label Sequent)
case1 = verify path0 0
result2 :: String
result2 = unlines
[ "; train0/enter/FIS/in@prime"
, "(set-option :auto-config false)"
, "(set-option :smt.timeout 3000)"
, "(declare-datatypes (a) ( (Maybe (Just (fromJust a)) Nothing) ))"
, "(declare-datatypes () ( (Null null) ))"
, "(declare-datatypes (a b) ( (Pair (pair (first a) (second b))) ))"
, "(define-sort guarded (a) (Maybe a))"
, "(declare-sort sl$BLK 0)"
, "; comment: we don't need to declare the sort Bool"
, "; comment: we don't need to declare the sort Int"
, "(declare-sort sl$LOC 0)"
, "; comment: we don't need to declare the sort Real"
, "(declare-sort sl$TRAIN 0)"
, "(define-sort pfun (a b) (Array a (Maybe b)))"
, "(define-sort set (a) (Array a Bool))"
, "(declare-const PLF (set sl$BLK))"
, "(declare-const ent sl$BLK)"
, "(declare-const ext sl$BLK)"
, "(declare-const in (set sl$TRAIN))"
, "(declare-const in@prime (set sl$TRAIN))"
, "(declare-const loc (pfun sl$TRAIN sl$BLK))"
, "(declare-const loc@prime (pfun sl$TRAIN sl$BLK))"
, "(declare-const t sl$TRAIN)"
, "(declare-fun apply@@sl$TRAIN@@sl$BLK"
, " ( (pfun sl$TRAIN sl$BLK)"
, " sl$TRAIN )"
, " sl$BLK)"
, "(declare-fun card@@sl$BLK ( (set sl$BLK) ) Int)"
, "(declare-fun card@@sl$LOC ( (set sl$LOC) ) Int)"
, "(declare-fun card@@sl$TRAIN ( (set sl$TRAIN) ) Int)"
, "(declare-fun dom@@sl$TRAIN@@sl$BLK"
, " ( (pfun sl$TRAIN sl$BLK) )"
, " (set sl$TRAIN))"
, "(declare-fun dom-rest@@sl$TRAIN@@sl$BLK"
, " ( (set sl$TRAIN)"
, " (pfun sl$TRAIN sl$BLK) )"
, " (pfun sl$TRAIN sl$BLK))"
, "(declare-fun dom-subt@@sl$TRAIN@@sl$BLK"
, " ( (set sl$TRAIN)"
, " (pfun sl$TRAIN sl$BLK) )"
, " (pfun sl$TRAIN sl$BLK))"
, "(declare-fun empty-fun@@sl$TRAIN@@sl$BLK"
, " ()"
, " (pfun sl$TRAIN sl$BLK))"
, "(declare-fun finite@@sl$BLK ( (set sl$BLK) ) Bool)"
, "(declare-fun finite@@sl$LOC ( (set sl$LOC) ) Bool)"
, "(declare-fun finite@@sl$TRAIN ( (set sl$TRAIN) ) Bool)"
, "(declare-fun injective@@sl$TRAIN@@sl$BLK"
, " ( (pfun sl$TRAIN sl$BLK) )"
, " Bool)"
, "(declare-fun mk-fun@@sl$TRAIN@@sl$BLK"
, " (sl$TRAIN sl$BLK)"
, " (pfun sl$TRAIN sl$BLK))"
, "(declare-fun mk-set@@sl$BLK (sl$BLK) (set sl$BLK))"
, "(declare-fun mk-set@@sl$TRAIN (sl$TRAIN) (set sl$TRAIN))"
, "(declare-fun ovl@@sl$TRAIN@@sl$BLK"
, " ( (pfun sl$TRAIN sl$BLK)"
, " (pfun sl$TRAIN sl$BLK) )"
, " (pfun sl$TRAIN sl$BLK))"
, "(declare-fun ran@@sl$TRAIN@@sl$BLK"
, " ( (pfun sl$TRAIN sl$BLK) )"
, " (set sl$BLK))"
, "(define-fun all@@sl$BLK"
, " ()"
, " (set sl$BLK)"
, " ( (as const (set sl$BLK))"
, " true ))"
, "(define-fun all@@sl$LOC"
, " ()"
, " (set sl$LOC)"
, " ( (as const (set sl$LOC))"
, " true ))"
, "(define-fun all@@sl$TRAIN"
, " ()"
, " (set sl$TRAIN)"
, " ( (as const (set sl$TRAIN))"
, " true ))"
, "(define-fun compl@@sl$BLK"
, " ( (s1 (set sl$BLK)) )"
, " (set sl$BLK)"
, " ( (_ map not)"
, " s1 ))"
, "(define-fun compl@@sl$LOC"
, " ( (s1 (set sl$LOC)) )"
, " (set sl$LOC)"
, " ( (_ map not)"
, " s1 ))"
, "(define-fun compl@@sl$TRAIN"
, " ( (s1 (set sl$TRAIN)) )"
, " (set sl$TRAIN)"
, " ( (_ map not)"
, " s1 ))"
, "(define-fun elem@@sl$BLK"
, " ( (x sl$BLK)"
, " (s1 (set sl$BLK)) )"
, " Bool"
, " (select s1 x))"
, "(define-fun elem@@sl$TRAIN"
, " ( (x sl$TRAIN)"
, " (s1 (set sl$TRAIN)) )"
, " Bool"
, " (select s1 x))"
, "(define-fun empty-set@@sl$BLK"
, " ()"
, " (set sl$BLK)"
, " ( (as const (set sl$BLK))"
, " false ))"
, "(define-fun empty-set@@sl$LOC"
, " ()"
, " (set sl$LOC)"
, " ( (as const (set sl$LOC))"
, " false ))"
, "(define-fun empty-set@@sl$TRAIN"
, " ()"
, " (set sl$TRAIN)"
, " ( (as const (set sl$TRAIN))"
, " false ))"
, "(define-fun set-diff@@sl$BLK"
, " ( (s1 (set sl$BLK))"
, " (s2 (set sl$BLK)) )"
, " (set sl$BLK)"
, " (intersect s1 ( (_ map not) s2 )))"
, "(define-fun set-diff@@sl$LOC"
, " ( (s1 (set sl$LOC))"
, " (s2 (set sl$LOC)) )"
, " (set sl$LOC)"
, " (intersect s1 ( (_ map not) s2 )))"
, "(define-fun set-diff@@sl$TRAIN"
, " ( (s1 (set sl$TRAIN))"
, " (s2 (set sl$TRAIN)) )"
, " (set sl$TRAIN)"
, " (intersect s1 ( (_ map not) s2 )))"
, "(define-fun st-subset@@sl$BLK"
, " ( (s1 (set sl$BLK))"
, " (s2 (set sl$BLK)) )"
, " Bool"
, " (and (subset s1 s2) (not (= s1 s2))))"
, "(define-fun st-subset@@sl$LOC"
, " ( (s1 (set sl$LOC))"
, " (s2 (set sl$LOC)) )"
, " Bool"
, " (and (subset s1 s2) (not (= s1 s2))))"
, "(define-fun st-subset@@sl$TRAIN"
, " ( (s1 (set sl$TRAIN))"
, " (s2 (set sl$TRAIN)) )"
, " Bool"
, " (and (subset s1 s2) (not (= s1 s2))))"
, "(define-fun sl$BLK"
, " ()"
, " (set sl$BLK)"
, " ( (as const (set sl$BLK))"
, " true ))"
, "(define-fun sl$LOC"
, " ()"
, " (set sl$LOC)"
, " ( (as const (set sl$LOC))"
, " true ))"
, "(define-fun sl$TRAIN"
, " ()"
, " (set sl$TRAIN)"
, " ( (as const (set sl$TRAIN))"
, " true ))"
, "(assert (forall ( (r (set sl$BLK)) )"
, " (! (=> (finite@@sl$BLK r) (<= 0 (card@@sl$BLK r)))"
, " :pattern"
, " ( (<= 0 (card@@sl$BLK r)) ))))"
, "(assert (forall ( (r (set sl$LOC)) )"
, " (! (=> (finite@@sl$LOC r) (<= 0 (card@@sl$LOC r)))"
, " :pattern"
, " ( (<= 0 (card@@sl$LOC r)) ))))"
, "(assert (forall ( (r (set sl$TRAIN)) )"
, " (! (=> (finite@@sl$TRAIN r) (<= 0 (card@@sl$TRAIN r)))"
, " :pattern"
, " ( (<= 0 (card@@sl$TRAIN r)) ))))"
, "(assert (forall ( (r (set sl$BLK)) )"
, " (! (= (= (card@@sl$BLK r) 0) (= r empty-set@@sl$BLK))"
, " :pattern"
, " ( (card@@sl$BLK r) ))))"
, "(assert (forall ( (r (set sl$LOC)) )"
, " (! (= (= (card@@sl$LOC r) 0) (= r empty-set@@sl$LOC))"
, " :pattern"
, " ( (card@@sl$LOC r) ))))"
, "(assert (forall ( (r (set sl$TRAIN)) )"
, " (! (= (= (card@@sl$TRAIN r) 0)"
, " (= r empty-set@@sl$TRAIN))"
, " :pattern"
, " ( (card@@sl$TRAIN r) ))))"
, "(assert (forall ( (x sl$BLK) )"
, " (! (= (card@@sl$BLK (mk-set@@sl$BLK x)) 1)"
, " :pattern"
, " ( (card@@sl$BLK (mk-set@@sl$BLK x)) ))))"
, "(assert (forall ( (x sl$TRAIN) )"
, " (! (= (card@@sl$TRAIN (mk-set@@sl$TRAIN x)) 1)"
, " :pattern"
, " ( (card@@sl$TRAIN (mk-set@@sl$TRAIN x)) ))))"
, "(assert (forall ( (r (set sl$BLK)) )"
, " (! (= (= (card@@sl$BLK r) 1)"
, " (exists ( (x sl$BLK) ) (and true (= r (mk-set@@sl$BLK x)))))"
, " :pattern"
, " ( (card@@sl$BLK r) ))))"
, "(assert (forall ( (r (set sl$TRAIN)) )"
, " (! (= (= (card@@sl$TRAIN r) 1)"
, " (exists ( (x sl$TRAIN) )"
, " (and true (= r (mk-set@@sl$TRAIN x)))))"
, " :pattern"
, " ( (card@@sl$TRAIN r) ))))"
, "(assert (forall ( (r (set sl$BLK))"
, " (r0 (set sl$BLK)) )"
, " (! (=> (= (intersect r r0) empty-set@@sl$BLK)"
, " (= (card@@sl$BLK (union r r0))"
, " (+ (card@@sl$BLK r) (card@@sl$BLK r0))))"
, " :pattern"
, " ( (card@@sl$BLK (union r r0)) ))))"
, "(assert (forall ( (r (set sl$LOC))"
, " (r0 (set sl$LOC)) )"
, " (! (=> (= (intersect r r0) empty-set@@sl$LOC)"
, " (= (card@@sl$LOC (union r r0))"
, " (+ (card@@sl$LOC r) (card@@sl$LOC r0))))"
, " :pattern"
, " ( (card@@sl$LOC (union r r0)) ))))"
, "(assert (forall ( (r (set sl$TRAIN))"
, " (r0 (set sl$TRAIN)) )"
, " (! (=> (= (intersect r r0) empty-set@@sl$TRAIN)"
, " (= (card@@sl$TRAIN (union r r0))"
, " (+ (card@@sl$TRAIN r) (card@@sl$TRAIN r0))))"
, " :pattern"
, " ( (card@@sl$TRAIN (union r r0)) ))))"
, "(assert (= (dom@@sl$TRAIN@@sl$BLK empty-fun@@sl$TRAIN@@sl$BLK)"
, " empty-set@@sl$TRAIN))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK)) )"
, " (! (= (ovl@@sl$TRAIN@@sl$BLK f1 empty-fun@@sl$TRAIN@@sl$BLK)"
, " f1)"
, " :pattern"
, " ( (ovl@@sl$TRAIN@@sl$BLK f1 empty-fun@@sl$TRAIN@@sl$BLK) ))))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK)) )"
, " (! (= (ovl@@sl$TRAIN@@sl$BLK empty-fun@@sl$TRAIN@@sl$BLK f1)"
, " f1)"
, " :pattern"
, " ( (ovl@@sl$TRAIN@@sl$BLK empty-fun@@sl$TRAIN@@sl$BLK f1) ))))"
, "(assert (forall ( (x sl$TRAIN)"
, " (y sl$BLK) )"
, " (! (= (dom@@sl$TRAIN@@sl$BLK (mk-fun@@sl$TRAIN@@sl$BLK x y))"
, " (mk-set@@sl$TRAIN x))"
, " :pattern"
, " ( (dom@@sl$TRAIN@@sl$BLK (mk-fun@@sl$TRAIN@@sl$BLK x y)) ))))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK))"
, " (f2 (pfun sl$TRAIN sl$BLK))"
, " (x sl$TRAIN) )"
, " (! (=> (elem@@sl$TRAIN x (dom@@sl$TRAIN@@sl$BLK f2))"
, " (= (apply@@sl$TRAIN@@sl$BLK (ovl@@sl$TRAIN@@sl$BLK f1 f2) x)"
, " (apply@@sl$TRAIN@@sl$BLK f2 x)))"
, " :pattern"
, " ( (apply@@sl$TRAIN@@sl$BLK (ovl@@sl$TRAIN@@sl$BLK f1 f2) x) ))))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK))"
, " (f2 (pfun sl$TRAIN sl$BLK))"
, " (x sl$TRAIN) )"
, " (! (=> (and (elem@@sl$TRAIN x (dom@@sl$TRAIN@@sl$BLK f1))"
, " (not (elem@@sl$TRAIN x (dom@@sl$TRAIN@@sl$BLK f2))))"
, " (= (apply@@sl$TRAIN@@sl$BLK (ovl@@sl$TRAIN@@sl$BLK f1 f2) x)"
, " (apply@@sl$TRAIN@@sl$BLK f1 x)))"
, " :pattern"
, " ( (apply@@sl$TRAIN@@sl$BLK (ovl@@sl$TRAIN@@sl$BLK f1 f2) x) ))))"
, "(assert (forall ( (x sl$TRAIN)"
, " (y sl$BLK) )"
, " (! (= (apply@@sl$TRAIN@@sl$BLK (mk-fun@@sl$TRAIN@@sl$BLK x y) x)"
, " y)"
, " :pattern"
, " ( (apply@@sl$TRAIN@@sl$BLK (mk-fun@@sl$TRAIN@@sl$BLK x y) x) ))))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK))"
, " (s1 (set sl$TRAIN))"
, " (x sl$TRAIN) )"
, " (! (=> (and (elem@@sl$TRAIN x s1)"
, " (elem@@sl$TRAIN x (dom@@sl$TRAIN@@sl$BLK f1)))"
, " (= (apply@@sl$TRAIN@@sl$BLK (dom-rest@@sl$TRAIN@@sl$BLK s1 f1) x)"
, " (apply@@sl$TRAIN@@sl$BLK f1 x)))"
, " :pattern"
, " ( (apply@@sl$TRAIN@@sl$BLK (dom-rest@@sl$TRAIN@@sl$BLK s1 f1) x) ))))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK))"
, " (s1 (set sl$TRAIN))"
, " (x sl$TRAIN) )"
, " (! (=> (elem@@sl$TRAIN x"
, " (set-diff@@sl$TRAIN (dom@@sl$TRAIN@@sl$BLK f1) s1))"
, " (= (apply@@sl$TRAIN@@sl$BLK (dom-subt@@sl$TRAIN@@sl$BLK s1 f1) x)"
, " (apply@@sl$TRAIN@@sl$BLK f1 x)))"
, " :pattern"
, " ( (apply@@sl$TRAIN@@sl$BLK (dom-subt@@sl$TRAIN@@sl$BLK s1 f1) x) ))))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK))"
, " (f2 (pfun sl$TRAIN sl$BLK)) )"
, " (! (= (dom@@sl$TRAIN@@sl$BLK (ovl@@sl$TRAIN@@sl$BLK f1 f2))"
, " (union (dom@@sl$TRAIN@@sl$BLK f1)"
, " (dom@@sl$TRAIN@@sl$BLK f2)))"
, " :pattern"
, " ( (dom@@sl$TRAIN@@sl$BLK (ovl@@sl$TRAIN@@sl$BLK f1 f2)) ))))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK))"
, " (s1 (set sl$TRAIN)) )"
, " (! (= (dom@@sl$TRAIN@@sl$BLK (dom-rest@@sl$TRAIN@@sl$BLK s1 f1))"
, " (intersect s1 (dom@@sl$TRAIN@@sl$BLK f1)))"
, " :pattern"
, " ( (dom@@sl$TRAIN@@sl$BLK (dom-rest@@sl$TRAIN@@sl$BLK s1 f1)) ))))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK))"
, " (s1 (set sl$TRAIN)) )"
, " (! (= (dom@@sl$TRAIN@@sl$BLK (dom-subt@@sl$TRAIN@@sl$BLK s1 f1))"
, " (set-diff@@sl$TRAIN (dom@@sl$TRAIN@@sl$BLK f1) s1))"
, " :pattern"
, " ( (dom@@sl$TRAIN@@sl$BLK (dom-subt@@sl$TRAIN@@sl$BLK s1 f1)) ))))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK))"
, " (x sl$TRAIN)"
, " (y sl$BLK) )"
, " (! (= (and (elem@@sl$TRAIN x (dom@@sl$TRAIN@@sl$BLK f1))"
, " (= (apply@@sl$TRAIN@@sl$BLK f1 x) y))"
, " (= (select f1 x) (Just y)))"
, " :pattern"
, " ( (elem@@sl$TRAIN x (dom@@sl$TRAIN@@sl$BLK f1))"
, " (apply@@sl$TRAIN@@sl$BLK f1 x)"
, " (select f1 x)"
, " (Just y) ))))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK))"
, " (x sl$TRAIN)"
, " (x2 sl$TRAIN)"
, " (y sl$BLK) )"
, " (! (=> (not (= x x2))"
, " (= (apply@@sl$TRAIN@@sl$BLK (ovl@@sl$TRAIN@@sl$BLK f1 (mk-fun@@sl$TRAIN@@sl$BLK x y))"
, " x2)"
, " (apply@@sl$TRAIN@@sl$BLK f1 x2)))"
, " :pattern"
, " ( (apply@@sl$TRAIN@@sl$BLK (ovl@@sl$TRAIN@@sl$BLK f1 (mk-fun@@sl$TRAIN@@sl$BLK x y))"
, " x2) ))))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK))"
, " (x sl$TRAIN)"
, " (y sl$BLK) )"
, " (! (= (apply@@sl$TRAIN@@sl$BLK (ovl@@sl$TRAIN@@sl$BLK f1 (mk-fun@@sl$TRAIN@@sl$BLK x y))"
, " x)"
, " y)"
, " :pattern"
, " ( (apply@@sl$TRAIN@@sl$BLK (ovl@@sl$TRAIN@@sl$BLK f1 (mk-fun@@sl$TRAIN@@sl$BLK x y))"
, " x) ))))"
, "(assert (= (ran@@sl$TRAIN@@sl$BLK empty-fun@@sl$TRAIN@@sl$BLK)"
, " empty-set@@sl$BLK))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK))"
, " (y sl$BLK) )"
, " (! (= (elem@@sl$BLK y (ran@@sl$TRAIN@@sl$BLK f1))"
, " (exists ( (x sl$TRAIN) )"
, " (and true"
, " (and (elem@@sl$TRAIN x (dom@@sl$TRAIN@@sl$BLK f1))"
, " (= (apply@@sl$TRAIN@@sl$BLK f1 x) y)))))"
, " :pattern"
, " ( (elem@@sl$BLK y (ran@@sl$TRAIN@@sl$BLK f1)) ))))"
, "(assert (forall ( (x sl$TRAIN)"
, " (y sl$BLK) )"
, " (! (= (ran@@sl$TRAIN@@sl$BLK (mk-fun@@sl$TRAIN@@sl$BLK x y))"
, " (mk-set@@sl$BLK y))"
, " :pattern"
, " ( (ran@@sl$TRAIN@@sl$BLK (mk-fun@@sl$TRAIN@@sl$BLK x y)) ))))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK)) )"
, " (! (= (injective@@sl$TRAIN@@sl$BLK f1)"
, " (forall ( (x sl$TRAIN)"
, " (x2 sl$TRAIN) )"
, " (=> (and (elem@@sl$TRAIN x (dom@@sl$TRAIN@@sl$BLK f1))"
, " (elem@@sl$TRAIN x2 (dom@@sl$TRAIN@@sl$BLK f1)))"
, " (=> (= (apply@@sl$TRAIN@@sl$BLK f1 x)"
, " (apply@@sl$TRAIN@@sl$BLK f1 x2))"
, " (= x x2)))))"
, " :pattern"
, " ( (injective@@sl$TRAIN@@sl$BLK f1) ))))"
, "(assert (injective@@sl$TRAIN@@sl$BLK empty-fun@@sl$TRAIN@@sl$BLK))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK))"
, " (x sl$TRAIN) )"
, " (! (=> (elem@@sl$TRAIN x (dom@@sl$TRAIN@@sl$BLK f1))"
, " (elem@@sl$BLK (apply@@sl$TRAIN@@sl$BLK f1 x)"
, " (ran@@sl$TRAIN@@sl$BLK f1)))"
, " :pattern"
, " ( (elem@@sl$BLK (apply@@sl$TRAIN@@sl$BLK f1 x)"
, " (ran@@sl$TRAIN@@sl$BLK f1)) ))))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK))"
, " (s1 (set sl$TRAIN))"
, " (x sl$TRAIN) )"
, " (! (=> (elem@@sl$TRAIN x"
, " (set-diff@@sl$TRAIN (dom@@sl$TRAIN@@sl$BLK f1) s1))"
, " (elem@@sl$BLK (apply@@sl$TRAIN@@sl$BLK f1 x)"
, " (ran@@sl$TRAIN@@sl$BLK (dom-subt@@sl$TRAIN@@sl$BLK s1 f1))))"
, " :pattern"
, " ( (elem@@sl$BLK (apply@@sl$TRAIN@@sl$BLK f1 x)"
, " (ran@@sl$TRAIN@@sl$BLK (dom-subt@@sl$TRAIN@@sl$BLK s1 f1))) ))))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK))"
, " (s1 (set sl$TRAIN))"
, " (x sl$TRAIN) )"
, " (! (=> (elem@@sl$TRAIN x (intersect (dom@@sl$TRAIN@@sl$BLK f1) s1))"
, " (elem@@sl$BLK (apply@@sl$TRAIN@@sl$BLK f1 x)"
, " (ran@@sl$TRAIN@@sl$BLK (dom-rest@@sl$TRAIN@@sl$BLK s1 f1))))"
, " :pattern"
, " ( (elem@@sl$BLK (apply@@sl$TRAIN@@sl$BLK f1 x)"
, " (ran@@sl$TRAIN@@sl$BLK (dom-rest@@sl$TRAIN@@sl$BLK s1 f1))) ))))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK))"
, " (x sl$TRAIN)"
, " (y sl$BLK) )"
, " (! (=> (and (elem@@sl$TRAIN x (dom@@sl$TRAIN@@sl$BLK f1))"
, " (injective@@sl$TRAIN@@sl$BLK f1))"
, " (= (ran@@sl$TRAIN@@sl$BLK (ovl@@sl$TRAIN@@sl$BLK f1 (mk-fun@@sl$TRAIN@@sl$BLK x y)))"
, " (union (set-diff@@sl$BLK (ran@@sl$TRAIN@@sl$BLK f1)"
, " (mk-set@@sl$BLK (apply@@sl$TRAIN@@sl$BLK f1 x)))"
, " (mk-set@@sl$BLK y))))"
, " :pattern"
, " ( (ran@@sl$TRAIN@@sl$BLK (ovl@@sl$TRAIN@@sl$BLK f1 (mk-fun@@sl$TRAIN@@sl$BLK x y))) ))))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK))"
, " (x sl$TRAIN)"
, " (y sl$BLK) )"
, " (! (=> (not (elem@@sl$TRAIN x (dom@@sl$TRAIN@@sl$BLK f1)))"
, " (= (ran@@sl$TRAIN@@sl$BLK (ovl@@sl$TRAIN@@sl$BLK f1 (mk-fun@@sl$TRAIN@@sl$BLK x y)))"
, " (union (ran@@sl$TRAIN@@sl$BLK f1) (mk-set@@sl$BLK y))))"
, " :pattern"
, " ( (ran@@sl$TRAIN@@sl$BLK (ovl@@sl$TRAIN@@sl$BLK f1 (mk-fun@@sl$TRAIN@@sl$BLK x y))) ))))"
, "(assert (forall ( (x sl$BLK)"
, " (y sl$BLK) )"
, " (! (= (elem@@sl$BLK x (mk-set@@sl$BLK y)) (= x y))"
, " :pattern"
, " ( (elem@@sl$BLK x (mk-set@@sl$BLK y)) ))))"
, "(assert (forall ( (x sl$TRAIN)"
, " (y sl$TRAIN) )"
, " (! (= (elem@@sl$TRAIN x (mk-set@@sl$TRAIN y)) (= x y))"
, " :pattern"
, " ( (elem@@sl$TRAIN x (mk-set@@sl$TRAIN y)) ))))"
, "(assert (forall ( (s1 (set sl$BLK))"
, " (s2 (set sl$BLK)) )"
, " (! (=> (finite@@sl$BLK s1)"
, " (finite@@sl$BLK (set-diff@@sl$BLK s1 s2)))"
, " :pattern"
, " ( (finite@@sl$BLK (set-diff@@sl$BLK s1 s2)) ))))"
, "(assert (forall ( (s1 (set sl$LOC))"
, " (s2 (set sl$LOC)) )"
, " (! (=> (finite@@sl$LOC s1)"
, " (finite@@sl$LOC (set-diff@@sl$LOC s1 s2)))"
, " :pattern"
, " ( (finite@@sl$LOC (set-diff@@sl$LOC s1 s2)) ))))"
, "(assert (forall ( (s1 (set sl$TRAIN))"
, " (s2 (set sl$TRAIN)) )"
, " (! (=> (finite@@sl$TRAIN s1)"
, " (finite@@sl$TRAIN (set-diff@@sl$TRAIN s1 s2)))"
, " :pattern"
, " ( (finite@@sl$TRAIN (set-diff@@sl$TRAIN s1 s2)) ))))"
, "(assert (forall ( (s1 (set sl$BLK))"
, " (s2 (set sl$BLK)) )"
, " (! (=> (and (finite@@sl$BLK s1) (finite@@sl$BLK s2))"
, " (finite@@sl$BLK (union s1 s2)))"
, " :pattern"
, " ( (finite@@sl$BLK (union s1 s2)) ))))"
, "(assert (forall ( (s1 (set sl$LOC))"
, " (s2 (set sl$LOC)) )"
, " (! (=> (and (finite@@sl$LOC s1) (finite@@sl$LOC s2))"
, " (finite@@sl$LOC (union s1 s2)))"
, " :pattern"
, " ( (finite@@sl$LOC (union s1 s2)) ))))"
, "(assert (forall ( (s1 (set sl$TRAIN))"
, " (s2 (set sl$TRAIN)) )"
, " (! (=> (and (finite@@sl$TRAIN s1) (finite@@sl$TRAIN s2))"
, " (finite@@sl$TRAIN (union s1 s2)))"
, " :pattern"
, " ( (finite@@sl$TRAIN (union s1 s2)) ))))"
, "(assert (forall ( (s1 (set sl$BLK))"
, " (s2 (set sl$BLK)) )"
, " (! (=> (and (finite@@sl$BLK s2) (not (finite@@sl$BLK s1)))"
, " (not (finite@@sl$BLK (set-diff@@sl$BLK s1 s2))))"
, " :pattern"
, " ( (finite@@sl$BLK (set-diff@@sl$BLK s1 s2)) ))))"
, "(assert (forall ( (s1 (set sl$LOC))"
, " (s2 (set sl$LOC)) )"
, " (! (=> (and (finite@@sl$LOC s2) (not (finite@@sl$LOC s1)))"
, " (not (finite@@sl$LOC (set-diff@@sl$LOC s1 s2))))"
, " :pattern"
, " ( (finite@@sl$LOC (set-diff@@sl$LOC s1 s2)) ))))"
, "(assert (forall ( (s1 (set sl$TRAIN))"
, " (s2 (set sl$TRAIN)) )"
, " (! (=> (and (finite@@sl$TRAIN s2) (not (finite@@sl$TRAIN s1)))"
, " (not (finite@@sl$TRAIN (set-diff@@sl$TRAIN s1 s2))))"
, " :pattern"
, " ( (finite@@sl$TRAIN (set-diff@@sl$TRAIN s1 s2)) ))))"
, "(assert (forall ( (x sl$BLK) )"
, " (! (finite@@sl$BLK (mk-set@@sl$BLK x))"
, " :pattern"
, " ( (finite@@sl$BLK (mk-set@@sl$BLK x)) ))))"
, "(assert (forall ( (x sl$TRAIN) )"
, " (! (finite@@sl$TRAIN (mk-set@@sl$TRAIN x))"
, " :pattern"
, " ( (finite@@sl$TRAIN (mk-set@@sl$TRAIN x)) ))))"
, "(assert (finite@@sl$BLK empty-set@@sl$BLK))"
, "(assert (finite@@sl$LOC empty-set@@sl$LOC))"
, "(assert (finite@@sl$TRAIN empty-set@@sl$TRAIN))"
, "(assert (not (exists ( (in@prime (set sl$TRAIN)) )"
, " (and true (= in@prime (union in (mk-set@@sl$TRAIN t)))))))"
, "; asm2"
, "(assert (and (not (= ent ext))"
, " (not (elem@@sl$BLK ent PLF))"
, " (not (elem@@sl$BLK ext PLF))))"
, "; asm3"
, "(assert (forall ( (p sl$BLK) )"
, " (! (= (not (= p ext))"
, " (elem@@sl$BLK p (union (mk-set@@sl$BLK ent) PLF)))"
, " :pattern"
, " ( (elem@@sl$BLK p (union (mk-set@@sl$BLK ent) PLF)) ))))"
, "; asm4"
, "(assert (forall ( (p sl$BLK) )"
, " (! (= (not (= p ent))"
, " (elem@@sl$BLK p (union (mk-set@@sl$BLK ext) PLF)))"
, " :pattern"
, " ( (elem@@sl$BLK p (union (mk-set@@sl$BLK ext) PLF)) ))))"
, "; asm5"
, "(assert (forall ( (p sl$BLK) )"
, " (! (= (or (= p ent) (= p ext))"
, " (not (elem@@sl$BLK p PLF)))"
, " :pattern"
, " ( (elem@@sl$BLK p PLF) ))))"
, "; axm0"
, "(assert (= sl$BLK"
, " (union (union (mk-set@@sl$BLK ent) (mk-set@@sl$BLK ext))"
, " PLF)))"
, "; grd1"
, "(assert (not (elem@@sl$TRAIN t in)))"
, "; inv1"
, "(assert (forall ( (t sl$TRAIN) )"
, " (! (=> (elem@@sl$TRAIN t in)"
, " (elem@@sl$BLK (apply@@sl$TRAIN@@sl$BLK loc t) sl$BLK))"
, " :pattern"
, " ( (elem@@sl$BLK (apply@@sl$TRAIN@@sl$BLK loc t) sl$BLK) ))))"
, "; inv2"
, "(assert (= (dom@@sl$TRAIN@@sl$BLK loc) in))"
, "(assert (not true))"
, "(check-sat-using (or-else (then qe smt)"
, " (then simplify smt)"
, " (then skip smt)"
, " (then (using-params simplify :expand-power true) smt)))"
, "; train0/enter/FIS/in@prime"
]
case2 :: IO String
case2 = proof_obligation path0 "train0/enter/FIS/in@prime" 0
result20 :: String
result20 = unlines
[ "; train0/enter/FIS/loc@prime"
, "(set-option :auto-config false)"
, "(set-option :smt.timeout 3000)"
, "(declare-datatypes (a) ( (Maybe (Just (fromJust a)) Nothing) ))"
, "(declare-datatypes () ( (Null null) ))"
, "(declare-datatypes (a b) ( (Pair (pair (first a) (second b))) ))"
, "(define-sort guarded (a) (Maybe a))"
, "(declare-sort sl$BLK 0)"
, "; comment: we don't need to declare the sort Bool"
, "; comment: we don't need to declare the sort Int"
, "(declare-sort sl$LOC 0)"
, "; comment: we don't need to declare the sort Real"
, "(declare-sort sl$TRAIN 0)"
, "(define-sort pfun (a b) (Array a (Maybe b)))"
, "(define-sort set (a) (Array a Bool))"
, "(declare-const PLF (set sl$BLK))"
, "(declare-const ent sl$BLK)"
, "(declare-const ext sl$BLK)"
, "(declare-const in (set sl$TRAIN))"
, "(declare-const in@prime (set sl$TRAIN))"
, "(declare-const loc (pfun sl$TRAIN sl$BLK))"
, "(declare-const loc@prime (pfun sl$TRAIN sl$BLK))"
, "(declare-const t sl$TRAIN)"
, "(declare-fun apply@@sl$TRAIN@@sl$BLK"
, " ( (pfun sl$TRAIN sl$BLK)"
, " sl$TRAIN )"
, " sl$BLK)"
, "(declare-fun card@@sl$BLK ( (set sl$BLK) ) Int)"
, "(declare-fun card@@sl$LOC ( (set sl$LOC) ) Int)"
, "(declare-fun card@@sl$TRAIN ( (set sl$TRAIN) ) Int)"
, "(declare-fun dom@@sl$TRAIN@@sl$BLK"
, " ( (pfun sl$TRAIN sl$BLK) )"
, " (set sl$TRAIN))"
, "(declare-fun dom-rest@@sl$TRAIN@@sl$BLK"
, " ( (set sl$TRAIN)"
, " (pfun sl$TRAIN sl$BLK) )"
, " (pfun sl$TRAIN sl$BLK))"
, "(declare-fun dom-subt@@sl$TRAIN@@sl$BLK"
, " ( (set sl$TRAIN)"
, " (pfun sl$TRAIN sl$BLK) )"
, " (pfun sl$TRAIN sl$BLK))"
, "(declare-fun empty-fun@@sl$TRAIN@@sl$BLK"
, " ()"
, " (pfun sl$TRAIN sl$BLK))"
, "(declare-fun finite@@sl$BLK ( (set sl$BLK) ) Bool)"
, "(declare-fun finite@@sl$LOC ( (set sl$LOC) ) Bool)"
, "(declare-fun finite@@sl$TRAIN ( (set sl$TRAIN) ) Bool)"
, "(declare-fun injective@@sl$TRAIN@@sl$BLK"
, " ( (pfun sl$TRAIN sl$BLK) )"
, " Bool)"
, "(declare-fun mk-fun@@sl$TRAIN@@sl$BLK"
, " (sl$TRAIN sl$BLK)"
, " (pfun sl$TRAIN sl$BLK))"
, "(declare-fun mk-set@@sl$BLK (sl$BLK) (set sl$BLK))"
, "(declare-fun mk-set@@sl$TRAIN (sl$TRAIN) (set sl$TRAIN))"
, "(declare-fun ovl@@sl$TRAIN@@sl$BLK"
, " ( (pfun sl$TRAIN sl$BLK)"
, " (pfun sl$TRAIN sl$BLK) )"
, " (pfun sl$TRAIN sl$BLK))"
, "(declare-fun ran@@sl$TRAIN@@sl$BLK"
, " ( (pfun sl$TRAIN sl$BLK) )"
, " (set sl$BLK))"
, "(define-fun all@@sl$BLK"
, " ()"
, " (set sl$BLK)"
, " ( (as const (set sl$BLK))"
, " true ))"
, "(define-fun all@@sl$LOC"
, " ()"
, " (set sl$LOC)"
, " ( (as const (set sl$LOC))"
, " true ))"
, "(define-fun all@@sl$TRAIN"
, " ()"
, " (set sl$TRAIN)"
, " ( (as const (set sl$TRAIN))"
, " true ))"
, "(define-fun compl@@sl$BLK"
, " ( (s1 (set sl$BLK)) )"
, " (set sl$BLK)"
, " ( (_ map not)"
, " s1 ))"
, "(define-fun compl@@sl$LOC"
, " ( (s1 (set sl$LOC)) )"
, " (set sl$LOC)"
, " ( (_ map not)"
, " s1 ))"
, "(define-fun compl@@sl$TRAIN"
, " ( (s1 (set sl$TRAIN)) )"
, " (set sl$TRAIN)"
, " ( (_ map not)"
, " s1 ))"
, "(define-fun elem@@sl$BLK"
, " ( (x sl$BLK)"
, " (s1 (set sl$BLK)) )"
, " Bool"
, " (select s1 x))"
, "(define-fun elem@@sl$TRAIN"
, " ( (x sl$TRAIN)"
, " (s1 (set sl$TRAIN)) )"
, " Bool"
, " (select s1 x))"
, "(define-fun empty-set@@sl$BLK"
, " ()"
, " (set sl$BLK)"
, " ( (as const (set sl$BLK))"
, " false ))"
, "(define-fun empty-set@@sl$LOC"
, " ()"
, " (set sl$LOC)"
, " ( (as const (set sl$LOC))"
, " false ))"
, "(define-fun empty-set@@sl$TRAIN"
, " ()"
, " (set sl$TRAIN)"
, " ( (as const (set sl$TRAIN))"
, " false ))"
, "(define-fun set-diff@@sl$BLK"
, " ( (s1 (set sl$BLK))"
, " (s2 (set sl$BLK)) )"
, " (set sl$BLK)"
, " (intersect s1 ( (_ map not) s2 )))"
, "(define-fun set-diff@@sl$LOC"
, " ( (s1 (set sl$LOC))"
, " (s2 (set sl$LOC)) )"
, " (set sl$LOC)"
, " (intersect s1 ( (_ map not) s2 )))"
, "(define-fun set-diff@@sl$TRAIN"
, " ( (s1 (set sl$TRAIN))"
, " (s2 (set sl$TRAIN)) )"
, " (set sl$TRAIN)"
, " (intersect s1 ( (_ map not) s2 )))"
, "(define-fun st-subset@@sl$BLK"
, " ( (s1 (set sl$BLK))"
, " (s2 (set sl$BLK)) )"
, " Bool"
, " (and (subset s1 s2) (not (= s1 s2))))"
, "(define-fun st-subset@@sl$LOC"
, " ( (s1 (set sl$LOC))"
, " (s2 (set sl$LOC)) )"
, " Bool"
, " (and (subset s1 s2) (not (= s1 s2))))"
, "(define-fun st-subset@@sl$TRAIN"
, " ( (s1 (set sl$TRAIN))"
, " (s2 (set sl$TRAIN)) )"
, " Bool"
, " (and (subset s1 s2) (not (= s1 s2))))"
, "(define-fun sl$BLK"
, " ()"
, " (set sl$BLK)"
, " ( (as const (set sl$BLK))"
, " true ))"
, "(define-fun sl$LOC"
, " ()"
, " (set sl$LOC)"
, " ( (as const (set sl$LOC))"
, " true ))"
, "(define-fun sl$TRAIN"
, " ()"
, " (set sl$TRAIN)"
, " ( (as const (set sl$TRAIN))"
, " true ))"
, "(assert (forall ( (r (set sl$BLK)) )"
, " (! (=> (finite@@sl$BLK r) (<= 0 (card@@sl$BLK r)))"
, " :pattern"
, " ( (<= 0 (card@@sl$BLK r)) ))))"
, "(assert (forall ( (r (set sl$LOC)) )"
, " (! (=> (finite@@sl$LOC r) (<= 0 (card@@sl$LOC r)))"
, " :pattern"
, " ( (<= 0 (card@@sl$LOC r)) ))))"
, "(assert (forall ( (r (set sl$TRAIN)) )"
, " (! (=> (finite@@sl$TRAIN r) (<= 0 (card@@sl$TRAIN r)))"
, " :pattern"
, " ( (<= 0 (card@@sl$TRAIN r)) ))))"
, "(assert (forall ( (r (set sl$BLK)) )"
, " (! (= (= (card@@sl$BLK r) 0) (= r empty-set@@sl$BLK))"
, " :pattern"
, " ( (card@@sl$BLK r) ))))"
, "(assert (forall ( (r (set sl$LOC)) )"
, " (! (= (= (card@@sl$LOC r) 0) (= r empty-set@@sl$LOC))"
, " :pattern"
, " ( (card@@sl$LOC r) ))))"
, "(assert (forall ( (r (set sl$TRAIN)) )"
, " (! (= (= (card@@sl$TRAIN r) 0)"
, " (= r empty-set@@sl$TRAIN))"
, " :pattern"
, " ( (card@@sl$TRAIN r) ))))"
, "(assert (forall ( (x sl$BLK) )"
, " (! (= (card@@sl$BLK (mk-set@@sl$BLK x)) 1)"
, " :pattern"
, " ( (card@@sl$BLK (mk-set@@sl$BLK x)) ))))"
, "(assert (forall ( (x sl$TRAIN) )"
, " (! (= (card@@sl$TRAIN (mk-set@@sl$TRAIN x)) 1)"
, " :pattern"
, " ( (card@@sl$TRAIN (mk-set@@sl$TRAIN x)) ))))"
, "(assert (forall ( (r (set sl$BLK)) )"
, " (! (= (= (card@@sl$BLK r) 1)"
, " (exists ( (x sl$BLK) ) (and true (= r (mk-set@@sl$BLK x)))))"
, " :pattern"
, " ( (card@@sl$BLK r) ))))"
, "(assert (forall ( (r (set sl$TRAIN)) )"
, " (! (= (= (card@@sl$TRAIN r) 1)"
, " (exists ( (x sl$TRAIN) )"
, " (and true (= r (mk-set@@sl$TRAIN x)))))"
, " :pattern"
, " ( (card@@sl$TRAIN r) ))))"
, "(assert (forall ( (r (set sl$BLK))"
, " (r0 (set sl$BLK)) )"
, " (! (=> (= (intersect r r0) empty-set@@sl$BLK)"
, " (= (card@@sl$BLK (union r r0))"
, " (+ (card@@sl$BLK r) (card@@sl$BLK r0))))"
, " :pattern"
, " ( (card@@sl$BLK (union r r0)) ))))"
, "(assert (forall ( (r (set sl$LOC))"
, " (r0 (set sl$LOC)) )"
, " (! (=> (= (intersect r r0) empty-set@@sl$LOC)"
, " (= (card@@sl$LOC (union r r0))"
, " (+ (card@@sl$LOC r) (card@@sl$LOC r0))))"
, " :pattern"
, " ( (card@@sl$LOC (union r r0)) ))))"
, "(assert (forall ( (r (set sl$TRAIN))"
, " (r0 (set sl$TRAIN)) )"
, " (! (=> (= (intersect r r0) empty-set@@sl$TRAIN)"
, " (= (card@@sl$TRAIN (union r r0))"
, " (+ (card@@sl$TRAIN r) (card@@sl$TRAIN r0))))"
, " :pattern"
, " ( (card@@sl$TRAIN (union r r0)) ))))"
, "(assert (= (dom@@sl$TRAIN@@sl$BLK empty-fun@@sl$TRAIN@@sl$BLK)"
, " empty-set@@sl$TRAIN))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK)) )"
, " (! (= (ovl@@sl$TRAIN@@sl$BLK f1 empty-fun@@sl$TRAIN@@sl$BLK)"
, " f1)"
, " :pattern"
, " ( (ovl@@sl$TRAIN@@sl$BLK f1 empty-fun@@sl$TRAIN@@sl$BLK) ))))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK)) )"
, " (! (= (ovl@@sl$TRAIN@@sl$BLK empty-fun@@sl$TRAIN@@sl$BLK f1)"
, " f1)"
, " :pattern"
, " ( (ovl@@sl$TRAIN@@sl$BLK empty-fun@@sl$TRAIN@@sl$BLK f1) ))))"
, "(assert (forall ( (x sl$TRAIN)"
, " (y sl$BLK) )"
, " (! (= (dom@@sl$TRAIN@@sl$BLK (mk-fun@@sl$TRAIN@@sl$BLK x y))"
, " (mk-set@@sl$TRAIN x))"
, " :pattern"
, " ( (dom@@sl$TRAIN@@sl$BLK (mk-fun@@sl$TRAIN@@sl$BLK x y)) ))))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK))"
, " (f2 (pfun sl$TRAIN sl$BLK))"
, " (x sl$TRAIN) )"
, " (! (=> (elem@@sl$TRAIN x (dom@@sl$TRAIN@@sl$BLK f2))"
, " (= (apply@@sl$TRAIN@@sl$BLK (ovl@@sl$TRAIN@@sl$BLK f1 f2) x)"
, " (apply@@sl$TRAIN@@sl$BLK f2 x)))"
, " :pattern"
, " ( (apply@@sl$TRAIN@@sl$BLK (ovl@@sl$TRAIN@@sl$BLK f1 f2) x) ))))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK))"
, " (f2 (pfun sl$TRAIN sl$BLK))"
, " (x sl$TRAIN) )"
, " (! (=> (and (elem@@sl$TRAIN x (dom@@sl$TRAIN@@sl$BLK f1))"
, " (not (elem@@sl$TRAIN x (dom@@sl$TRAIN@@sl$BLK f2))))"
, " (= (apply@@sl$TRAIN@@sl$BLK (ovl@@sl$TRAIN@@sl$BLK f1 f2) x)"
, " (apply@@sl$TRAIN@@sl$BLK f1 x)))"
, " :pattern"
, " ( (apply@@sl$TRAIN@@sl$BLK (ovl@@sl$TRAIN@@sl$BLK f1 f2) x) ))))"
, "(assert (forall ( (x sl$TRAIN)"
, " (y sl$BLK) )"
, " (! (= (apply@@sl$TRAIN@@sl$BLK (mk-fun@@sl$TRAIN@@sl$BLK x y) x)"
, " y)"
, " :pattern"
, " ( (apply@@sl$TRAIN@@sl$BLK (mk-fun@@sl$TRAIN@@sl$BLK x y) x) ))))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK))"
, " (s1 (set sl$TRAIN))"
, " (x sl$TRAIN) )"
, " (! (=> (and (elem@@sl$TRAIN x s1)"
, " (elem@@sl$TRAIN x (dom@@sl$TRAIN@@sl$BLK f1)))"
, " (= (apply@@sl$TRAIN@@sl$BLK (dom-rest@@sl$TRAIN@@sl$BLK s1 f1) x)"
, " (apply@@sl$TRAIN@@sl$BLK f1 x)))"
, " :pattern"
, " ( (apply@@sl$TRAIN@@sl$BLK (dom-rest@@sl$TRAIN@@sl$BLK s1 f1) x) ))))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK))"
, " (s1 (set sl$TRAIN))"
, " (x sl$TRAIN) )"
, " (! (=> (elem@@sl$TRAIN x"
, " (set-diff@@sl$TRAIN (dom@@sl$TRAIN@@sl$BLK f1) s1))"
, " (= (apply@@sl$TRAIN@@sl$BLK (dom-subt@@sl$TRAIN@@sl$BLK s1 f1) x)"
, " (apply@@sl$TRAIN@@sl$BLK f1 x)))"
, " :pattern"
, " ( (apply@@sl$TRAIN@@sl$BLK (dom-subt@@sl$TRAIN@@sl$BLK s1 f1) x) ))))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK))"
, " (f2 (pfun sl$TRAIN sl$BLK)) )"
, " (! (= (dom@@sl$TRAIN@@sl$BLK (ovl@@sl$TRAIN@@sl$BLK f1 f2))"
, " (union (dom@@sl$TRAIN@@sl$BLK f1)"
, " (dom@@sl$TRAIN@@sl$BLK f2)))"
, " :pattern"
, " ( (dom@@sl$TRAIN@@sl$BLK (ovl@@sl$TRAIN@@sl$BLK f1 f2)) ))))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK))"
, " (s1 (set sl$TRAIN)) )"
, " (! (= (dom@@sl$TRAIN@@sl$BLK (dom-rest@@sl$TRAIN@@sl$BLK s1 f1))"
, " (intersect s1 (dom@@sl$TRAIN@@sl$BLK f1)))"
, " :pattern"
, " ( (dom@@sl$TRAIN@@sl$BLK (dom-rest@@sl$TRAIN@@sl$BLK s1 f1)) ))))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK))"
, " (s1 (set sl$TRAIN)) )"
, " (! (= (dom@@sl$TRAIN@@sl$BLK (dom-subt@@sl$TRAIN@@sl$BLK s1 f1))"
, " (set-diff@@sl$TRAIN (dom@@sl$TRAIN@@sl$BLK f1) s1))"
, " :pattern"
, " ( (dom@@sl$TRAIN@@sl$BLK (dom-subt@@sl$TRAIN@@sl$BLK s1 f1)) ))))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK))"
, " (x sl$TRAIN)"
, " (y sl$BLK) )"
, " (! (= (and (elem@@sl$TRAIN x (dom@@sl$TRAIN@@sl$BLK f1))"
, " (= (apply@@sl$TRAIN@@sl$BLK f1 x) y))"
, " (= (select f1 x) (Just y)))"
, " :pattern"
, " ( (elem@@sl$TRAIN x (dom@@sl$TRAIN@@sl$BLK f1))"
, " (apply@@sl$TRAIN@@sl$BLK f1 x)"
, " (select f1 x)"
, " (Just y) ))))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK))"
, " (x sl$TRAIN)"
, " (x2 sl$TRAIN)"
, " (y sl$BLK) )"
, " (! (=> (not (= x x2))"
, " (= (apply@@sl$TRAIN@@sl$BLK (ovl@@sl$TRAIN@@sl$BLK f1 (mk-fun@@sl$TRAIN@@sl$BLK x y))"
, " x2)"
, " (apply@@sl$TRAIN@@sl$BLK f1 x2)))"
, " :pattern"
, " ( (apply@@sl$TRAIN@@sl$BLK (ovl@@sl$TRAIN@@sl$BLK f1 (mk-fun@@sl$TRAIN@@sl$BLK x y))"
, " x2) ))))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK))"
, " (x sl$TRAIN)"
, " (y sl$BLK) )"
, " (! (= (apply@@sl$TRAIN@@sl$BLK (ovl@@sl$TRAIN@@sl$BLK f1 (mk-fun@@sl$TRAIN@@sl$BLK x y))"
, " x)"
, " y)"
, " :pattern"
, " ( (apply@@sl$TRAIN@@sl$BLK (ovl@@sl$TRAIN@@sl$BLK f1 (mk-fun@@sl$TRAIN@@sl$BLK x y))"
, " x) ))))"
, "(assert (= (ran@@sl$TRAIN@@sl$BLK empty-fun@@sl$TRAIN@@sl$BLK)"
, " empty-set@@sl$BLK))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK))"
, " (y sl$BLK) )"
, " (! (= (elem@@sl$BLK y (ran@@sl$TRAIN@@sl$BLK f1))"
, " (exists ( (x sl$TRAIN) )"
, " (and true"
, " (and (elem@@sl$TRAIN x (dom@@sl$TRAIN@@sl$BLK f1))"
, " (= (apply@@sl$TRAIN@@sl$BLK f1 x) y)))))"
, " :pattern"
, " ( (elem@@sl$BLK y (ran@@sl$TRAIN@@sl$BLK f1)) ))))"
, "(assert (forall ( (x sl$TRAIN)"
, " (y sl$BLK) )"
, " (! (= (ran@@sl$TRAIN@@sl$BLK (mk-fun@@sl$TRAIN@@sl$BLK x y))"
, " (mk-set@@sl$BLK y))"
, " :pattern"
, " ( (ran@@sl$TRAIN@@sl$BLK (mk-fun@@sl$TRAIN@@sl$BLK x y)) ))))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK)) )"
, " (! (= (injective@@sl$TRAIN@@sl$BLK f1)"
, " (forall ( (x sl$TRAIN)"
, " (x2 sl$TRAIN) )"
, " (=> (and (elem@@sl$TRAIN x (dom@@sl$TRAIN@@sl$BLK f1))"
, " (elem@@sl$TRAIN x2 (dom@@sl$TRAIN@@sl$BLK f1)))"
, " (=> (= (apply@@sl$TRAIN@@sl$BLK f1 x)"
, " (apply@@sl$TRAIN@@sl$BLK f1 x2))"
, " (= x x2)))))"
, " :pattern"
, " ( (injective@@sl$TRAIN@@sl$BLK f1) ))))"
, "(assert (injective@@sl$TRAIN@@sl$BLK empty-fun@@sl$TRAIN@@sl$BLK))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK))"
, " (x sl$TRAIN) )"
, " (! (=> (elem@@sl$TRAIN x (dom@@sl$TRAIN@@sl$BLK f1))"
, " (elem@@sl$BLK (apply@@sl$TRAIN@@sl$BLK f1 x)"
, " (ran@@sl$TRAIN@@sl$BLK f1)))"
, " :pattern"
, " ( (elem@@sl$BLK (apply@@sl$TRAIN@@sl$BLK f1 x)"
, " (ran@@sl$TRAIN@@sl$BLK f1)) ))))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK))"
, " (s1 (set sl$TRAIN))"
, " (x sl$TRAIN) )"
, " (! (=> (elem@@sl$TRAIN x"
, " (set-diff@@sl$TRAIN (dom@@sl$TRAIN@@sl$BLK f1) s1))"
, " (elem@@sl$BLK (apply@@sl$TRAIN@@sl$BLK f1 x)"
, " (ran@@sl$TRAIN@@sl$BLK (dom-subt@@sl$TRAIN@@sl$BLK s1 f1))))"
, " :pattern"
, " ( (elem@@sl$BLK (apply@@sl$TRAIN@@sl$BLK f1 x)"
, " (ran@@sl$TRAIN@@sl$BLK (dom-subt@@sl$TRAIN@@sl$BLK s1 f1))) ))))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK))"
, " (s1 (set sl$TRAIN))"
, " (x sl$TRAIN) )"
, " (! (=> (elem@@sl$TRAIN x (intersect (dom@@sl$TRAIN@@sl$BLK f1) s1))"
, " (elem@@sl$BLK (apply@@sl$TRAIN@@sl$BLK f1 x)"
, " (ran@@sl$TRAIN@@sl$BLK (dom-rest@@sl$TRAIN@@sl$BLK s1 f1))))"
, " :pattern"
, " ( (elem@@sl$BLK (apply@@sl$TRAIN@@sl$BLK f1 x)"
, " (ran@@sl$TRAIN@@sl$BLK (dom-rest@@sl$TRAIN@@sl$BLK s1 f1))) ))))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK))"
, " (x sl$TRAIN)"
, " (y sl$BLK) )"
, " (! (=> (and (elem@@sl$TRAIN x (dom@@sl$TRAIN@@sl$BLK f1))"
, " (injective@@sl$TRAIN@@sl$BLK f1))"
, " (= (ran@@sl$TRAIN@@sl$BLK (ovl@@sl$TRAIN@@sl$BLK f1 (mk-fun@@sl$TRAIN@@sl$BLK x y)))"
, " (union (set-diff@@sl$BLK (ran@@sl$TRAIN@@sl$BLK f1)"
, " (mk-set@@sl$BLK (apply@@sl$TRAIN@@sl$BLK f1 x)))"
, " (mk-set@@sl$BLK y))))"
, " :pattern"
, " ( (ran@@sl$TRAIN@@sl$BLK (ovl@@sl$TRAIN@@sl$BLK f1 (mk-fun@@sl$TRAIN@@sl$BLK x y))) ))))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK))"
, " (x sl$TRAIN)"
, " (y sl$BLK) )"
, " (! (=> (not (elem@@sl$TRAIN x (dom@@sl$TRAIN@@sl$BLK f1)))"
, " (= (ran@@sl$TRAIN@@sl$BLK (ovl@@sl$TRAIN@@sl$BLK f1 (mk-fun@@sl$TRAIN@@sl$BLK x y)))"
, " (union (ran@@sl$TRAIN@@sl$BLK f1) (mk-set@@sl$BLK y))))"
, " :pattern"
, " ( (ran@@sl$TRAIN@@sl$BLK (ovl@@sl$TRAIN@@sl$BLK f1 (mk-fun@@sl$TRAIN@@sl$BLK x y))) ))))"
, "(assert (forall ( (x sl$BLK)"
, " (y sl$BLK) )"
, " (! (= (elem@@sl$BLK x (mk-set@@sl$BLK y)) (= x y))"
, " :pattern"
, " ( (elem@@sl$BLK x (mk-set@@sl$BLK y)) ))))"
, "(assert (forall ( (x sl$TRAIN)"
, " (y sl$TRAIN) )"
, " (! (= (elem@@sl$TRAIN x (mk-set@@sl$TRAIN y)) (= x y))"
, " :pattern"
, " ( (elem@@sl$TRAIN x (mk-set@@sl$TRAIN y)) ))))"
, "(assert (forall ( (s1 (set sl$BLK))"
, " (s2 (set sl$BLK)) )"
, " (! (=> (finite@@sl$BLK s1)"
, " (finite@@sl$BLK (set-diff@@sl$BLK s1 s2)))"
, " :pattern"
, " ( (finite@@sl$BLK (set-diff@@sl$BLK s1 s2)) ))))"
, "(assert (forall ( (s1 (set sl$LOC))"
, " (s2 (set sl$LOC)) )"
, " (! (=> (finite@@sl$LOC s1)"
, " (finite@@sl$LOC (set-diff@@sl$LOC s1 s2)))"
, " :pattern"
, " ( (finite@@sl$LOC (set-diff@@sl$LOC s1 s2)) ))))"
, "(assert (forall ( (s1 (set sl$TRAIN))"
, " (s2 (set sl$TRAIN)) )"
, " (! (=> (finite@@sl$TRAIN s1)"
, " (finite@@sl$TRAIN (set-diff@@sl$TRAIN s1 s2)))"
, " :pattern"
, " ( (finite@@sl$TRAIN (set-diff@@sl$TRAIN s1 s2)) ))))"
, "(assert (forall ( (s1 (set sl$BLK))"
, " (s2 (set sl$BLK)) )"
, " (! (=> (and (finite@@sl$BLK s1) (finite@@sl$BLK s2))"
, " (finite@@sl$BLK (union s1 s2)))"
, " :pattern"
, " ( (finite@@sl$BLK (union s1 s2)) ))))"
, "(assert (forall ( (s1 (set sl$LOC))"
, " (s2 (set sl$LOC)) )"
, " (! (=> (and (finite@@sl$LOC s1) (finite@@sl$LOC s2))"
, " (finite@@sl$LOC (union s1 s2)))"
, " :pattern"
, " ( (finite@@sl$LOC (union s1 s2)) ))))"
, "(assert (forall ( (s1 (set sl$TRAIN))"
, " (s2 (set sl$TRAIN)) )"
, " (! (=> (and (finite@@sl$TRAIN s1) (finite@@sl$TRAIN s2))"
, " (finite@@sl$TRAIN (union s1 s2)))"
, " :pattern"
, " ( (finite@@sl$TRAIN (union s1 s2)) ))))"
, "(assert (forall ( (s1 (set sl$BLK))"
, " (s2 (set sl$BLK)) )"
, " (! (=> (and (finite@@sl$BLK s2) (not (finite@@sl$BLK s1)))"
, " (not (finite@@sl$BLK (set-diff@@sl$BLK s1 s2))))"
, " :pattern"
, " ( (finite@@sl$BLK (set-diff@@sl$BLK s1 s2)) ))))"
, "(assert (forall ( (s1 (set sl$LOC))"
, " (s2 (set sl$LOC)) )"
, " (! (=> (and (finite@@sl$LOC s2) (not (finite@@sl$LOC s1)))"
, " (not (finite@@sl$LOC (set-diff@@sl$LOC s1 s2))))"
, " :pattern"
, " ( (finite@@sl$LOC (set-diff@@sl$LOC s1 s2)) ))))"
, "(assert (forall ( (s1 (set sl$TRAIN))"
, " (s2 (set sl$TRAIN)) )"
, " (! (=> (and (finite@@sl$TRAIN s2) (not (finite@@sl$TRAIN s1)))"
, " (not (finite@@sl$TRAIN (set-diff@@sl$TRAIN s1 s2))))"
, " :pattern"
, " ( (finite@@sl$TRAIN (set-diff@@sl$TRAIN s1 s2)) ))))"
, "(assert (forall ( (x sl$BLK) )"
, " (! (finite@@sl$BLK (mk-set@@sl$BLK x))"
, " :pattern"
, " ( (finite@@sl$BLK (mk-set@@sl$BLK x)) ))))"
, "(assert (forall ( (x sl$TRAIN) )"
, " (! (finite@@sl$TRAIN (mk-set@@sl$TRAIN x))"
, " :pattern"
, " ( (finite@@sl$TRAIN (mk-set@@sl$TRAIN x)) ))))"
, "(assert (finite@@sl$BLK empty-set@@sl$BLK))"
, "(assert (finite@@sl$LOC empty-set@@sl$LOC))"
, "(assert (finite@@sl$TRAIN empty-set@@sl$TRAIN))"
, "(assert (not (exists ( (loc@prime (pfun sl$TRAIN sl$BLK)) )"
, " (and true"
, " (= loc@prime"
, " (ovl@@sl$TRAIN@@sl$BLK loc (mk-fun@@sl$TRAIN@@sl$BLK t ent)))))))"
, "; asm2"
, "(assert (and (not (= ent ext))"
, " (not (elem@@sl$BLK ent PLF))"
, " (not (elem@@sl$BLK ext PLF))))"
, "; asm3"
, "(assert (forall ( (p sl$BLK) )"
, " (! (= (not (= p ext))"
, " (elem@@sl$BLK p (union (mk-set@@sl$BLK ent) PLF)))"
, " :pattern"
, " ( (elem@@sl$BLK p (union (mk-set@@sl$BLK ent) PLF)) ))))"
, "; asm4"
, "(assert (forall ( (p sl$BLK) )"
, " (! (= (not (= p ent))"
, " (elem@@sl$BLK p (union (mk-set@@sl$BLK ext) PLF)))"
, " :pattern"
, " ( (elem@@sl$BLK p (union (mk-set@@sl$BLK ext) PLF)) ))))"
, "; asm5"
, "(assert (forall ( (p sl$BLK) )"
, " (! (= (or (= p ent) (= p ext))"
, " (not (elem@@sl$BLK p PLF)))"
, " :pattern"
, " ( (elem@@sl$BLK p PLF) ))))"
, "; axm0"
, "(assert (= sl$BLK"
, " (union (union (mk-set@@sl$BLK ent) (mk-set@@sl$BLK ext))"
, " PLF)))"
, "; grd1"
, "(assert (not (elem@@sl$TRAIN t in)))"
, "; inv1"
, "(assert (forall ( (t sl$TRAIN) )"
, " (! (=> (elem@@sl$TRAIN t in)"
, " (elem@@sl$BLK (apply@@sl$TRAIN@@sl$BLK loc t) sl$BLK))"
, " :pattern"
, " ( (elem@@sl$BLK (apply@@sl$TRAIN@@sl$BLK loc t) sl$BLK) ))))"
, "; inv2"
, "(assert (= (dom@@sl$TRAIN@@sl$BLK loc) in))"
, "(assert (not true))"
, "(check-sat-using (or-else (then qe smt)"
, " (then simplify smt)"
, " (then skip smt)"
, " (then (using-params simplify :expand-power true) smt)))"
, "; train0/enter/FIS/loc@prime"
]
case20 :: IO String
case20 = proof_obligation path0 "train0/enter/FIS/loc@prime" 0
result3 :: String
result3 = unlines
[ "; train0/leave/FIS/in@prime"
, "(set-option :auto-config false)"
, "(set-option :smt.timeout 3000)"
, "(declare-datatypes (a) ( (Maybe (Just (fromJust a)) Nothing) ))"
, "(declare-datatypes () ( (Null null) ))"
, "(declare-datatypes (a b) ( (Pair (pair (first a) (second b))) ))"
, "(define-sort guarded (a) (Maybe a))"
, "(declare-sort sl$BLK 0)"
, "; comment: we don't need to declare the sort Bool"
, "; comment: we don't need to declare the sort Int"
, "(declare-sort sl$LOC 0)"
, "; comment: we don't need to declare the sort Real"
, "(declare-sort sl$TRAIN 0)"
, "(define-sort pfun (a b) (Array a (Maybe b)))"
, "(define-sort set (a) (Array a Bool))"
, "(declare-const PLF (set sl$BLK))"
, "(declare-const ent sl$BLK)"
, "(declare-const ext sl$BLK)"
, "(declare-const in (set sl$TRAIN))"
, "(declare-const in@prime (set sl$TRAIN))"
, "(declare-const loc (pfun sl$TRAIN sl$BLK))"
, "(declare-const loc@prime (pfun sl$TRAIN sl$BLK))"
, "(declare-const t sl$TRAIN)"
, "(declare-fun apply@@sl$TRAIN@@sl$BLK"
, " ( (pfun sl$TRAIN sl$BLK)"
, " sl$TRAIN )"
, " sl$BLK)"
, "(declare-fun card@@sl$BLK ( (set sl$BLK) ) Int)"
, "(declare-fun card@@sl$LOC ( (set sl$LOC) ) Int)"
, "(declare-fun card@@sl$TRAIN ( (set sl$TRAIN) ) Int)"
, "(declare-fun dom@@sl$TRAIN@@sl$BLK"
, " ( (pfun sl$TRAIN sl$BLK) )"
, " (set sl$TRAIN))"
, "(declare-fun dom-rest@@sl$TRAIN@@sl$BLK"
, " ( (set sl$TRAIN)"
, " (pfun sl$TRAIN sl$BLK) )"
, " (pfun sl$TRAIN sl$BLK))"
, "(declare-fun dom-subt@@sl$TRAIN@@sl$BLK"
, " ( (set sl$TRAIN)"
, " (pfun sl$TRAIN sl$BLK) )"
, " (pfun sl$TRAIN sl$BLK))"
, "(declare-fun empty-fun@@sl$TRAIN@@sl$BLK"
, " ()"
, " (pfun sl$TRAIN sl$BLK))"
, "(declare-fun finite@@sl$BLK ( (set sl$BLK) ) Bool)"
, "(declare-fun finite@@sl$LOC ( (set sl$LOC) ) Bool)"
, "(declare-fun finite@@sl$TRAIN ( (set sl$TRAIN) ) Bool)"
, "(declare-fun injective@@sl$TRAIN@@sl$BLK"
, " ( (pfun sl$TRAIN sl$BLK) )"
, " Bool)"
, "(declare-fun mk-fun@@sl$TRAIN@@sl$BLK"
, " (sl$TRAIN sl$BLK)"
, " (pfun sl$TRAIN sl$BLK))"
, "(declare-fun mk-set@@sl$BLK (sl$BLK) (set sl$BLK))"
, "(declare-fun mk-set@@sl$TRAIN (sl$TRAIN) (set sl$TRAIN))"
, "(declare-fun ovl@@sl$TRAIN@@sl$BLK"
, " ( (pfun sl$TRAIN sl$BLK)"
, " (pfun sl$TRAIN sl$BLK) )"
, " (pfun sl$TRAIN sl$BLK))"
, "(declare-fun ran@@sl$TRAIN@@sl$BLK"
, " ( (pfun sl$TRAIN sl$BLK) )"
, " (set sl$BLK))"
, "(define-fun all@@sl$BLK"
, " ()"
, " (set sl$BLK)"
, " ( (as const (set sl$BLK))"
, " true ))"
, "(define-fun all@@sl$LOC"
, " ()"
, " (set sl$LOC)"
, " ( (as const (set sl$LOC))"
, " true ))"
, "(define-fun all@@sl$TRAIN"
, " ()"
, " (set sl$TRAIN)"
, " ( (as const (set sl$TRAIN))"
, " true ))"
, "(define-fun compl@@sl$BLK"
, " ( (s1 (set sl$BLK)) )"
, " (set sl$BLK)"
, " ( (_ map not)"
, " s1 ))"
, "(define-fun compl@@sl$LOC"
, " ( (s1 (set sl$LOC)) )"
, " (set sl$LOC)"
, " ( (_ map not)"
, " s1 ))"
, "(define-fun compl@@sl$TRAIN"
, " ( (s1 (set sl$TRAIN)) )"
, " (set sl$TRAIN)"
, " ( (_ map not)"
, " s1 ))"
, "(define-fun elem@@sl$BLK"
, " ( (x sl$BLK)"
, " (s1 (set sl$BLK)) )"
, " Bool"
, " (select s1 x))"
, "(define-fun elem@@sl$TRAIN"
, " ( (x sl$TRAIN)"
, " (s1 (set sl$TRAIN)) )"
, " Bool"
, " (select s1 x))"
, "(define-fun empty-set@@sl$BLK"
, " ()"
, " (set sl$BLK)"
, " ( (as const (set sl$BLK))"
, " false ))"
, "(define-fun empty-set@@sl$LOC"
, " ()"
, " (set sl$LOC)"
, " ( (as const (set sl$LOC))"
, " false ))"
, "(define-fun empty-set@@sl$TRAIN"
, " ()"
, " (set sl$TRAIN)"
, " ( (as const (set sl$TRAIN))"
, " false ))"
, "(define-fun set-diff@@sl$BLK"
, " ( (s1 (set sl$BLK))"
, " (s2 (set sl$BLK)) )"
, " (set sl$BLK)"
, " (intersect s1 ( (_ map not) s2 )))"
, "(define-fun set-diff@@sl$LOC"
, " ( (s1 (set sl$LOC))"
, " (s2 (set sl$LOC)) )"
, " (set sl$LOC)"
, " (intersect s1 ( (_ map not) s2 )))"
, "(define-fun set-diff@@sl$TRAIN"
, " ( (s1 (set sl$TRAIN))"
, " (s2 (set sl$TRAIN)) )"
, " (set sl$TRAIN)"
, " (intersect s1 ( (_ map not) s2 )))"
, "(define-fun st-subset@@sl$BLK"
, " ( (s1 (set sl$BLK))"
, " (s2 (set sl$BLK)) )"
, " Bool"
, " (and (subset s1 s2) (not (= s1 s2))))"
, "(define-fun st-subset@@sl$LOC"
, " ( (s1 (set sl$LOC))"
, " (s2 (set sl$LOC)) )"
, " Bool"
, " (and (subset s1 s2) (not (= s1 s2))))"
, "(define-fun st-subset@@sl$TRAIN"
, " ( (s1 (set sl$TRAIN))"
, " (s2 (set sl$TRAIN)) )"
, " Bool"
, " (and (subset s1 s2) (not (= s1 s2))))"
, "(define-fun sl$BLK"
, " ()"
, " (set sl$BLK)"
, " ( (as const (set sl$BLK))"
, " true ))"
, "(define-fun sl$LOC"
, " ()"
, " (set sl$LOC)"
, " ( (as const (set sl$LOC))"
, " true ))"
, "(define-fun sl$TRAIN"
, " ()"
, " (set sl$TRAIN)"
, " ( (as const (set sl$TRAIN))"
, " true ))"
, "(assert (forall ( (r (set sl$BLK)) )"
, " (! (=> (finite@@sl$BLK r) (<= 0 (card@@sl$BLK r)))"
, " :pattern"
, " ( (<= 0 (card@@sl$BLK r)) ))))"
, "(assert (forall ( (r (set sl$LOC)) )"
, " (! (=> (finite@@sl$LOC r) (<= 0 (card@@sl$LOC r)))"
, " :pattern"
, " ( (<= 0 (card@@sl$LOC r)) ))))"
, "(assert (forall ( (r (set sl$TRAIN)) )"
, " (! (=> (finite@@sl$TRAIN r) (<= 0 (card@@sl$TRAIN r)))"
, " :pattern"
, " ( (<= 0 (card@@sl$TRAIN r)) ))))"
, "(assert (forall ( (r (set sl$BLK)) )"
, " (! (= (= (card@@sl$BLK r) 0) (= r empty-set@@sl$BLK))"
, " :pattern"
, " ( (card@@sl$BLK r) ))))"
, "(assert (forall ( (r (set sl$LOC)) )"
, " (! (= (= (card@@sl$LOC r) 0) (= r empty-set@@sl$LOC))"
, " :pattern"
, " ( (card@@sl$LOC r) ))))"
, "(assert (forall ( (r (set sl$TRAIN)) )"
, " (! (= (= (card@@sl$TRAIN r) 0)"
, " (= r empty-set@@sl$TRAIN))"
, " :pattern"
, " ( (card@@sl$TRAIN r) ))))"
, "(assert (forall ( (x sl$BLK) )"
, " (! (= (card@@sl$BLK (mk-set@@sl$BLK x)) 1)"
, " :pattern"
, " ( (card@@sl$BLK (mk-set@@sl$BLK x)) ))))"
, "(assert (forall ( (x sl$TRAIN) )"
, " (! (= (card@@sl$TRAIN (mk-set@@sl$TRAIN x)) 1)"
, " :pattern"
, " ( (card@@sl$TRAIN (mk-set@@sl$TRAIN x)) ))))"
, "(assert (forall ( (r (set sl$BLK)) )"
, " (! (= (= (card@@sl$BLK r) 1)"
, " (exists ( (x sl$BLK) ) (and true (= r (mk-set@@sl$BLK x)))))"
, " :pattern"
, " ( (card@@sl$BLK r) ))))"
, "(assert (forall ( (r (set sl$TRAIN)) )"
, " (! (= (= (card@@sl$TRAIN r) 1)"
, " (exists ( (x sl$TRAIN) )"
, " (and true (= r (mk-set@@sl$TRAIN x)))))"
, " :pattern"
, " ( (card@@sl$TRAIN r) ))))"
, "(assert (forall ( (r (set sl$BLK))"
, " (r0 (set sl$BLK)) )"
, " (! (=> (= (intersect r r0) empty-set@@sl$BLK)"
, " (= (card@@sl$BLK (union r r0))"
, " (+ (card@@sl$BLK r) (card@@sl$BLK r0))))"
, " :pattern"
, " ( (card@@sl$BLK (union r r0)) ))))"
, "(assert (forall ( (r (set sl$LOC))"
, " (r0 (set sl$LOC)) )"
, " (! (=> (= (intersect r r0) empty-set@@sl$LOC)"
, " (= (card@@sl$LOC (union r r0))"
, " (+ (card@@sl$LOC r) (card@@sl$LOC r0))))"
, " :pattern"
, " ( (card@@sl$LOC (union r r0)) ))))"
, "(assert (forall ( (r (set sl$TRAIN))"
, " (r0 (set sl$TRAIN)) )"
, " (! (=> (= (intersect r r0) empty-set@@sl$TRAIN)"
, " (= (card@@sl$TRAIN (union r r0))"
, " (+ (card@@sl$TRAIN r) (card@@sl$TRAIN r0))))"
, " :pattern"
, " ( (card@@sl$TRAIN (union r r0)) ))))"
, "(assert (= (dom@@sl$TRAIN@@sl$BLK empty-fun@@sl$TRAIN@@sl$BLK)"
, " empty-set@@sl$TRAIN))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK)) )"
, " (! (= (ovl@@sl$TRAIN@@sl$BLK f1 empty-fun@@sl$TRAIN@@sl$BLK)"
, " f1)"
, " :pattern"
, " ( (ovl@@sl$TRAIN@@sl$BLK f1 empty-fun@@sl$TRAIN@@sl$BLK) ))))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK)) )"
, " (! (= (ovl@@sl$TRAIN@@sl$BLK empty-fun@@sl$TRAIN@@sl$BLK f1)"
, " f1)"
, " :pattern"
, " ( (ovl@@sl$TRAIN@@sl$BLK empty-fun@@sl$TRAIN@@sl$BLK f1) ))))"
, "(assert (forall ( (x sl$TRAIN)"
, " (y sl$BLK) )"
, " (! (= (dom@@sl$TRAIN@@sl$BLK (mk-fun@@sl$TRAIN@@sl$BLK x y))"
, " (mk-set@@sl$TRAIN x))"
, " :pattern"
, " ( (dom@@sl$TRAIN@@sl$BLK (mk-fun@@sl$TRAIN@@sl$BLK x y)) ))))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK))"
, " (f2 (pfun sl$TRAIN sl$BLK))"
, " (x sl$TRAIN) )"
, " (! (=> (elem@@sl$TRAIN x (dom@@sl$TRAIN@@sl$BLK f2))"
, " (= (apply@@sl$TRAIN@@sl$BLK (ovl@@sl$TRAIN@@sl$BLK f1 f2) x)"
, " (apply@@sl$TRAIN@@sl$BLK f2 x)))"
, " :pattern"
, " ( (apply@@sl$TRAIN@@sl$BLK (ovl@@sl$TRAIN@@sl$BLK f1 f2) x) ))))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK))"
, " (f2 (pfun sl$TRAIN sl$BLK))"
, " (x sl$TRAIN) )"
, " (! (=> (and (elem@@sl$TRAIN x (dom@@sl$TRAIN@@sl$BLK f1))"
, " (not (elem@@sl$TRAIN x (dom@@sl$TRAIN@@sl$BLK f2))))"
, " (= (apply@@sl$TRAIN@@sl$BLK (ovl@@sl$TRAIN@@sl$BLK f1 f2) x)"
, " (apply@@sl$TRAIN@@sl$BLK f1 x)))"
, " :pattern"
, " ( (apply@@sl$TRAIN@@sl$BLK (ovl@@sl$TRAIN@@sl$BLK f1 f2) x) ))))"
, "(assert (forall ( (x sl$TRAIN)"
, " (y sl$BLK) )"
, " (! (= (apply@@sl$TRAIN@@sl$BLK (mk-fun@@sl$TRAIN@@sl$BLK x y) x)"
, " y)"
, " :pattern"
, " ( (apply@@sl$TRAIN@@sl$BLK (mk-fun@@sl$TRAIN@@sl$BLK x y) x) ))))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK))"
, " (s1 (set sl$TRAIN))"
, " (x sl$TRAIN) )"
, " (! (=> (and (elem@@sl$TRAIN x s1)"
, " (elem@@sl$TRAIN x (dom@@sl$TRAIN@@sl$BLK f1)))"
, " (= (apply@@sl$TRAIN@@sl$BLK (dom-rest@@sl$TRAIN@@sl$BLK s1 f1) x)"
, " (apply@@sl$TRAIN@@sl$BLK f1 x)))"
, " :pattern"
, " ( (apply@@sl$TRAIN@@sl$BLK (dom-rest@@sl$TRAIN@@sl$BLK s1 f1) x) ))))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK))"
, " (s1 (set sl$TRAIN))"
, " (x sl$TRAIN) )"
, " (! (=> (elem@@sl$TRAIN x"
, " (set-diff@@sl$TRAIN (dom@@sl$TRAIN@@sl$BLK f1) s1))"
, " (= (apply@@sl$TRAIN@@sl$BLK (dom-subt@@sl$TRAIN@@sl$BLK s1 f1) x)"
, " (apply@@sl$TRAIN@@sl$BLK f1 x)))"
, " :pattern"
, " ( (apply@@sl$TRAIN@@sl$BLK (dom-subt@@sl$TRAIN@@sl$BLK s1 f1) x) ))))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK))"
, " (f2 (pfun sl$TRAIN sl$BLK)) )"
, " (! (= (dom@@sl$TRAIN@@sl$BLK (ovl@@sl$TRAIN@@sl$BLK f1 f2))"
, " (union (dom@@sl$TRAIN@@sl$BLK f1)"
, " (dom@@sl$TRAIN@@sl$BLK f2)))"
, " :pattern"
, " ( (dom@@sl$TRAIN@@sl$BLK (ovl@@sl$TRAIN@@sl$BLK f1 f2)) ))))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK))"
, " (s1 (set sl$TRAIN)) )"
, " (! (= (dom@@sl$TRAIN@@sl$BLK (dom-rest@@sl$TRAIN@@sl$BLK s1 f1))"
, " (intersect s1 (dom@@sl$TRAIN@@sl$BLK f1)))"
, " :pattern"
, " ( (dom@@sl$TRAIN@@sl$BLK (dom-rest@@sl$TRAIN@@sl$BLK s1 f1)) ))))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK))"
, " (s1 (set sl$TRAIN)) )"
, " (! (= (dom@@sl$TRAIN@@sl$BLK (dom-subt@@sl$TRAIN@@sl$BLK s1 f1))"
, " (set-diff@@sl$TRAIN (dom@@sl$TRAIN@@sl$BLK f1) s1))"
, " :pattern"
, " ( (dom@@sl$TRAIN@@sl$BLK (dom-subt@@sl$TRAIN@@sl$BLK s1 f1)) ))))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK))"
, " (x sl$TRAIN)"
, " (y sl$BLK) )"
, " (! (= (and (elem@@sl$TRAIN x (dom@@sl$TRAIN@@sl$BLK f1))"
, " (= (apply@@sl$TRAIN@@sl$BLK f1 x) y))"
, " (= (select f1 x) (Just y)))"
, " :pattern"
, " ( (elem@@sl$TRAIN x (dom@@sl$TRAIN@@sl$BLK f1))"
, " (apply@@sl$TRAIN@@sl$BLK f1 x)"
, " (select f1 x)"
, " (Just y) ))))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK))"
, " (x sl$TRAIN)"
, " (x2 sl$TRAIN)"
, " (y sl$BLK) )"
, " (! (=> (not (= x x2))"
, " (= (apply@@sl$TRAIN@@sl$BLK (ovl@@sl$TRAIN@@sl$BLK f1 (mk-fun@@sl$TRAIN@@sl$BLK x y))"
, " x2)"
, " (apply@@sl$TRAIN@@sl$BLK f1 x2)))"
, " :pattern"
, " ( (apply@@sl$TRAIN@@sl$BLK (ovl@@sl$TRAIN@@sl$BLK f1 (mk-fun@@sl$TRAIN@@sl$BLK x y))"
, " x2) ))))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK))"
, " (x sl$TRAIN)"
, " (y sl$BLK) )"
, " (! (= (apply@@sl$TRAIN@@sl$BLK (ovl@@sl$TRAIN@@sl$BLK f1 (mk-fun@@sl$TRAIN@@sl$BLK x y))"
, " x)"
, " y)"
, " :pattern"
, " ( (apply@@sl$TRAIN@@sl$BLK (ovl@@sl$TRAIN@@sl$BLK f1 (mk-fun@@sl$TRAIN@@sl$BLK x y))"
, " x) ))))"
, "(assert (= (ran@@sl$TRAIN@@sl$BLK empty-fun@@sl$TRAIN@@sl$BLK)"
, " empty-set@@sl$BLK))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK))"
, " (y sl$BLK) )"
, " (! (= (elem@@sl$BLK y (ran@@sl$TRAIN@@sl$BLK f1))"
, " (exists ( (x sl$TRAIN) )"
, " (and true"
, " (and (elem@@sl$TRAIN x (dom@@sl$TRAIN@@sl$BLK f1))"
, " (= (apply@@sl$TRAIN@@sl$BLK f1 x) y)))))"
, " :pattern"
, " ( (elem@@sl$BLK y (ran@@sl$TRAIN@@sl$BLK f1)) ))))"
, "(assert (forall ( (x sl$TRAIN)"
, " (y sl$BLK) )"
, " (! (= (ran@@sl$TRAIN@@sl$BLK (mk-fun@@sl$TRAIN@@sl$BLK x y))"
, " (mk-set@@sl$BLK y))"
, " :pattern"
, " ( (ran@@sl$TRAIN@@sl$BLK (mk-fun@@sl$TRAIN@@sl$BLK x y)) ))))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK)) )"
, " (! (= (injective@@sl$TRAIN@@sl$BLK f1)"
, " (forall ( (x sl$TRAIN)"
, " (x2 sl$TRAIN) )"
, " (=> (and (elem@@sl$TRAIN x (dom@@sl$TRAIN@@sl$BLK f1))"
, " (elem@@sl$TRAIN x2 (dom@@sl$TRAIN@@sl$BLK f1)))"
, " (=> (= (apply@@sl$TRAIN@@sl$BLK f1 x)"
, " (apply@@sl$TRAIN@@sl$BLK f1 x2))"
, " (= x x2)))))"
, " :pattern"
, " ( (injective@@sl$TRAIN@@sl$BLK f1) ))))"
, "(assert (injective@@sl$TRAIN@@sl$BLK empty-fun@@sl$TRAIN@@sl$BLK))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK))"
, " (x sl$TRAIN) )"
, " (! (=> (elem@@sl$TRAIN x (dom@@sl$TRAIN@@sl$BLK f1))"
, " (elem@@sl$BLK (apply@@sl$TRAIN@@sl$BLK f1 x)"
, " (ran@@sl$TRAIN@@sl$BLK f1)))"
, " :pattern"
, " ( (elem@@sl$BLK (apply@@sl$TRAIN@@sl$BLK f1 x)"
, " (ran@@sl$TRAIN@@sl$BLK f1)) ))))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK))"
, " (s1 (set sl$TRAIN))"
, " (x sl$TRAIN) )"
, " (! (=> (elem@@sl$TRAIN x"
, " (set-diff@@sl$TRAIN (dom@@sl$TRAIN@@sl$BLK f1) s1))"
, " (elem@@sl$BLK (apply@@sl$TRAIN@@sl$BLK f1 x)"
, " (ran@@sl$TRAIN@@sl$BLK (dom-subt@@sl$TRAIN@@sl$BLK s1 f1))))"
, " :pattern"
, " ( (elem@@sl$BLK (apply@@sl$TRAIN@@sl$BLK f1 x)"
, " (ran@@sl$TRAIN@@sl$BLK (dom-subt@@sl$TRAIN@@sl$BLK s1 f1))) ))))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK))"
, " (s1 (set sl$TRAIN))"
, " (x sl$TRAIN) )"
, " (! (=> (elem@@sl$TRAIN x (intersect (dom@@sl$TRAIN@@sl$BLK f1) s1))"
, " (elem@@sl$BLK (apply@@sl$TRAIN@@sl$BLK f1 x)"
, " (ran@@sl$TRAIN@@sl$BLK (dom-rest@@sl$TRAIN@@sl$BLK s1 f1))))"
, " :pattern"
, " ( (elem@@sl$BLK (apply@@sl$TRAIN@@sl$BLK f1 x)"
, " (ran@@sl$TRAIN@@sl$BLK (dom-rest@@sl$TRAIN@@sl$BLK s1 f1))) ))))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK))"
, " (x sl$TRAIN)"
, " (y sl$BLK) )"
, " (! (=> (and (elem@@sl$TRAIN x (dom@@sl$TRAIN@@sl$BLK f1))"
, " (injective@@sl$TRAIN@@sl$BLK f1))"
, " (= (ran@@sl$TRAIN@@sl$BLK (ovl@@sl$TRAIN@@sl$BLK f1 (mk-fun@@sl$TRAIN@@sl$BLK x y)))"
, " (union (set-diff@@sl$BLK (ran@@sl$TRAIN@@sl$BLK f1)"
, " (mk-set@@sl$BLK (apply@@sl$TRAIN@@sl$BLK f1 x)))"
, " (mk-set@@sl$BLK y))))"
, " :pattern"
, " ( (ran@@sl$TRAIN@@sl$BLK (ovl@@sl$TRAIN@@sl$BLK f1 (mk-fun@@sl$TRAIN@@sl$BLK x y))) ))))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK))"
, " (x sl$TRAIN)"
, " (y sl$BLK) )"
, " (! (=> (not (elem@@sl$TRAIN x (dom@@sl$TRAIN@@sl$BLK f1)))"
, " (= (ran@@sl$TRAIN@@sl$BLK (ovl@@sl$TRAIN@@sl$BLK f1 (mk-fun@@sl$TRAIN@@sl$BLK x y)))"
, " (union (ran@@sl$TRAIN@@sl$BLK f1) (mk-set@@sl$BLK y))))"
, " :pattern"
, " ( (ran@@sl$TRAIN@@sl$BLK (ovl@@sl$TRAIN@@sl$BLK f1 (mk-fun@@sl$TRAIN@@sl$BLK x y))) ))))"
, "(assert (forall ( (x sl$BLK)"
, " (y sl$BLK) )"
, " (! (= (elem@@sl$BLK x (mk-set@@sl$BLK y)) (= x y))"
, " :pattern"
, " ( (elem@@sl$BLK x (mk-set@@sl$BLK y)) ))))"
, "(assert (forall ( (x sl$TRAIN)"
, " (y sl$TRAIN) )"
, " (! (= (elem@@sl$TRAIN x (mk-set@@sl$TRAIN y)) (= x y))"
, " :pattern"
, " ( (elem@@sl$TRAIN x (mk-set@@sl$TRAIN y)) ))))"
, "(assert (forall ( (s1 (set sl$BLK))"
, " (s2 (set sl$BLK)) )"
, " (! (=> (finite@@sl$BLK s1)"
, " (finite@@sl$BLK (set-diff@@sl$BLK s1 s2)))"
, " :pattern"
, " ( (finite@@sl$BLK (set-diff@@sl$BLK s1 s2)) ))))"
, "(assert (forall ( (s1 (set sl$LOC))"
, " (s2 (set sl$LOC)) )"
, " (! (=> (finite@@sl$LOC s1)"
, " (finite@@sl$LOC (set-diff@@sl$LOC s1 s2)))"
, " :pattern"
, " ( (finite@@sl$LOC (set-diff@@sl$LOC s1 s2)) ))))"
, "(assert (forall ( (s1 (set sl$TRAIN))"
, " (s2 (set sl$TRAIN)) )"
, " (! (=> (finite@@sl$TRAIN s1)"
, " (finite@@sl$TRAIN (set-diff@@sl$TRAIN s1 s2)))"
, " :pattern"
, " ( (finite@@sl$TRAIN (set-diff@@sl$TRAIN s1 s2)) ))))"
, "(assert (forall ( (s1 (set sl$BLK))"
, " (s2 (set sl$BLK)) )"
, " (! (=> (and (finite@@sl$BLK s1) (finite@@sl$BLK s2))"
, " (finite@@sl$BLK (union s1 s2)))"
, " :pattern"
, " ( (finite@@sl$BLK (union s1 s2)) ))))"
, "(assert (forall ( (s1 (set sl$LOC))"
, " (s2 (set sl$LOC)) )"
, " (! (=> (and (finite@@sl$LOC s1) (finite@@sl$LOC s2))"
, " (finite@@sl$LOC (union s1 s2)))"
, " :pattern"
, " ( (finite@@sl$LOC (union s1 s2)) ))))"
, "(assert (forall ( (s1 (set sl$TRAIN))"
, " (s2 (set sl$TRAIN)) )"
, " (! (=> (and (finite@@sl$TRAIN s1) (finite@@sl$TRAIN s2))"
, " (finite@@sl$TRAIN (union s1 s2)))"
, " :pattern"
, " ( (finite@@sl$TRAIN (union s1 s2)) ))))"
, "(assert (forall ( (s1 (set sl$BLK))"
, " (s2 (set sl$BLK)) )"
, " (! (=> (and (finite@@sl$BLK s2) (not (finite@@sl$BLK s1)))"
, " (not (finite@@sl$BLK (set-diff@@sl$BLK s1 s2))))"
, " :pattern"
, " ( (finite@@sl$BLK (set-diff@@sl$BLK s1 s2)) ))))"
, "(assert (forall ( (s1 (set sl$LOC))"
, " (s2 (set sl$LOC)) )"
, " (! (=> (and (finite@@sl$LOC s2) (not (finite@@sl$LOC s1)))"
, " (not (finite@@sl$LOC (set-diff@@sl$LOC s1 s2))))"
, " :pattern"
, " ( (finite@@sl$LOC (set-diff@@sl$LOC s1 s2)) ))))"
, "(assert (forall ( (s1 (set sl$TRAIN))"
, " (s2 (set sl$TRAIN)) )"
, " (! (=> (and (finite@@sl$TRAIN s2) (not (finite@@sl$TRAIN s1)))"
, " (not (finite@@sl$TRAIN (set-diff@@sl$TRAIN s1 s2))))"
, " :pattern"
, " ( (finite@@sl$TRAIN (set-diff@@sl$TRAIN s1 s2)) ))))"
, "(assert (forall ( (x sl$BLK) )"
, " (! (finite@@sl$BLK (mk-set@@sl$BLK x))"
, " :pattern"
, " ( (finite@@sl$BLK (mk-set@@sl$BLK x)) ))))"
, "(assert (forall ( (x sl$TRAIN) )"
, " (! (finite@@sl$TRAIN (mk-set@@sl$TRAIN x))"
, " :pattern"
, " ( (finite@@sl$TRAIN (mk-set@@sl$TRAIN x)) ))))"
, "(assert (finite@@sl$BLK empty-set@@sl$BLK))"
, "(assert (finite@@sl$LOC empty-set@@sl$LOC))"
, "(assert (finite@@sl$TRAIN empty-set@@sl$TRAIN))"
, "(assert (not (exists ( (in@prime (set sl$TRAIN)) )"
, " (and true"
, " (= in@prime"
, " (set-diff@@sl$TRAIN in (mk-set@@sl$TRAIN t)))))))"
, "; asm2"
, "(assert (and (not (= ent ext))"
, " (not (elem@@sl$BLK ent PLF))"
, " (not (elem@@sl$BLK ext PLF))))"
, "; asm3"
, "(assert (forall ( (p sl$BLK) )"
, " (! (= (not (= p ext))"
, " (elem@@sl$BLK p (union (mk-set@@sl$BLK ent) PLF)))"
, " :pattern"
, " ( (elem@@sl$BLK p (union (mk-set@@sl$BLK ent) PLF)) ))))"
, "; asm4"
, "(assert (forall ( (p sl$BLK) )"
, " (! (= (not (= p ent))"
, " (elem@@sl$BLK p (union (mk-set@@sl$BLK ext) PLF)))"
, " :pattern"
, " ( (elem@@sl$BLK p (union (mk-set@@sl$BLK ext) PLF)) ))))"
, "; asm5"
, "(assert (forall ( (p sl$BLK) )"
, " (! (= (or (= p ent) (= p ext))"
, " (not (elem@@sl$BLK p PLF)))"
, " :pattern"
, " ( (elem@@sl$BLK p PLF) ))))"
, "; axm0"
, "(assert (= sl$BLK"
, " (union (union (mk-set@@sl$BLK ent) (mk-set@@sl$BLK ext))"
, " PLF)))"
, "; c0"
, "(assert (elem@@sl$TRAIN t in))"
, "; grd0"
, "(assert (and (= (apply@@sl$TRAIN@@sl$BLK loc t) ext)"
, " (elem@@sl$TRAIN t in)))"
, "; inv1"
, "(assert (forall ( (t sl$TRAIN) )"
, " (! (=> (elem@@sl$TRAIN t in)"
, " (elem@@sl$BLK (apply@@sl$TRAIN@@sl$BLK loc t) sl$BLK))"
, " :pattern"
, " ( (elem@@sl$BLK (apply@@sl$TRAIN@@sl$BLK loc t) sl$BLK) ))))"
, "; inv2"
, "(assert (= (dom@@sl$TRAIN@@sl$BLK loc) in))"
, "(assert (not true))"
, "(check-sat-using (or-else (then qe smt)"
, " (then simplify smt)"
, " (then skip smt)"
, " (then (using-params simplify :expand-power true) smt)))"
, "; train0/leave/FIS/in@prime"
]
case3 :: IO String
case3 = proof_obligation path0 "train0/leave/FIS/in@prime" 0
result19 :: String
result19 = unlines
[ "; train0/leave/FIS/loc@prime"
, "(set-option :auto-config false)"
, "(set-option :smt.timeout 3000)"
, "(declare-datatypes (a) ( (Maybe (Just (fromJust a)) Nothing) ))"
, "(declare-datatypes () ( (Null null) ))"
, "(declare-datatypes (a b) ( (Pair (pair (first a) (second b))) ))"
, "(define-sort guarded (a) (Maybe a))"
, "(declare-sort sl$BLK 0)"
, "; comment: we don't need to declare the sort Bool"
, "; comment: we don't need to declare the sort Int"
, "(declare-sort sl$LOC 0)"
, "; comment: we don't need to declare the sort Real"
, "(declare-sort sl$TRAIN 0)"
, "(define-sort pfun (a b) (Array a (Maybe b)))"
, "(define-sort set (a) (Array a Bool))"
, "(declare-const PLF (set sl$BLK))"
, "(declare-const ent sl$BLK)"
, "(declare-const ext sl$BLK)"
, "(declare-const in (set sl$TRAIN))"
, "(declare-const in@prime (set sl$TRAIN))"
, "(declare-const loc (pfun sl$TRAIN sl$BLK))"
, "(declare-const loc@prime (pfun sl$TRAIN sl$BLK))"
, "(declare-const t sl$TRAIN)"
, "(declare-fun apply@@sl$TRAIN@@sl$BLK"
, " ( (pfun sl$TRAIN sl$BLK)"
, " sl$TRAIN )"
, " sl$BLK)"
, "(declare-fun card@@sl$BLK ( (set sl$BLK) ) Int)"
, "(declare-fun card@@sl$LOC ( (set sl$LOC) ) Int)"
, "(declare-fun card@@sl$TRAIN ( (set sl$TRAIN) ) Int)"
, "(declare-fun dom@@sl$TRAIN@@sl$BLK"
, " ( (pfun sl$TRAIN sl$BLK) )"
, " (set sl$TRAIN))"
, "(declare-fun dom-rest@@sl$TRAIN@@sl$BLK"
, " ( (set sl$TRAIN)"
, " (pfun sl$TRAIN sl$BLK) )"
, " (pfun sl$TRAIN sl$BLK))"
, "(declare-fun dom-subt@@sl$TRAIN@@sl$BLK"
, " ( (set sl$TRAIN)"
, " (pfun sl$TRAIN sl$BLK) )"
, " (pfun sl$TRAIN sl$BLK))"
, "(declare-fun empty-fun@@sl$TRAIN@@sl$BLK"
, " ()"
, " (pfun sl$TRAIN sl$BLK))"
, "(declare-fun finite@@sl$BLK ( (set sl$BLK) ) Bool)"
, "(declare-fun finite@@sl$LOC ( (set sl$LOC) ) Bool)"
, "(declare-fun finite@@sl$TRAIN ( (set sl$TRAIN) ) Bool)"
, "(declare-fun injective@@sl$TRAIN@@sl$BLK"
, " ( (pfun sl$TRAIN sl$BLK) )"
, " Bool)"
, "(declare-fun mk-fun@@sl$TRAIN@@sl$BLK"
, " (sl$TRAIN sl$BLK)"
, " (pfun sl$TRAIN sl$BLK))"
, "(declare-fun mk-set@@sl$BLK (sl$BLK) (set sl$BLK))"
, "(declare-fun mk-set@@sl$TRAIN (sl$TRAIN) (set sl$TRAIN))"
, "(declare-fun ovl@@sl$TRAIN@@sl$BLK"
, " ( (pfun sl$TRAIN sl$BLK)"
, " (pfun sl$TRAIN sl$BLK) )"
, " (pfun sl$TRAIN sl$BLK))"
, "(declare-fun ran@@sl$TRAIN@@sl$BLK"
, " ( (pfun sl$TRAIN sl$BLK) )"
, " (set sl$BLK))"
, "(define-fun all@@sl$BLK"
, " ()"
, " (set sl$BLK)"
, " ( (as const (set sl$BLK))"
, " true ))"
, "(define-fun all@@sl$LOC"
, " ()"
, " (set sl$LOC)"
, " ( (as const (set sl$LOC))"
, " true ))"
, "(define-fun all@@sl$TRAIN"
, " ()"
, " (set sl$TRAIN)"
, " ( (as const (set sl$TRAIN))"
, " true ))"
, "(define-fun compl@@sl$BLK"
, " ( (s1 (set sl$BLK)) )"
, " (set sl$BLK)"
, " ( (_ map not)"
, " s1 ))"
, "(define-fun compl@@sl$LOC"
, " ( (s1 (set sl$LOC)) )"
, " (set sl$LOC)"
, " ( (_ map not)"
, " s1 ))"
, "(define-fun compl@@sl$TRAIN"
, " ( (s1 (set sl$TRAIN)) )"
, " (set sl$TRAIN)"
, " ( (_ map not)"
, " s1 ))"
, "(define-fun elem@@sl$BLK"
, " ( (x sl$BLK)"
, " (s1 (set sl$BLK)) )"
, " Bool"
, " (select s1 x))"
, "(define-fun elem@@sl$TRAIN"
, " ( (x sl$TRAIN)"
, " (s1 (set sl$TRAIN)) )"
, " Bool"
, " (select s1 x))"
, "(define-fun empty-set@@sl$BLK"
, " ()"
, " (set sl$BLK)"
, " ( (as const (set sl$BLK))"
, " false ))"
, "(define-fun empty-set@@sl$LOC"
, " ()"
, " (set sl$LOC)"
, " ( (as const (set sl$LOC))"
, " false ))"
, "(define-fun empty-set@@sl$TRAIN"
, " ()"
, " (set sl$TRAIN)"
, " ( (as const (set sl$TRAIN))"
, " false ))"
, "(define-fun set-diff@@sl$BLK"
, " ( (s1 (set sl$BLK))"
, " (s2 (set sl$BLK)) )"
, " (set sl$BLK)"
, " (intersect s1 ( (_ map not) s2 )))"
, "(define-fun set-diff@@sl$LOC"
, " ( (s1 (set sl$LOC))"
, " (s2 (set sl$LOC)) )"
, " (set sl$LOC)"
, " (intersect s1 ( (_ map not) s2 )))"
, "(define-fun set-diff@@sl$TRAIN"
, " ( (s1 (set sl$TRAIN))"
, " (s2 (set sl$TRAIN)) )"
, " (set sl$TRAIN)"
, " (intersect s1 ( (_ map not) s2 )))"
, "(define-fun st-subset@@sl$BLK"
, " ( (s1 (set sl$BLK))"
, " (s2 (set sl$BLK)) )"
, " Bool"
, " (and (subset s1 s2) (not (= s1 s2))))"
, "(define-fun st-subset@@sl$LOC"
, " ( (s1 (set sl$LOC))"
, " (s2 (set sl$LOC)) )"
, " Bool"
, " (and (subset s1 s2) (not (= s1 s2))))"
, "(define-fun st-subset@@sl$TRAIN"
, " ( (s1 (set sl$TRAIN))"
, " (s2 (set sl$TRAIN)) )"
, " Bool"
, " (and (subset s1 s2) (not (= s1 s2))))"
, "(define-fun sl$BLK"
, " ()"
, " (set sl$BLK)"
, " ( (as const (set sl$BLK))"
, " true ))"
, "(define-fun sl$LOC"
, " ()"
, " (set sl$LOC)"
, " ( (as const (set sl$LOC))"
, " true ))"
, "(define-fun sl$TRAIN"
, " ()"
, " (set sl$TRAIN)"
, " ( (as const (set sl$TRAIN))"
, " true ))"
, "(assert (forall ( (r (set sl$BLK)) )"
, " (! (=> (finite@@sl$BLK r) (<= 0 (card@@sl$BLK r)))"
, " :pattern"
, " ( (<= 0 (card@@sl$BLK r)) ))))"
, "(assert (forall ( (r (set sl$LOC)) )"
, " (! (=> (finite@@sl$LOC r) (<= 0 (card@@sl$LOC r)))"
, " :pattern"
, " ( (<= 0 (card@@sl$LOC r)) ))))"
, "(assert (forall ( (r (set sl$TRAIN)) )"
, " (! (=> (finite@@sl$TRAIN r) (<= 0 (card@@sl$TRAIN r)))"
, " :pattern"
, " ( (<= 0 (card@@sl$TRAIN r)) ))))"
, "(assert (forall ( (r (set sl$BLK)) )"
, " (! (= (= (card@@sl$BLK r) 0) (= r empty-set@@sl$BLK))"
, " :pattern"
, " ( (card@@sl$BLK r) ))))"
, "(assert (forall ( (r (set sl$LOC)) )"
, " (! (= (= (card@@sl$LOC r) 0) (= r empty-set@@sl$LOC))"
, " :pattern"
, " ( (card@@sl$LOC r) ))))"
, "(assert (forall ( (r (set sl$TRAIN)) )"
, " (! (= (= (card@@sl$TRAIN r) 0)"
, " (= r empty-set@@sl$TRAIN))"
, " :pattern"
, " ( (card@@sl$TRAIN r) ))))"
, "(assert (forall ( (x sl$BLK) )"
, " (! (= (card@@sl$BLK (mk-set@@sl$BLK x)) 1)"
, " :pattern"
, " ( (card@@sl$BLK (mk-set@@sl$BLK x)) ))))"
, "(assert (forall ( (x sl$TRAIN) )"
, " (! (= (card@@sl$TRAIN (mk-set@@sl$TRAIN x)) 1)"
, " :pattern"
, " ( (card@@sl$TRAIN (mk-set@@sl$TRAIN x)) ))))"
, "(assert (forall ( (r (set sl$BLK)) )"
, " (! (= (= (card@@sl$BLK r) 1)"
, " (exists ( (x sl$BLK) ) (and true (= r (mk-set@@sl$BLK x)))))"
, " :pattern"
, " ( (card@@sl$BLK r) ))))"
, "(assert (forall ( (r (set sl$TRAIN)) )"
, " (! (= (= (card@@sl$TRAIN r) 1)"
, " (exists ( (x sl$TRAIN) )"
, " (and true (= r (mk-set@@sl$TRAIN x)))))"
, " :pattern"
, " ( (card@@sl$TRAIN r) ))))"
, "(assert (forall ( (r (set sl$BLK))"
, " (r0 (set sl$BLK)) )"
, " (! (=> (= (intersect r r0) empty-set@@sl$BLK)"
, " (= (card@@sl$BLK (union r r0))"
, " (+ (card@@sl$BLK r) (card@@sl$BLK r0))))"
, " :pattern"
, " ( (card@@sl$BLK (union r r0)) ))))"
, "(assert (forall ( (r (set sl$LOC))"
, " (r0 (set sl$LOC)) )"
, " (! (=> (= (intersect r r0) empty-set@@sl$LOC)"
, " (= (card@@sl$LOC (union r r0))"
, " (+ (card@@sl$LOC r) (card@@sl$LOC r0))))"
, " :pattern"
, " ( (card@@sl$LOC (union r r0)) ))))"
, "(assert (forall ( (r (set sl$TRAIN))"
, " (r0 (set sl$TRAIN)) )"
, " (! (=> (= (intersect r r0) empty-set@@sl$TRAIN)"
, " (= (card@@sl$TRAIN (union r r0))"
, " (+ (card@@sl$TRAIN r) (card@@sl$TRAIN r0))))"
, " :pattern"
, " ( (card@@sl$TRAIN (union r r0)) ))))"
, "(assert (= (dom@@sl$TRAIN@@sl$BLK empty-fun@@sl$TRAIN@@sl$BLK)"
, " empty-set@@sl$TRAIN))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK)) )"
, " (! (= (ovl@@sl$TRAIN@@sl$BLK f1 empty-fun@@sl$TRAIN@@sl$BLK)"
, " f1)"
, " :pattern"
, " ( (ovl@@sl$TRAIN@@sl$BLK f1 empty-fun@@sl$TRAIN@@sl$BLK) ))))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK)) )"
, " (! (= (ovl@@sl$TRAIN@@sl$BLK empty-fun@@sl$TRAIN@@sl$BLK f1)"
, " f1)"
, " :pattern"
, " ( (ovl@@sl$TRAIN@@sl$BLK empty-fun@@sl$TRAIN@@sl$BLK f1) ))))"
, "(assert (forall ( (x sl$TRAIN)"
, " (y sl$BLK) )"
, " (! (= (dom@@sl$TRAIN@@sl$BLK (mk-fun@@sl$TRAIN@@sl$BLK x y))"
, " (mk-set@@sl$TRAIN x))"
, " :pattern"
, " ( (dom@@sl$TRAIN@@sl$BLK (mk-fun@@sl$TRAIN@@sl$BLK x y)) ))))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK))"
, " (f2 (pfun sl$TRAIN sl$BLK))"
, " (x sl$TRAIN) )"
, " (! (=> (elem@@sl$TRAIN x (dom@@sl$TRAIN@@sl$BLK f2))"
, " (= (apply@@sl$TRAIN@@sl$BLK (ovl@@sl$TRAIN@@sl$BLK f1 f2) x)"
, " (apply@@sl$TRAIN@@sl$BLK f2 x)))"
, " :pattern"
, " ( (apply@@sl$TRAIN@@sl$BLK (ovl@@sl$TRAIN@@sl$BLK f1 f2) x) ))))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK))"
, " (f2 (pfun sl$TRAIN sl$BLK))"
, " (x sl$TRAIN) )"
, " (! (=> (and (elem@@sl$TRAIN x (dom@@sl$TRAIN@@sl$BLK f1))"
, " (not (elem@@sl$TRAIN x (dom@@sl$TRAIN@@sl$BLK f2))))"
, " (= (apply@@sl$TRAIN@@sl$BLK (ovl@@sl$TRAIN@@sl$BLK f1 f2) x)"
, " (apply@@sl$TRAIN@@sl$BLK f1 x)))"
, " :pattern"
, " ( (apply@@sl$TRAIN@@sl$BLK (ovl@@sl$TRAIN@@sl$BLK f1 f2) x) ))))"
, "(assert (forall ( (x sl$TRAIN)"
, " (y sl$BLK) )"
, " (! (= (apply@@sl$TRAIN@@sl$BLK (mk-fun@@sl$TRAIN@@sl$BLK x y) x)"
, " y)"
, " :pattern"
, " ( (apply@@sl$TRAIN@@sl$BLK (mk-fun@@sl$TRAIN@@sl$BLK x y) x) ))))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK))"
, " (s1 (set sl$TRAIN))"
, " (x sl$TRAIN) )"
, " (! (=> (and (elem@@sl$TRAIN x s1)"
, " (elem@@sl$TRAIN x (dom@@sl$TRAIN@@sl$BLK f1)))"
, " (= (apply@@sl$TRAIN@@sl$BLK (dom-rest@@sl$TRAIN@@sl$BLK s1 f1) x)"
, " (apply@@sl$TRAIN@@sl$BLK f1 x)))"
, " :pattern"
, " ( (apply@@sl$TRAIN@@sl$BLK (dom-rest@@sl$TRAIN@@sl$BLK s1 f1) x) ))))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK))"
, " (s1 (set sl$TRAIN))"
, " (x sl$TRAIN) )"
, " (! (=> (elem@@sl$TRAIN x"
, " (set-diff@@sl$TRAIN (dom@@sl$TRAIN@@sl$BLK f1) s1))"
, " (= (apply@@sl$TRAIN@@sl$BLK (dom-subt@@sl$TRAIN@@sl$BLK s1 f1) x)"
, " (apply@@sl$TRAIN@@sl$BLK f1 x)))"
, " :pattern"
, " ( (apply@@sl$TRAIN@@sl$BLK (dom-subt@@sl$TRAIN@@sl$BLK s1 f1) x) ))))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK))"
, " (f2 (pfun sl$TRAIN sl$BLK)) )"
, " (! (= (dom@@sl$TRAIN@@sl$BLK (ovl@@sl$TRAIN@@sl$BLK f1 f2))"
, " (union (dom@@sl$TRAIN@@sl$BLK f1)"
, " (dom@@sl$TRAIN@@sl$BLK f2)))"
, " :pattern"
, " ( (dom@@sl$TRAIN@@sl$BLK (ovl@@sl$TRAIN@@sl$BLK f1 f2)) ))))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK))"
, " (s1 (set sl$TRAIN)) )"
, " (! (= (dom@@sl$TRAIN@@sl$BLK (dom-rest@@sl$TRAIN@@sl$BLK s1 f1))"
, " (intersect s1 (dom@@sl$TRAIN@@sl$BLK f1)))"
, " :pattern"
, " ( (dom@@sl$TRAIN@@sl$BLK (dom-rest@@sl$TRAIN@@sl$BLK s1 f1)) ))))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK))"
, " (s1 (set sl$TRAIN)) )"
, " (! (= (dom@@sl$TRAIN@@sl$BLK (dom-subt@@sl$TRAIN@@sl$BLK s1 f1))"
, " (set-diff@@sl$TRAIN (dom@@sl$TRAIN@@sl$BLK f1) s1))"
, " :pattern"
, " ( (dom@@sl$TRAIN@@sl$BLK (dom-subt@@sl$TRAIN@@sl$BLK s1 f1)) ))))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK))"
, " (x sl$TRAIN)"
, " (y sl$BLK) )"
, " (! (= (and (elem@@sl$TRAIN x (dom@@sl$TRAIN@@sl$BLK f1))"
, " (= (apply@@sl$TRAIN@@sl$BLK f1 x) y))"
, " (= (select f1 x) (Just y)))"
, " :pattern"
, " ( (elem@@sl$TRAIN x (dom@@sl$TRAIN@@sl$BLK f1))"
, " (apply@@sl$TRAIN@@sl$BLK f1 x)"
, " (select f1 x)"
, " (Just y) ))))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK))"
, " (x sl$TRAIN)"
, " (x2 sl$TRAIN)"
, " (y sl$BLK) )"
, " (! (=> (not (= x x2))"
, " (= (apply@@sl$TRAIN@@sl$BLK (ovl@@sl$TRAIN@@sl$BLK f1 (mk-fun@@sl$TRAIN@@sl$BLK x y))"
, " x2)"
, " (apply@@sl$TRAIN@@sl$BLK f1 x2)))"
, " :pattern"
, " ( (apply@@sl$TRAIN@@sl$BLK (ovl@@sl$TRAIN@@sl$BLK f1 (mk-fun@@sl$TRAIN@@sl$BLK x y))"
, " x2) ))))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK))"
, " (x sl$TRAIN)"
, " (y sl$BLK) )"
, " (! (= (apply@@sl$TRAIN@@sl$BLK (ovl@@sl$TRAIN@@sl$BLK f1 (mk-fun@@sl$TRAIN@@sl$BLK x y))"
, " x)"
, " y)"
, " :pattern"
, " ( (apply@@sl$TRAIN@@sl$BLK (ovl@@sl$TRAIN@@sl$BLK f1 (mk-fun@@sl$TRAIN@@sl$BLK x y))"
, " x) ))))"
, "(assert (= (ran@@sl$TRAIN@@sl$BLK empty-fun@@sl$TRAIN@@sl$BLK)"
, " empty-set@@sl$BLK))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK))"
, " (y sl$BLK) )"
, " (! (= (elem@@sl$BLK y (ran@@sl$TRAIN@@sl$BLK f1))"
, " (exists ( (x sl$TRAIN) )"
, " (and true"
, " (and (elem@@sl$TRAIN x (dom@@sl$TRAIN@@sl$BLK f1))"
, " (= (apply@@sl$TRAIN@@sl$BLK f1 x) y)))))"
, " :pattern"
, " ( (elem@@sl$BLK y (ran@@sl$TRAIN@@sl$BLK f1)) ))))"
, "(assert (forall ( (x sl$TRAIN)"
, " (y sl$BLK) )"
, " (! (= (ran@@sl$TRAIN@@sl$BLK (mk-fun@@sl$TRAIN@@sl$BLK x y))"
, " (mk-set@@sl$BLK y))"
, " :pattern"
, " ( (ran@@sl$TRAIN@@sl$BLK (mk-fun@@sl$TRAIN@@sl$BLK x y)) ))))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK)) )"
, " (! (= (injective@@sl$TRAIN@@sl$BLK f1)"
, " (forall ( (x sl$TRAIN)"
, " (x2 sl$TRAIN) )"
, " (=> (and (elem@@sl$TRAIN x (dom@@sl$TRAIN@@sl$BLK f1))"
, " (elem@@sl$TRAIN x2 (dom@@sl$TRAIN@@sl$BLK f1)))"
, " (=> (= (apply@@sl$TRAIN@@sl$BLK f1 x)"
, " (apply@@sl$TRAIN@@sl$BLK f1 x2))"
, " (= x x2)))))"
, " :pattern"
, " ( (injective@@sl$TRAIN@@sl$BLK f1) ))))"
, "(assert (injective@@sl$TRAIN@@sl$BLK empty-fun@@sl$TRAIN@@sl$BLK))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK))"
, " (x sl$TRAIN) )"
, " (! (=> (elem@@sl$TRAIN x (dom@@sl$TRAIN@@sl$BLK f1))"
, " (elem@@sl$BLK (apply@@sl$TRAIN@@sl$BLK f1 x)"
, " (ran@@sl$TRAIN@@sl$BLK f1)))"
, " :pattern"
, " ( (elem@@sl$BLK (apply@@sl$TRAIN@@sl$BLK f1 x)"
, " (ran@@sl$TRAIN@@sl$BLK f1)) ))))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK))"
, " (s1 (set sl$TRAIN))"
, " (x sl$TRAIN) )"
, " (! (=> (elem@@sl$TRAIN x"
, " (set-diff@@sl$TRAIN (dom@@sl$TRAIN@@sl$BLK f1) s1))"
, " (elem@@sl$BLK (apply@@sl$TRAIN@@sl$BLK f1 x)"
, " (ran@@sl$TRAIN@@sl$BLK (dom-subt@@sl$TRAIN@@sl$BLK s1 f1))))"
, " :pattern"
, " ( (elem@@sl$BLK (apply@@sl$TRAIN@@sl$BLK f1 x)"
, " (ran@@sl$TRAIN@@sl$BLK (dom-subt@@sl$TRAIN@@sl$BLK s1 f1))) ))))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK))"
, " (s1 (set sl$TRAIN))"
, " (x sl$TRAIN) )"
, " (! (=> (elem@@sl$TRAIN x (intersect (dom@@sl$TRAIN@@sl$BLK f1) s1))"
, " (elem@@sl$BLK (apply@@sl$TRAIN@@sl$BLK f1 x)"
, " (ran@@sl$TRAIN@@sl$BLK (dom-rest@@sl$TRAIN@@sl$BLK s1 f1))))"
, " :pattern"
, " ( (elem@@sl$BLK (apply@@sl$TRAIN@@sl$BLK f1 x)"
, " (ran@@sl$TRAIN@@sl$BLK (dom-rest@@sl$TRAIN@@sl$BLK s1 f1))) ))))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK))"
, " (x sl$TRAIN)"
, " (y sl$BLK) )"
, " (! (=> (and (elem@@sl$TRAIN x (dom@@sl$TRAIN@@sl$BLK f1))"
, " (injective@@sl$TRAIN@@sl$BLK f1))"
, " (= (ran@@sl$TRAIN@@sl$BLK (ovl@@sl$TRAIN@@sl$BLK f1 (mk-fun@@sl$TRAIN@@sl$BLK x y)))"
, " (union (set-diff@@sl$BLK (ran@@sl$TRAIN@@sl$BLK f1)"
, " (mk-set@@sl$BLK (apply@@sl$TRAIN@@sl$BLK f1 x)))"
, " (mk-set@@sl$BLK y))))"
, " :pattern"
, " ( (ran@@sl$TRAIN@@sl$BLK (ovl@@sl$TRAIN@@sl$BLK f1 (mk-fun@@sl$TRAIN@@sl$BLK x y))) ))))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK))"
, " (x sl$TRAIN)"
, " (y sl$BLK) )"
, " (! (=> (not (elem@@sl$TRAIN x (dom@@sl$TRAIN@@sl$BLK f1)))"
, " (= (ran@@sl$TRAIN@@sl$BLK (ovl@@sl$TRAIN@@sl$BLK f1 (mk-fun@@sl$TRAIN@@sl$BLK x y)))"
, " (union (ran@@sl$TRAIN@@sl$BLK f1) (mk-set@@sl$BLK y))))"
, " :pattern"
, " ( (ran@@sl$TRAIN@@sl$BLK (ovl@@sl$TRAIN@@sl$BLK f1 (mk-fun@@sl$TRAIN@@sl$BLK x y))) ))))"
, "(assert (forall ( (x sl$BLK)"
, " (y sl$BLK) )"
, " (! (= (elem@@sl$BLK x (mk-set@@sl$BLK y)) (= x y))"
, " :pattern"
, " ( (elem@@sl$BLK x (mk-set@@sl$BLK y)) ))))"
, "(assert (forall ( (x sl$TRAIN)"
, " (y sl$TRAIN) )"
, " (! (= (elem@@sl$TRAIN x (mk-set@@sl$TRAIN y)) (= x y))"
, " :pattern"
, " ( (elem@@sl$TRAIN x (mk-set@@sl$TRAIN y)) ))))"
, "(assert (forall ( (s1 (set sl$BLK))"
, " (s2 (set sl$BLK)) )"
, " (! (=> (finite@@sl$BLK s1)"
, " (finite@@sl$BLK (set-diff@@sl$BLK s1 s2)))"
, " :pattern"
, " ( (finite@@sl$BLK (set-diff@@sl$BLK s1 s2)) ))))"
, "(assert (forall ( (s1 (set sl$LOC))"
, " (s2 (set sl$LOC)) )"
, " (! (=> (finite@@sl$LOC s1)"
, " (finite@@sl$LOC (set-diff@@sl$LOC s1 s2)))"
, " :pattern"
, " ( (finite@@sl$LOC (set-diff@@sl$LOC s1 s2)) ))))"
, "(assert (forall ( (s1 (set sl$TRAIN))"
, " (s2 (set sl$TRAIN)) )"
, " (! (=> (finite@@sl$TRAIN s1)"
, " (finite@@sl$TRAIN (set-diff@@sl$TRAIN s1 s2)))"
, " :pattern"
, " ( (finite@@sl$TRAIN (set-diff@@sl$TRAIN s1 s2)) ))))"
, "(assert (forall ( (s1 (set sl$BLK))"
, " (s2 (set sl$BLK)) )"
, " (! (=> (and (finite@@sl$BLK s1) (finite@@sl$BLK s2))"
, " (finite@@sl$BLK (union s1 s2)))"
, " :pattern"
, " ( (finite@@sl$BLK (union s1 s2)) ))))"
, "(assert (forall ( (s1 (set sl$LOC))"
, " (s2 (set sl$LOC)) )"
, " (! (=> (and (finite@@sl$LOC s1) (finite@@sl$LOC s2))"
, " (finite@@sl$LOC (union s1 s2)))"
, " :pattern"
, " ( (finite@@sl$LOC (union s1 s2)) ))))"
, "(assert (forall ( (s1 (set sl$TRAIN))"
, " (s2 (set sl$TRAIN)) )"
, " (! (=> (and (finite@@sl$TRAIN s1) (finite@@sl$TRAIN s2))"
, " (finite@@sl$TRAIN (union s1 s2)))"
, " :pattern"
, " ( (finite@@sl$TRAIN (union s1 s2)) ))))"
, "(assert (forall ( (s1 (set sl$BLK))"
, " (s2 (set sl$BLK)) )"
, " (! (=> (and (finite@@sl$BLK s2) (not (finite@@sl$BLK s1)))"
, " (not (finite@@sl$BLK (set-diff@@sl$BLK s1 s2))))"
, " :pattern"
, " ( (finite@@sl$BLK (set-diff@@sl$BLK s1 s2)) ))))"
, "(assert (forall ( (s1 (set sl$LOC))"
, " (s2 (set sl$LOC)) )"
, " (! (=> (and (finite@@sl$LOC s2) (not (finite@@sl$LOC s1)))"
, " (not (finite@@sl$LOC (set-diff@@sl$LOC s1 s2))))"
, " :pattern"
, " ( (finite@@sl$LOC (set-diff@@sl$LOC s1 s2)) ))))"
, "(assert (forall ( (s1 (set sl$TRAIN))"
, " (s2 (set sl$TRAIN)) )"
, " (! (=> (and (finite@@sl$TRAIN s2) (not (finite@@sl$TRAIN s1)))"
, " (not (finite@@sl$TRAIN (set-diff@@sl$TRAIN s1 s2))))"
, " :pattern"
, " ( (finite@@sl$TRAIN (set-diff@@sl$TRAIN s1 s2)) ))))"
, "(assert (forall ( (x sl$BLK) )"
, " (! (finite@@sl$BLK (mk-set@@sl$BLK x))"
, " :pattern"
, " ( (finite@@sl$BLK (mk-set@@sl$BLK x)) ))))"
, "(assert (forall ( (x sl$TRAIN) )"
, " (! (finite@@sl$TRAIN (mk-set@@sl$TRAIN x))"
, " :pattern"
, " ( (finite@@sl$TRAIN (mk-set@@sl$TRAIN x)) ))))"
, "(assert (finite@@sl$BLK empty-set@@sl$BLK))"
, "(assert (finite@@sl$LOC empty-set@@sl$LOC))"
, "(assert (finite@@sl$TRAIN empty-set@@sl$TRAIN))"
, "(assert (not (exists ( (loc@prime (pfun sl$TRAIN sl$BLK)) )"
, " (and true"
, " (= loc@prime"
, " (dom-subt@@sl$TRAIN@@sl$BLK (mk-set@@sl$TRAIN t) loc))))))"
, "; asm2"
, "(assert (and (not (= ent ext))"
, " (not (elem@@sl$BLK ent PLF))"
, " (not (elem@@sl$BLK ext PLF))))"
, "; asm3"
, "(assert (forall ( (p sl$BLK) )"
, " (! (= (not (= p ext))"
, " (elem@@sl$BLK p (union (mk-set@@sl$BLK ent) PLF)))"
, " :pattern"
, " ( (elem@@sl$BLK p (union (mk-set@@sl$BLK ent) PLF)) ))))"
, "; asm4"
, "(assert (forall ( (p sl$BLK) )"
, " (! (= (not (= p ent))"
, " (elem@@sl$BLK p (union (mk-set@@sl$BLK ext) PLF)))"
, " :pattern"
, " ( (elem@@sl$BLK p (union (mk-set@@sl$BLK ext) PLF)) ))))"
, "; asm5"
, "(assert (forall ( (p sl$BLK) )"
, " (! (= (or (= p ent) (= p ext))"
, " (not (elem@@sl$BLK p PLF)))"
, " :pattern"
, " ( (elem@@sl$BLK p PLF) ))))"
, "; axm0"
, "(assert (= sl$BLK"
, " (union (union (mk-set@@sl$BLK ent) (mk-set@@sl$BLK ext))"
, " PLF)))"
, "; c0"
, "(assert (elem@@sl$TRAIN t in))"
, "; grd0"
, "(assert (and (= (apply@@sl$TRAIN@@sl$BLK loc t) ext)"
, " (elem@@sl$TRAIN t in)))"
, "; inv1"
, "(assert (forall ( (t sl$TRAIN) )"
, " (! (=> (elem@@sl$TRAIN t in)"
, " (elem@@sl$BLK (apply@@sl$TRAIN@@sl$BLK loc t) sl$BLK))"
, " :pattern"
, " ( (elem@@sl$BLK (apply@@sl$TRAIN@@sl$BLK loc t) sl$BLK) ))))"
, "; inv2"
, "(assert (= (dom@@sl$TRAIN@@sl$BLK loc) in))"
, "(assert (not true))"
, "(check-sat-using (or-else (then qe smt)"
, " (then simplify smt)"
, " (then skip smt)"
, " (then (using-params simplify :expand-power true) smt)))"
, "; train0/leave/FIS/loc@prime"
]
case19 :: IO String
case19 = proof_obligation path0 "train0/leave/FIS/loc@prime" 0
result4 :: String
result4 = unlines
[ "; train0/leave/SCH/grd0"
, "(set-option :auto-config false)"
, "(set-option :smt.timeout 3000)"
, "(declare-datatypes (a) ( (Maybe (Just (fromJust a)) Nothing) ))"
, "(declare-datatypes () ( (Null null) ))"
, "(declare-datatypes (a b) ( (Pair (pair (first a) (second b))) ))"
, "(define-sort guarded (a) (Maybe a))"
, "(declare-sort sl$BLK 0)"
, "; comment: we don't need to declare the sort Bool"
, "; comment: we don't need to declare the sort Int"
, "(declare-sort sl$LOC 0)"
, "; comment: we don't need to declare the sort Real"
, "(declare-sort sl$TRAIN 0)"
, "(define-sort pfun (a b) (Array a (Maybe b)))"
, "(define-sort set (a) (Array a Bool))"
, "(declare-const PLF (set sl$BLK))"
, "(declare-const ent sl$BLK)"
, "(declare-const ext sl$BLK)"
, "(declare-const in (set sl$TRAIN))"
, "(declare-const loc (pfun sl$TRAIN sl$BLK))"
, "(declare-const t sl$TRAIN)"
, "(declare-fun apply@@sl$TRAIN@@sl$BLK"
, " ( (pfun sl$TRAIN sl$BLK)"
, " sl$TRAIN )"
, " sl$BLK)"
, "(declare-fun card@@sl$BLK ( (set sl$BLK) ) Int)"
, "(declare-fun card@@sl$LOC ( (set sl$LOC) ) Int)"
, "(declare-fun card@@sl$TRAIN ( (set sl$TRAIN) ) Int)"
, "(declare-fun dom@@sl$TRAIN@@sl$BLK"
, " ( (pfun sl$TRAIN sl$BLK) )"
, " (set sl$TRAIN))"
, "(declare-fun dom-rest@@sl$TRAIN@@sl$BLK"
, " ( (set sl$TRAIN)"
, " (pfun sl$TRAIN sl$BLK) )"
, " (pfun sl$TRAIN sl$BLK))"
, "(declare-fun dom-subt@@sl$TRAIN@@sl$BLK"
, " ( (set sl$TRAIN)"
, " (pfun sl$TRAIN sl$BLK) )"
, " (pfun sl$TRAIN sl$BLK))"
, "(declare-fun empty-fun@@sl$TRAIN@@sl$BLK"
, " ()"
, " (pfun sl$TRAIN sl$BLK))"
, "(declare-fun finite@@sl$BLK ( (set sl$BLK) ) Bool)"
, "(declare-fun finite@@sl$LOC ( (set sl$LOC) ) Bool)"
, "(declare-fun finite@@sl$TRAIN ( (set sl$TRAIN) ) Bool)"
, "(declare-fun injective@@sl$TRAIN@@sl$BLK"
, " ( (pfun sl$TRAIN sl$BLK) )"
, " Bool)"
, "(declare-fun mk-fun@@sl$TRAIN@@sl$BLK"
, " (sl$TRAIN sl$BLK)"
, " (pfun sl$TRAIN sl$BLK))"
, "(declare-fun mk-set@@sl$BLK (sl$BLK) (set sl$BLK))"
, "(declare-fun mk-set@@sl$TRAIN (sl$TRAIN) (set sl$TRAIN))"
, "(declare-fun ovl@@sl$TRAIN@@sl$BLK"
, " ( (pfun sl$TRAIN sl$BLK)"
, " (pfun sl$TRAIN sl$BLK) )"
, " (pfun sl$TRAIN sl$BLK))"
, "(declare-fun ran@@sl$TRAIN@@sl$BLK"
, " ( (pfun sl$TRAIN sl$BLK) )"
, " (set sl$BLK))"
, "(define-fun all@@sl$BLK"
, " ()"
, " (set sl$BLK)"
, " ( (as const (set sl$BLK))"
, " true ))"
, "(define-fun all@@sl$LOC"
, " ()"
, " (set sl$LOC)"
, " ( (as const (set sl$LOC))"
, " true ))"
, "(define-fun all@@sl$TRAIN"
, " ()"
, " (set sl$TRAIN)"
, " ( (as const (set sl$TRAIN))"
, " true ))"
, "(define-fun compl@@sl$BLK"
, " ( (s1 (set sl$BLK)) )"
, " (set sl$BLK)"
, " ( (_ map not)"
, " s1 ))"
, "(define-fun compl@@sl$LOC"
, " ( (s1 (set sl$LOC)) )"
, " (set sl$LOC)"
, " ( (_ map not)"
, " s1 ))"
, "(define-fun compl@@sl$TRAIN"
, " ( (s1 (set sl$TRAIN)) )"
, " (set sl$TRAIN)"
, " ( (_ map not)"
, " s1 ))"
, "(define-fun elem@@sl$BLK"
, " ( (x sl$BLK)"
, " (s1 (set sl$BLK)) )"
, " Bool"
, " (select s1 x))"
, "(define-fun elem@@sl$TRAIN"
, " ( (x sl$TRAIN)"
, " (s1 (set sl$TRAIN)) )"
, " Bool"
, " (select s1 x))"
, "(define-fun empty-set@@sl$BLK"
, " ()"
, " (set sl$BLK)"
, " ( (as const (set sl$BLK))"
, " false ))"
, "(define-fun empty-set@@sl$LOC"
, " ()"
, " (set sl$LOC)"
, " ( (as const (set sl$LOC))"
, " false ))"
, "(define-fun empty-set@@sl$TRAIN"
, " ()"
, " (set sl$TRAIN)"
, " ( (as const (set sl$TRAIN))"
, " false ))"
, "(define-fun set-diff@@sl$BLK"
, " ( (s1 (set sl$BLK))"
, " (s2 (set sl$BLK)) )"
, " (set sl$BLK)"
, " (intersect s1 ( (_ map not) s2 )))"
, "(define-fun set-diff@@sl$LOC"
, " ( (s1 (set sl$LOC))"
, " (s2 (set sl$LOC)) )"
, " (set sl$LOC)"
, " (intersect s1 ( (_ map not) s2 )))"
, "(define-fun set-diff@@sl$TRAIN"
, " ( (s1 (set sl$TRAIN))"
, " (s2 (set sl$TRAIN)) )"
, " (set sl$TRAIN)"
, " (intersect s1 ( (_ map not) s2 )))"
, "(define-fun st-subset@@sl$BLK"
, " ( (s1 (set sl$BLK))"
, " (s2 (set sl$BLK)) )"
, " Bool"
, " (and (subset s1 s2) (not (= s1 s2))))"
, "(define-fun st-subset@@sl$LOC"
, " ( (s1 (set sl$LOC))"
, " (s2 (set sl$LOC)) )"
, " Bool"
, " (and (subset s1 s2) (not (= s1 s2))))"
, "(define-fun st-subset@@sl$TRAIN"
, " ( (s1 (set sl$TRAIN))"
, " (s2 (set sl$TRAIN)) )"
, " Bool"
, " (and (subset s1 s2) (not (= s1 s2))))"
, "(define-fun sl$BLK"
, " ()"
, " (set sl$BLK)"
, " ( (as const (set sl$BLK))"
, " true ))"
, "(define-fun sl$LOC"
, " ()"
, " (set sl$LOC)"
, " ( (as const (set sl$LOC))"
, " true ))"
, "(define-fun sl$TRAIN"
, " ()"
, " (set sl$TRAIN)"
, " ( (as const (set sl$TRAIN))"
, " true ))"
, "(assert (forall ( (r (set sl$BLK)) )"
, " (! (=> (finite@@sl$BLK r) (<= 0 (card@@sl$BLK r)))"
, " :pattern"
, " ( (<= 0 (card@@sl$BLK r)) ))))"
, "(assert (forall ( (r (set sl$LOC)) )"
, " (! (=> (finite@@sl$LOC r) (<= 0 (card@@sl$LOC r)))"
, " :pattern"
, " ( (<= 0 (card@@sl$LOC r)) ))))"
, "(assert (forall ( (r (set sl$TRAIN)) )"
, " (! (=> (finite@@sl$TRAIN r) (<= 0 (card@@sl$TRAIN r)))"
, " :pattern"
, " ( (<= 0 (card@@sl$TRAIN r)) ))))"
, "(assert (forall ( (r (set sl$BLK)) )"
, " (! (= (= (card@@sl$BLK r) 0) (= r empty-set@@sl$BLK))"
, " :pattern"
, " ( (card@@sl$BLK r) ))))"
, "(assert (forall ( (r (set sl$LOC)) )"
, " (! (= (= (card@@sl$LOC r) 0) (= r empty-set@@sl$LOC))"
, " :pattern"
, " ( (card@@sl$LOC r) ))))"
, "(assert (forall ( (r (set sl$TRAIN)) )"
, " (! (= (= (card@@sl$TRAIN r) 0)"
, " (= r empty-set@@sl$TRAIN))"
, " :pattern"
, " ( (card@@sl$TRAIN r) ))))"
, "(assert (forall ( (x sl$BLK) )"
, " (! (= (card@@sl$BLK (mk-set@@sl$BLK x)) 1)"
, " :pattern"
, " ( (card@@sl$BLK (mk-set@@sl$BLK x)) ))))"
, "(assert (forall ( (x sl$TRAIN) )"
, " (! (= (card@@sl$TRAIN (mk-set@@sl$TRAIN x)) 1)"
, " :pattern"
, " ( (card@@sl$TRAIN (mk-set@@sl$TRAIN x)) ))))"
, "(assert (forall ( (r (set sl$BLK)) )"
, " (! (= (= (card@@sl$BLK r) 1)"
, " (exists ( (x sl$BLK) ) (and true (= r (mk-set@@sl$BLK x)))))"
, " :pattern"
, " ( (card@@sl$BLK r) ))))"
, "(assert (forall ( (r (set sl$TRAIN)) )"
, " (! (= (= (card@@sl$TRAIN r) 1)"
, " (exists ( (x sl$TRAIN) )"
, " (and true (= r (mk-set@@sl$TRAIN x)))))"
, " :pattern"
, " ( (card@@sl$TRAIN r) ))))"
, "(assert (forall ( (r (set sl$BLK))"
, " (r0 (set sl$BLK)) )"
, " (! (=> (= (intersect r r0) empty-set@@sl$BLK)"
, " (= (card@@sl$BLK (union r r0))"
, " (+ (card@@sl$BLK r) (card@@sl$BLK r0))))"
, " :pattern"
, " ( (card@@sl$BLK (union r r0)) ))))"
, "(assert (forall ( (r (set sl$LOC))"
, " (r0 (set sl$LOC)) )"
, " (! (=> (= (intersect r r0) empty-set@@sl$LOC)"
, " (= (card@@sl$LOC (union r r0))"
, " (+ (card@@sl$LOC r) (card@@sl$LOC r0))))"
, " :pattern"
, " ( (card@@sl$LOC (union r r0)) ))))"
, "(assert (forall ( (r (set sl$TRAIN))"
, " (r0 (set sl$TRAIN)) )"
, " (! (=> (= (intersect r r0) empty-set@@sl$TRAIN)"
, " (= (card@@sl$TRAIN (union r r0))"
, " (+ (card@@sl$TRAIN r) (card@@sl$TRAIN r0))))"
, " :pattern"
, " ( (card@@sl$TRAIN (union r r0)) ))))"
, "(assert (= (dom@@sl$TRAIN@@sl$BLK empty-fun@@sl$TRAIN@@sl$BLK)"
, " empty-set@@sl$TRAIN))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK)) )"
, " (! (= (ovl@@sl$TRAIN@@sl$BLK f1 empty-fun@@sl$TRAIN@@sl$BLK)"
, " f1)"
, " :pattern"
, " ( (ovl@@sl$TRAIN@@sl$BLK f1 empty-fun@@sl$TRAIN@@sl$BLK) ))))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK)) )"
, " (! (= (ovl@@sl$TRAIN@@sl$BLK empty-fun@@sl$TRAIN@@sl$BLK f1)"
, " f1)"
, " :pattern"
, " ( (ovl@@sl$TRAIN@@sl$BLK empty-fun@@sl$TRAIN@@sl$BLK f1) ))))"
, "(assert (forall ( (x sl$TRAIN)"
, " (y sl$BLK) )"
, " (! (= (dom@@sl$TRAIN@@sl$BLK (mk-fun@@sl$TRAIN@@sl$BLK x y))"
, " (mk-set@@sl$TRAIN x))"
, " :pattern"
, " ( (dom@@sl$TRAIN@@sl$BLK (mk-fun@@sl$TRAIN@@sl$BLK x y)) ))))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK))"
, " (f2 (pfun sl$TRAIN sl$BLK))"
, " (x sl$TRAIN) )"
, " (! (=> (elem@@sl$TRAIN x (dom@@sl$TRAIN@@sl$BLK f2))"
, " (= (apply@@sl$TRAIN@@sl$BLK (ovl@@sl$TRAIN@@sl$BLK f1 f2) x)"
, " (apply@@sl$TRAIN@@sl$BLK f2 x)))"
, " :pattern"
, " ( (apply@@sl$TRAIN@@sl$BLK (ovl@@sl$TRAIN@@sl$BLK f1 f2) x) ))))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK))"
, " (f2 (pfun sl$TRAIN sl$BLK))"
, " (x sl$TRAIN) )"
, " (! (=> (and (elem@@sl$TRAIN x (dom@@sl$TRAIN@@sl$BLK f1))"
, " (not (elem@@sl$TRAIN x (dom@@sl$TRAIN@@sl$BLK f2))))"
, " (= (apply@@sl$TRAIN@@sl$BLK (ovl@@sl$TRAIN@@sl$BLK f1 f2) x)"
, " (apply@@sl$TRAIN@@sl$BLK f1 x)))"
, " :pattern"
, " ( (apply@@sl$TRAIN@@sl$BLK (ovl@@sl$TRAIN@@sl$BLK f1 f2) x) ))))"
, "(assert (forall ( (x sl$TRAIN)"
, " (y sl$BLK) )"
, " (! (= (apply@@sl$TRAIN@@sl$BLK (mk-fun@@sl$TRAIN@@sl$BLK x y) x)"
, " y)"
, " :pattern"
, " ( (apply@@sl$TRAIN@@sl$BLK (mk-fun@@sl$TRAIN@@sl$BLK x y) x) ))))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK))"
, " (s1 (set sl$TRAIN))"
, " (x sl$TRAIN) )"
, " (! (=> (and (elem@@sl$TRAIN x s1)"
, " (elem@@sl$TRAIN x (dom@@sl$TRAIN@@sl$BLK f1)))"
, " (= (apply@@sl$TRAIN@@sl$BLK (dom-rest@@sl$TRAIN@@sl$BLK s1 f1) x)"
, " (apply@@sl$TRAIN@@sl$BLK f1 x)))"
, " :pattern"
, " ( (apply@@sl$TRAIN@@sl$BLK (dom-rest@@sl$TRAIN@@sl$BLK s1 f1) x) ))))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK))"
, " (s1 (set sl$TRAIN))"
, " (x sl$TRAIN) )"
, " (! (=> (elem@@sl$TRAIN x"
, " (set-diff@@sl$TRAIN (dom@@sl$TRAIN@@sl$BLK f1) s1))"
, " (= (apply@@sl$TRAIN@@sl$BLK (dom-subt@@sl$TRAIN@@sl$BLK s1 f1) x)"
, " (apply@@sl$TRAIN@@sl$BLK f1 x)))"
, " :pattern"
, " ( (apply@@sl$TRAIN@@sl$BLK (dom-subt@@sl$TRAIN@@sl$BLK s1 f1) x) ))))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK))"
, " (f2 (pfun sl$TRAIN sl$BLK)) )"
, " (! (= (dom@@sl$TRAIN@@sl$BLK (ovl@@sl$TRAIN@@sl$BLK f1 f2))"
, " (union (dom@@sl$TRAIN@@sl$BLK f1)"
, " (dom@@sl$TRAIN@@sl$BLK f2)))"
, " :pattern"
, " ( (dom@@sl$TRAIN@@sl$BLK (ovl@@sl$TRAIN@@sl$BLK f1 f2)) ))))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK))"
, " (s1 (set sl$TRAIN)) )"
, " (! (= (dom@@sl$TRAIN@@sl$BLK (dom-rest@@sl$TRAIN@@sl$BLK s1 f1))"
, " (intersect s1 (dom@@sl$TRAIN@@sl$BLK f1)))"
, " :pattern"
, " ( (dom@@sl$TRAIN@@sl$BLK (dom-rest@@sl$TRAIN@@sl$BLK s1 f1)) ))))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK))"
, " (s1 (set sl$TRAIN)) )"
, " (! (= (dom@@sl$TRAIN@@sl$BLK (dom-subt@@sl$TRAIN@@sl$BLK s1 f1))"
, " (set-diff@@sl$TRAIN (dom@@sl$TRAIN@@sl$BLK f1) s1))"
, " :pattern"
, " ( (dom@@sl$TRAIN@@sl$BLK (dom-subt@@sl$TRAIN@@sl$BLK s1 f1)) ))))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK))"
, " (x sl$TRAIN)"
, " (y sl$BLK) )"
, " (! (= (and (elem@@sl$TRAIN x (dom@@sl$TRAIN@@sl$BLK f1))"
, " (= (apply@@sl$TRAIN@@sl$BLK f1 x) y))"
, " (= (select f1 x) (Just y)))"
, " :pattern"
, " ( (elem@@sl$TRAIN x (dom@@sl$TRAIN@@sl$BLK f1))"
, " (apply@@sl$TRAIN@@sl$BLK f1 x)"
, " (select f1 x)"
, " (Just y) ))))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK))"
, " (x sl$TRAIN)"
, " (x2 sl$TRAIN)"
, " (y sl$BLK) )"
, " (! (=> (not (= x x2))"
, " (= (apply@@sl$TRAIN@@sl$BLK (ovl@@sl$TRAIN@@sl$BLK f1 (mk-fun@@sl$TRAIN@@sl$BLK x y))"
, " x2)"
, " (apply@@sl$TRAIN@@sl$BLK f1 x2)))"
, " :pattern"
, " ( (apply@@sl$TRAIN@@sl$BLK (ovl@@sl$TRAIN@@sl$BLK f1 (mk-fun@@sl$TRAIN@@sl$BLK x y))"
, " x2) ))))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK))"
, " (x sl$TRAIN)"
, " (y sl$BLK) )"
, " (! (= (apply@@sl$TRAIN@@sl$BLK (ovl@@sl$TRAIN@@sl$BLK f1 (mk-fun@@sl$TRAIN@@sl$BLK x y))"
, " x)"
, " y)"
, " :pattern"
, " ( (apply@@sl$TRAIN@@sl$BLK (ovl@@sl$TRAIN@@sl$BLK f1 (mk-fun@@sl$TRAIN@@sl$BLK x y))"
, " x) ))))"
, "(assert (= (ran@@sl$TRAIN@@sl$BLK empty-fun@@sl$TRAIN@@sl$BLK)"
, " empty-set@@sl$BLK))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK))"
, " (y sl$BLK) )"
, " (! (= (elem@@sl$BLK y (ran@@sl$TRAIN@@sl$BLK f1))"
, " (exists ( (x sl$TRAIN) )"
, " (and true"
, " (and (elem@@sl$TRAIN x (dom@@sl$TRAIN@@sl$BLK f1))"
, " (= (apply@@sl$TRAIN@@sl$BLK f1 x) y)))))"
, " :pattern"
, " ( (elem@@sl$BLK y (ran@@sl$TRAIN@@sl$BLK f1)) ))))"
, "(assert (forall ( (x sl$TRAIN)"
, " (y sl$BLK) )"
, " (! (= (ran@@sl$TRAIN@@sl$BLK (mk-fun@@sl$TRAIN@@sl$BLK x y))"
, " (mk-set@@sl$BLK y))"
, " :pattern"
, " ( (ran@@sl$TRAIN@@sl$BLK (mk-fun@@sl$TRAIN@@sl$BLK x y)) ))))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK)) )"
, " (! (= (injective@@sl$TRAIN@@sl$BLK f1)"
, " (forall ( (x sl$TRAIN)"
, " (x2 sl$TRAIN) )"
, " (=> (and (elem@@sl$TRAIN x (dom@@sl$TRAIN@@sl$BLK f1))"
, " (elem@@sl$TRAIN x2 (dom@@sl$TRAIN@@sl$BLK f1)))"
, " (=> (= (apply@@sl$TRAIN@@sl$BLK f1 x)"
, " (apply@@sl$TRAIN@@sl$BLK f1 x2))"
, " (= x x2)))))"
, " :pattern"
, " ( (injective@@sl$TRAIN@@sl$BLK f1) ))))"
, "(assert (injective@@sl$TRAIN@@sl$BLK empty-fun@@sl$TRAIN@@sl$BLK))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK))"
, " (x sl$TRAIN) )"
, " (! (=> (elem@@sl$TRAIN x (dom@@sl$TRAIN@@sl$BLK f1))"
, " (elem@@sl$BLK (apply@@sl$TRAIN@@sl$BLK f1 x)"
, " (ran@@sl$TRAIN@@sl$BLK f1)))"
, " :pattern"
, " ( (elem@@sl$BLK (apply@@sl$TRAIN@@sl$BLK f1 x)"
, " (ran@@sl$TRAIN@@sl$BLK f1)) ))))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK))"
, " (s1 (set sl$TRAIN))"
, " (x sl$TRAIN) )"
, " (! (=> (elem@@sl$TRAIN x"
, " (set-diff@@sl$TRAIN (dom@@sl$TRAIN@@sl$BLK f1) s1))"
, " (elem@@sl$BLK (apply@@sl$TRAIN@@sl$BLK f1 x)"
, " (ran@@sl$TRAIN@@sl$BLK (dom-subt@@sl$TRAIN@@sl$BLK s1 f1))))"
, " :pattern"
, " ( (elem@@sl$BLK (apply@@sl$TRAIN@@sl$BLK f1 x)"
, " (ran@@sl$TRAIN@@sl$BLK (dom-subt@@sl$TRAIN@@sl$BLK s1 f1))) ))))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK))"
, " (s1 (set sl$TRAIN))"
, " (x sl$TRAIN) )"
, " (! (=> (elem@@sl$TRAIN x (intersect (dom@@sl$TRAIN@@sl$BLK f1) s1))"
, " (elem@@sl$BLK (apply@@sl$TRAIN@@sl$BLK f1 x)"
, " (ran@@sl$TRAIN@@sl$BLK (dom-rest@@sl$TRAIN@@sl$BLK s1 f1))))"
, " :pattern"
, " ( (elem@@sl$BLK (apply@@sl$TRAIN@@sl$BLK f1 x)"
, " (ran@@sl$TRAIN@@sl$BLK (dom-rest@@sl$TRAIN@@sl$BLK s1 f1))) ))))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK))"
, " (x sl$TRAIN)"
, " (y sl$BLK) )"
, " (! (=> (and (elem@@sl$TRAIN x (dom@@sl$TRAIN@@sl$BLK f1))"
, " (injective@@sl$TRAIN@@sl$BLK f1))"
, " (= (ran@@sl$TRAIN@@sl$BLK (ovl@@sl$TRAIN@@sl$BLK f1 (mk-fun@@sl$TRAIN@@sl$BLK x y)))"
, " (union (set-diff@@sl$BLK (ran@@sl$TRAIN@@sl$BLK f1)"
, " (mk-set@@sl$BLK (apply@@sl$TRAIN@@sl$BLK f1 x)))"
, " (mk-set@@sl$BLK y))))"
, " :pattern"
, " ( (ran@@sl$TRAIN@@sl$BLK (ovl@@sl$TRAIN@@sl$BLK f1 (mk-fun@@sl$TRAIN@@sl$BLK x y))) ))))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK))"
, " (x sl$TRAIN)"
, " (y sl$BLK) )"
, " (! (=> (not (elem@@sl$TRAIN x (dom@@sl$TRAIN@@sl$BLK f1)))"
, " (= (ran@@sl$TRAIN@@sl$BLK (ovl@@sl$TRAIN@@sl$BLK f1 (mk-fun@@sl$TRAIN@@sl$BLK x y)))"
, " (union (ran@@sl$TRAIN@@sl$BLK f1) (mk-set@@sl$BLK y))))"
, " :pattern"
, " ( (ran@@sl$TRAIN@@sl$BLK (ovl@@sl$TRAIN@@sl$BLK f1 (mk-fun@@sl$TRAIN@@sl$BLK x y))) ))))"
, "(assert (forall ( (x sl$BLK)"
, " (y sl$BLK) )"
, " (! (= (elem@@sl$BLK x (mk-set@@sl$BLK y)) (= x y))"
, " :pattern"
, " ( (elem@@sl$BLK x (mk-set@@sl$BLK y)) ))))"
, "(assert (forall ( (x sl$TRAIN)"
, " (y sl$TRAIN) )"
, " (! (= (elem@@sl$TRAIN x (mk-set@@sl$TRAIN y)) (= x y))"
, " :pattern"
, " ( (elem@@sl$TRAIN x (mk-set@@sl$TRAIN y)) ))))"
, "(assert (forall ( (s1 (set sl$BLK))"
, " (s2 (set sl$BLK)) )"
, " (! (=> (finite@@sl$BLK s1)"
, " (finite@@sl$BLK (set-diff@@sl$BLK s1 s2)))"
, " :pattern"
, " ( (finite@@sl$BLK (set-diff@@sl$BLK s1 s2)) ))))"
, "(assert (forall ( (s1 (set sl$LOC))"
, " (s2 (set sl$LOC)) )"
, " (! (=> (finite@@sl$LOC s1)"
, " (finite@@sl$LOC (set-diff@@sl$LOC s1 s2)))"
, " :pattern"
, " ( (finite@@sl$LOC (set-diff@@sl$LOC s1 s2)) ))))"
, "(assert (forall ( (s1 (set sl$TRAIN))"
, " (s2 (set sl$TRAIN)) )"
, " (! (=> (finite@@sl$TRAIN s1)"
, " (finite@@sl$TRAIN (set-diff@@sl$TRAIN s1 s2)))"
, " :pattern"
, " ( (finite@@sl$TRAIN (set-diff@@sl$TRAIN s1 s2)) ))))"
, "(assert (forall ( (s1 (set sl$BLK))"
, " (s2 (set sl$BLK)) )"
, " (! (=> (and (finite@@sl$BLK s1) (finite@@sl$BLK s2))"
, " (finite@@sl$BLK (union s1 s2)))"
, " :pattern"
, " ( (finite@@sl$BLK (union s1 s2)) ))))"
, "(assert (forall ( (s1 (set sl$LOC))"
, " (s2 (set sl$LOC)) )"
, " (! (=> (and (finite@@sl$LOC s1) (finite@@sl$LOC s2))"
, " (finite@@sl$LOC (union s1 s2)))"
, " :pattern"
, " ( (finite@@sl$LOC (union s1 s2)) ))))"
, "(assert (forall ( (s1 (set sl$TRAIN))"
, " (s2 (set sl$TRAIN)) )"
, " (! (=> (and (finite@@sl$TRAIN s1) (finite@@sl$TRAIN s2))"
, " (finite@@sl$TRAIN (union s1 s2)))"
, " :pattern"
, " ( (finite@@sl$TRAIN (union s1 s2)) ))))"
, "(assert (forall ( (s1 (set sl$BLK))"
, " (s2 (set sl$BLK)) )"
, " (! (=> (and (finite@@sl$BLK s2) (not (finite@@sl$BLK s1)))"
, " (not (finite@@sl$BLK (set-diff@@sl$BLK s1 s2))))"
, " :pattern"
, " ( (finite@@sl$BLK (set-diff@@sl$BLK s1 s2)) ))))"
, "(assert (forall ( (s1 (set sl$LOC))"
, " (s2 (set sl$LOC)) )"
, " (! (=> (and (finite@@sl$LOC s2) (not (finite@@sl$LOC s1)))"
, " (not (finite@@sl$LOC (set-diff@@sl$LOC s1 s2))))"
, " :pattern"
, " ( (finite@@sl$LOC (set-diff@@sl$LOC s1 s2)) ))))"
, "(assert (forall ( (s1 (set sl$TRAIN))"
, " (s2 (set sl$TRAIN)) )"
, " (! (=> (and (finite@@sl$TRAIN s2) (not (finite@@sl$TRAIN s1)))"
, " (not (finite@@sl$TRAIN (set-diff@@sl$TRAIN s1 s2))))"
, " :pattern"
, " ( (finite@@sl$TRAIN (set-diff@@sl$TRAIN s1 s2)) ))))"
, "(assert (forall ( (x sl$BLK) )"
, " (! (finite@@sl$BLK (mk-set@@sl$BLK x))"
, " :pattern"
, " ( (finite@@sl$BLK (mk-set@@sl$BLK x)) ))))"
, "(assert (forall ( (x sl$TRAIN) )"
, " (! (finite@@sl$TRAIN (mk-set@@sl$TRAIN x))"
, " :pattern"
, " ( (finite@@sl$TRAIN (mk-set@@sl$TRAIN x)) ))))"
, "(assert (finite@@sl$BLK empty-set@@sl$BLK))"
, "(assert (finite@@sl$LOC empty-set@@sl$LOC))"
, "(assert (finite@@sl$TRAIN empty-set@@sl$TRAIN))"
, "; asm2"
, "(assert (and (not (= ent ext))"
, " (not (elem@@sl$BLK ent PLF))"
, " (not (elem@@sl$BLK ext PLF))))"
, "; asm3"
, "(assert (forall ( (p sl$BLK) )"
, " (! (= (not (= p ext))"
, " (elem@@sl$BLK p (union (mk-set@@sl$BLK ent) PLF)))"
, " :pattern"
, " ( (elem@@sl$BLK p (union (mk-set@@sl$BLK ent) PLF)) ))))"
, "; asm4"
, "(assert (forall ( (p sl$BLK) )"
, " (! (= (not (= p ent))"
, " (elem@@sl$BLK p (union (mk-set@@sl$BLK ext) PLF)))"
, " :pattern"
, " ( (elem@@sl$BLK p (union (mk-set@@sl$BLK ext) PLF)) ))))"
, "; asm5"
, "(assert (forall ( (p sl$BLK) )"
, " (! (= (or (= p ent) (= p ext))"
, " (not (elem@@sl$BLK p PLF)))"
, " :pattern"
, " ( (elem@@sl$BLK p PLF) ))))"
, "; axm0"
, "(assert (= sl$BLK"
, " (union (union (mk-set@@sl$BLK ent) (mk-set@@sl$BLK ext))"
, " PLF)))"
, "; c0"
, "(assert (elem@@sl$TRAIN t in))"
, "; inv1"
, "(assert (forall ( (t sl$TRAIN) )"
, " (! (=> (elem@@sl$TRAIN t in)"
, " (elem@@sl$BLK (apply@@sl$TRAIN@@sl$BLK loc t) sl$BLK))"
, " :pattern"
, " ( (elem@@sl$BLK (apply@@sl$TRAIN@@sl$BLK loc t) sl$BLK) ))))"
, "; inv2"
, "(assert (= (dom@@sl$TRAIN@@sl$BLK loc) in))"
, "(assert (not (and (= (apply@@sl$TRAIN@@sl$BLK loc t) ext)"
, " (elem@@sl$TRAIN t in))))"
, "(check-sat-using (or-else (then qe smt)"
, " (then simplify smt)"
, " (then skip smt)"
, " (then (using-params simplify :expand-power true) smt)))"
, "; train0/leave/SCH/grd0"
]
case4 :: IO String
case4 = proof_obligation path0 "train0/leave/SCH/grd0" 0
result5 :: String
result5 = unlines
[ "; train0/tr0/TR/WFIS/t/t@prime"
, "(set-option :auto-config false)"
, "(set-option :smt.timeout 3000)"
, "(declare-datatypes (a) ( (Maybe (Just (fromJust a)) Nothing) ))"
, "(declare-datatypes () ( (Null null) ))"
, "(declare-datatypes (a b) ( (Pair (pair (first a) (second b))) ))"
, "(define-sort guarded (a) (Maybe a))"
, "(declare-sort sl$BLK 0)"
, "; comment: we don't need to declare the sort Bool"
, "; comment: we don't need to declare the sort Int"
, "(declare-sort sl$LOC 0)"
, "; comment: we don't need to declare the sort Real"
, "(declare-sort sl$TRAIN 0)"
, "(define-sort pfun (a b) (Array a (Maybe b)))"
, "(define-sort set (a) (Array a Bool))"
, "(declare-const PLF (set sl$BLK))"
, "(declare-const ent sl$BLK)"
, "(declare-const ext sl$BLK)"
, "(declare-const in (set sl$TRAIN))"
, "(declare-const in@prime (set sl$TRAIN))"
, "(declare-const loc (pfun sl$TRAIN sl$BLK))"
, "(declare-const loc@prime (pfun sl$TRAIN sl$BLK))"
, "(declare-const t sl$TRAIN)"
, "(declare-fun apply@@sl$TRAIN@@sl$BLK"
, " ( (pfun sl$TRAIN sl$BLK)"
, " sl$TRAIN )"
, " sl$BLK)"
, "(declare-fun card@@sl$BLK ( (set sl$BLK) ) Int)"
, "(declare-fun card@@sl$LOC ( (set sl$LOC) ) Int)"
, "(declare-fun card@@sl$TRAIN ( (set sl$TRAIN) ) Int)"
, "(declare-fun dom@@sl$TRAIN@@sl$BLK"
, " ( (pfun sl$TRAIN sl$BLK) )"
, " (set sl$TRAIN))"
, "(declare-fun dom-rest@@sl$TRAIN@@sl$BLK"
, " ( (set sl$TRAIN)"
, " (pfun sl$TRAIN sl$BLK) )"
, " (pfun sl$TRAIN sl$BLK))"
, "(declare-fun dom-subt@@sl$TRAIN@@sl$BLK"
, " ( (set sl$TRAIN)"
, " (pfun sl$TRAIN sl$BLK) )"
, " (pfun sl$TRAIN sl$BLK))"
, "(declare-fun empty-fun@@sl$TRAIN@@sl$BLK"
, " ()"
, " (pfun sl$TRAIN sl$BLK))"
, "(declare-fun finite@@sl$BLK ( (set sl$BLK) ) Bool)"
, "(declare-fun finite@@sl$LOC ( (set sl$LOC) ) Bool)"
, "(declare-fun finite@@sl$TRAIN ( (set sl$TRAIN) ) Bool)"
, "(declare-fun injective@@sl$TRAIN@@sl$BLK"
, " ( (pfun sl$TRAIN sl$BLK) )"
, " Bool)"
, "(declare-fun mk-fun@@sl$TRAIN@@sl$BLK"
, " (sl$TRAIN sl$BLK)"
, " (pfun sl$TRAIN sl$BLK))"
, "(declare-fun mk-set@@sl$BLK (sl$BLK) (set sl$BLK))"
, "(declare-fun mk-set@@sl$TRAIN (sl$TRAIN) (set sl$TRAIN))"
, "(declare-fun ovl@@sl$TRAIN@@sl$BLK"
, " ( (pfun sl$TRAIN sl$BLK)"
, " (pfun sl$TRAIN sl$BLK) )"
, " (pfun sl$TRAIN sl$BLK))"
, "(declare-fun ran@@sl$TRAIN@@sl$BLK"
, " ( (pfun sl$TRAIN sl$BLK) )"
, " (set sl$BLK))"
, "(define-fun all@@sl$BLK"
, " ()"
, " (set sl$BLK)"
, " ( (as const (set sl$BLK))"
, " true ))"
, "(define-fun all@@sl$LOC"
, " ()"
, " (set sl$LOC)"
, " ( (as const (set sl$LOC))"
, " true ))"
, "(define-fun all@@sl$TRAIN"
, " ()"
, " (set sl$TRAIN)"
, " ( (as const (set sl$TRAIN))"
, " true ))"
, "(define-fun compl@@sl$BLK"
, " ( (s1 (set sl$BLK)) )"
, " (set sl$BLK)"
, " ( (_ map not)"
, " s1 ))"
, "(define-fun compl@@sl$LOC"
, " ( (s1 (set sl$LOC)) )"
, " (set sl$LOC)"
, " ( (_ map not)"
, " s1 ))"
, "(define-fun compl@@sl$TRAIN"
, " ( (s1 (set sl$TRAIN)) )"
, " (set sl$TRAIN)"
, " ( (_ map not)"
, " s1 ))"
, "(define-fun elem@@sl$BLK"
, " ( (x sl$BLK)"
, " (s1 (set sl$BLK)) )"
, " Bool"
, " (select s1 x))"
, "(define-fun elem@@sl$TRAIN"
, " ( (x sl$TRAIN)"
, " (s1 (set sl$TRAIN)) )"
, " Bool"
, " (select s1 x))"
, "(define-fun empty-set@@sl$BLK"
, " ()"
, " (set sl$BLK)"
, " ( (as const (set sl$BLK))"
, " false ))"
, "(define-fun empty-set@@sl$LOC"
, " ()"
, " (set sl$LOC)"
, " ( (as const (set sl$LOC))"
, " false ))"
, "(define-fun empty-set@@sl$TRAIN"
, " ()"
, " (set sl$TRAIN)"
, " ( (as const (set sl$TRAIN))"
, " false ))"
, "(define-fun set-diff@@sl$BLK"
, " ( (s1 (set sl$BLK))"
, " (s2 (set sl$BLK)) )"
, " (set sl$BLK)"
, " (intersect s1 ( (_ map not) s2 )))"
, "(define-fun set-diff@@sl$LOC"
, " ( (s1 (set sl$LOC))"
, " (s2 (set sl$LOC)) )"
, " (set sl$LOC)"
, " (intersect s1 ( (_ map not) s2 )))"
, "(define-fun set-diff@@sl$TRAIN"
, " ( (s1 (set sl$TRAIN))"
, " (s2 (set sl$TRAIN)) )"
, " (set sl$TRAIN)"
, " (intersect s1 ( (_ map not) s2 )))"
, "(define-fun st-subset@@sl$BLK"
, " ( (s1 (set sl$BLK))"
, " (s2 (set sl$BLK)) )"
, " Bool"
, " (and (subset s1 s2) (not (= s1 s2))))"
, "(define-fun st-subset@@sl$LOC"
, " ( (s1 (set sl$LOC))"
, " (s2 (set sl$LOC)) )"
, " Bool"
, " (and (subset s1 s2) (not (= s1 s2))))"
, "(define-fun st-subset@@sl$TRAIN"
, " ( (s1 (set sl$TRAIN))"
, " (s2 (set sl$TRAIN)) )"
, " Bool"
, " (and (subset s1 s2) (not (= s1 s2))))"
, "(define-fun sl$BLK"
, " ()"
, " (set sl$BLK)"
, " ( (as const (set sl$BLK))"
, " true ))"
, "(define-fun sl$LOC"
, " ()"
, " (set sl$LOC)"
, " ( (as const (set sl$LOC))"
, " true ))"
, "(define-fun sl$TRAIN"
, " ()"
, " (set sl$TRAIN)"
, " ( (as const (set sl$TRAIN))"
, " true ))"
, "(assert (forall ( (r (set sl$BLK)) )"
, " (! (=> (finite@@sl$BLK r) (<= 0 (card@@sl$BLK r)))"
, " :pattern"
, " ( (<= 0 (card@@sl$BLK r)) ))))"
, "(assert (forall ( (r (set sl$LOC)) )"
, " (! (=> (finite@@sl$LOC r) (<= 0 (card@@sl$LOC r)))"
, " :pattern"
, " ( (<= 0 (card@@sl$LOC r)) ))))"
, "(assert (forall ( (r (set sl$TRAIN)) )"
, " (! (=> (finite@@sl$TRAIN r) (<= 0 (card@@sl$TRAIN r)))"
, " :pattern"
, " ( (<= 0 (card@@sl$TRAIN r)) ))))"
, "(assert (forall ( (r (set sl$BLK)) )"
, " (! (= (= (card@@sl$BLK r) 0) (= r empty-set@@sl$BLK))"
, " :pattern"
, " ( (card@@sl$BLK r) ))))"
, "(assert (forall ( (r (set sl$LOC)) )"
, " (! (= (= (card@@sl$LOC r) 0) (= r empty-set@@sl$LOC))"
, " :pattern"
, " ( (card@@sl$LOC r) ))))"
, "(assert (forall ( (r (set sl$TRAIN)) )"
, " (! (= (= (card@@sl$TRAIN r) 0)"
, " (= r empty-set@@sl$TRAIN))"
, " :pattern"
, " ( (card@@sl$TRAIN r) ))))"
, "(assert (forall ( (x sl$BLK) )"
, " (! (= (card@@sl$BLK (mk-set@@sl$BLK x)) 1)"
, " :pattern"
, " ( (card@@sl$BLK (mk-set@@sl$BLK x)) ))))"
, "(assert (forall ( (x sl$TRAIN) )"
, " (! (= (card@@sl$TRAIN (mk-set@@sl$TRAIN x)) 1)"
, " :pattern"
, " ( (card@@sl$TRAIN (mk-set@@sl$TRAIN x)) ))))"
, "(assert (forall ( (r (set sl$BLK)) )"
, " (! (= (= (card@@sl$BLK r) 1)"
, " (exists ( (x sl$BLK) ) (and true (= r (mk-set@@sl$BLK x)))))"
, " :pattern"
, " ( (card@@sl$BLK r) ))))"
, "(assert (forall ( (r (set sl$TRAIN)) )"
, " (! (= (= (card@@sl$TRAIN r) 1)"
, " (exists ( (x sl$TRAIN) )"
, " (and true (= r (mk-set@@sl$TRAIN x)))))"
, " :pattern"
, " ( (card@@sl$TRAIN r) ))))"
, "(assert (forall ( (r (set sl$BLK))"
, " (r0 (set sl$BLK)) )"
, " (! (=> (= (intersect r r0) empty-set@@sl$BLK)"
, " (= (card@@sl$BLK (union r r0))"
, " (+ (card@@sl$BLK r) (card@@sl$BLK r0))))"
, " :pattern"
, " ( (card@@sl$BLK (union r r0)) ))))"
, "(assert (forall ( (r (set sl$LOC))"
, " (r0 (set sl$LOC)) )"
, " (! (=> (= (intersect r r0) empty-set@@sl$LOC)"
, " (= (card@@sl$LOC (union r r0))"
, " (+ (card@@sl$LOC r) (card@@sl$LOC r0))))"
, " :pattern"
, " ( (card@@sl$LOC (union r r0)) ))))"
, "(assert (forall ( (r (set sl$TRAIN))"
, " (r0 (set sl$TRAIN)) )"
, " (! (=> (= (intersect r r0) empty-set@@sl$TRAIN)"
, " (= (card@@sl$TRAIN (union r r0))"
, " (+ (card@@sl$TRAIN r) (card@@sl$TRAIN r0))))"
, " :pattern"
, " ( (card@@sl$TRAIN (union r r0)) ))))"
, "(assert (= (dom@@sl$TRAIN@@sl$BLK empty-fun@@sl$TRAIN@@sl$BLK)"
, " empty-set@@sl$TRAIN))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK)) )"
, " (! (= (ovl@@sl$TRAIN@@sl$BLK f1 empty-fun@@sl$TRAIN@@sl$BLK)"
, " f1)"
, " :pattern"
, " ( (ovl@@sl$TRAIN@@sl$BLK f1 empty-fun@@sl$TRAIN@@sl$BLK) ))))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK)) )"
, " (! (= (ovl@@sl$TRAIN@@sl$BLK empty-fun@@sl$TRAIN@@sl$BLK f1)"
, " f1)"
, " :pattern"
, " ( (ovl@@sl$TRAIN@@sl$BLK empty-fun@@sl$TRAIN@@sl$BLK f1) ))))"
, "(assert (forall ( (x sl$TRAIN)"
, " (y sl$BLK) )"
, " (! (= (dom@@sl$TRAIN@@sl$BLK (mk-fun@@sl$TRAIN@@sl$BLK x y))"
, " (mk-set@@sl$TRAIN x))"
, " :pattern"
, " ( (dom@@sl$TRAIN@@sl$BLK (mk-fun@@sl$TRAIN@@sl$BLK x y)) ))))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK))"
, " (f2 (pfun sl$TRAIN sl$BLK))"
, " (x sl$TRAIN) )"
, " (! (=> (elem@@sl$TRAIN x (dom@@sl$TRAIN@@sl$BLK f2))"
, " (= (apply@@sl$TRAIN@@sl$BLK (ovl@@sl$TRAIN@@sl$BLK f1 f2) x)"
, " (apply@@sl$TRAIN@@sl$BLK f2 x)))"
, " :pattern"
, " ( (apply@@sl$TRAIN@@sl$BLK (ovl@@sl$TRAIN@@sl$BLK f1 f2) x) ))))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK))"
, " (f2 (pfun sl$TRAIN sl$BLK))"
, " (x sl$TRAIN) )"
, " (! (=> (and (elem@@sl$TRAIN x (dom@@sl$TRAIN@@sl$BLK f1))"
, " (not (elem@@sl$TRAIN x (dom@@sl$TRAIN@@sl$BLK f2))))"
, " (= (apply@@sl$TRAIN@@sl$BLK (ovl@@sl$TRAIN@@sl$BLK f1 f2) x)"
, " (apply@@sl$TRAIN@@sl$BLK f1 x)))"
, " :pattern"
, " ( (apply@@sl$TRAIN@@sl$BLK (ovl@@sl$TRAIN@@sl$BLK f1 f2) x) ))))"
, "(assert (forall ( (x sl$TRAIN)"
, " (y sl$BLK) )"
, " (! (= (apply@@sl$TRAIN@@sl$BLK (mk-fun@@sl$TRAIN@@sl$BLK x y) x)"
, " y)"
, " :pattern"
, " ( (apply@@sl$TRAIN@@sl$BLK (mk-fun@@sl$TRAIN@@sl$BLK x y) x) ))))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK))"
, " (s1 (set sl$TRAIN))"
, " (x sl$TRAIN) )"
, " (! (=> (and (elem@@sl$TRAIN x s1)"
, " (elem@@sl$TRAIN x (dom@@sl$TRAIN@@sl$BLK f1)))"
, " (= (apply@@sl$TRAIN@@sl$BLK (dom-rest@@sl$TRAIN@@sl$BLK s1 f1) x)"
, " (apply@@sl$TRAIN@@sl$BLK f1 x)))"
, " :pattern"
, " ( (apply@@sl$TRAIN@@sl$BLK (dom-rest@@sl$TRAIN@@sl$BLK s1 f1) x) ))))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK))"
, " (s1 (set sl$TRAIN))"
, " (x sl$TRAIN) )"
, " (! (=> (elem@@sl$TRAIN x"
, " (set-diff@@sl$TRAIN (dom@@sl$TRAIN@@sl$BLK f1) s1))"
, " (= (apply@@sl$TRAIN@@sl$BLK (dom-subt@@sl$TRAIN@@sl$BLK s1 f1) x)"
, " (apply@@sl$TRAIN@@sl$BLK f1 x)))"
, " :pattern"
, " ( (apply@@sl$TRAIN@@sl$BLK (dom-subt@@sl$TRAIN@@sl$BLK s1 f1) x) ))))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK))"
, " (f2 (pfun sl$TRAIN sl$BLK)) )"
, " (! (= (dom@@sl$TRAIN@@sl$BLK (ovl@@sl$TRAIN@@sl$BLK f1 f2))"
, " (union (dom@@sl$TRAIN@@sl$BLK f1)"
, " (dom@@sl$TRAIN@@sl$BLK f2)))"
, " :pattern"
, " ( (dom@@sl$TRAIN@@sl$BLK (ovl@@sl$TRAIN@@sl$BLK f1 f2)) ))))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK))"
, " (s1 (set sl$TRAIN)) )"
, " (! (= (dom@@sl$TRAIN@@sl$BLK (dom-rest@@sl$TRAIN@@sl$BLK s1 f1))"
, " (intersect s1 (dom@@sl$TRAIN@@sl$BLK f1)))"
, " :pattern"
, " ( (dom@@sl$TRAIN@@sl$BLK (dom-rest@@sl$TRAIN@@sl$BLK s1 f1)) ))))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK))"
, " (s1 (set sl$TRAIN)) )"
, " (! (= (dom@@sl$TRAIN@@sl$BLK (dom-subt@@sl$TRAIN@@sl$BLK s1 f1))"
, " (set-diff@@sl$TRAIN (dom@@sl$TRAIN@@sl$BLK f1) s1))"
, " :pattern"
, " ( (dom@@sl$TRAIN@@sl$BLK (dom-subt@@sl$TRAIN@@sl$BLK s1 f1)) ))))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK))"
, " (x sl$TRAIN)"
, " (y sl$BLK) )"
, " (! (= (and (elem@@sl$TRAIN x (dom@@sl$TRAIN@@sl$BLK f1))"
, " (= (apply@@sl$TRAIN@@sl$BLK f1 x) y))"
, " (= (select f1 x) (Just y)))"
, " :pattern"
, " ( (elem@@sl$TRAIN x (dom@@sl$TRAIN@@sl$BLK f1))"
, " (apply@@sl$TRAIN@@sl$BLK f1 x)"
, " (select f1 x)"
, " (Just y) ))))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK))"
, " (x sl$TRAIN)"
, " (x2 sl$TRAIN)"
, " (y sl$BLK) )"
, " (! (=> (not (= x x2))"
, " (= (apply@@sl$TRAIN@@sl$BLK (ovl@@sl$TRAIN@@sl$BLK f1 (mk-fun@@sl$TRAIN@@sl$BLK x y))"
, " x2)"
, " (apply@@sl$TRAIN@@sl$BLK f1 x2)))"
, " :pattern"
, " ( (apply@@sl$TRAIN@@sl$BLK (ovl@@sl$TRAIN@@sl$BLK f1 (mk-fun@@sl$TRAIN@@sl$BLK x y))"
, " x2) ))))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK))"
, " (x sl$TRAIN)"
, " (y sl$BLK) )"
, " (! (= (apply@@sl$TRAIN@@sl$BLK (ovl@@sl$TRAIN@@sl$BLK f1 (mk-fun@@sl$TRAIN@@sl$BLK x y))"
, " x)"
, " y)"
, " :pattern"
, " ( (apply@@sl$TRAIN@@sl$BLK (ovl@@sl$TRAIN@@sl$BLK f1 (mk-fun@@sl$TRAIN@@sl$BLK x y))"
, " x) ))))"
, "(assert (= (ran@@sl$TRAIN@@sl$BLK empty-fun@@sl$TRAIN@@sl$BLK)"
, " empty-set@@sl$BLK))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK))"
, " (y sl$BLK) )"
, " (! (= (elem@@sl$BLK y (ran@@sl$TRAIN@@sl$BLK f1))"
, " (exists ( (x sl$TRAIN) )"
, " (and true"
, " (and (elem@@sl$TRAIN x (dom@@sl$TRAIN@@sl$BLK f1))"
, " (= (apply@@sl$TRAIN@@sl$BLK f1 x) y)))))"
, " :pattern"
, " ( (elem@@sl$BLK y (ran@@sl$TRAIN@@sl$BLK f1)) ))))"
, "(assert (forall ( (x sl$TRAIN)"
, " (y sl$BLK) )"
, " (! (= (ran@@sl$TRAIN@@sl$BLK (mk-fun@@sl$TRAIN@@sl$BLK x y))"
, " (mk-set@@sl$BLK y))"
, " :pattern"
, " ( (ran@@sl$TRAIN@@sl$BLK (mk-fun@@sl$TRAIN@@sl$BLK x y)) ))))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK)) )"
, " (! (= (injective@@sl$TRAIN@@sl$BLK f1)"
, " (forall ( (x sl$TRAIN)"
, " (x2 sl$TRAIN) )"
, " (=> (and (elem@@sl$TRAIN x (dom@@sl$TRAIN@@sl$BLK f1))"
, " (elem@@sl$TRAIN x2 (dom@@sl$TRAIN@@sl$BLK f1)))"
, " (=> (= (apply@@sl$TRAIN@@sl$BLK f1 x)"
, " (apply@@sl$TRAIN@@sl$BLK f1 x2))"
, " (= x x2)))))"
, " :pattern"
, " ( (injective@@sl$TRAIN@@sl$BLK f1) ))))"
, "(assert (injective@@sl$TRAIN@@sl$BLK empty-fun@@sl$TRAIN@@sl$BLK))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK))"
, " (x sl$TRAIN) )"
, " (! (=> (elem@@sl$TRAIN x (dom@@sl$TRAIN@@sl$BLK f1))"
, " (elem@@sl$BLK (apply@@sl$TRAIN@@sl$BLK f1 x)"
, " (ran@@sl$TRAIN@@sl$BLK f1)))"
, " :pattern"
, " ( (elem@@sl$BLK (apply@@sl$TRAIN@@sl$BLK f1 x)"
, " (ran@@sl$TRAIN@@sl$BLK f1)) ))))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK))"
, " (s1 (set sl$TRAIN))"
, " (x sl$TRAIN) )"
, " (! (=> (elem@@sl$TRAIN x"
, " (set-diff@@sl$TRAIN (dom@@sl$TRAIN@@sl$BLK f1) s1))"
, " (elem@@sl$BLK (apply@@sl$TRAIN@@sl$BLK f1 x)"
, " (ran@@sl$TRAIN@@sl$BLK (dom-subt@@sl$TRAIN@@sl$BLK s1 f1))))"
, " :pattern"
, " ( (elem@@sl$BLK (apply@@sl$TRAIN@@sl$BLK f1 x)"
, " (ran@@sl$TRAIN@@sl$BLK (dom-subt@@sl$TRAIN@@sl$BLK s1 f1))) ))))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK))"
, " (s1 (set sl$TRAIN))"
, " (x sl$TRAIN) )"
, " (! (=> (elem@@sl$TRAIN x (intersect (dom@@sl$TRAIN@@sl$BLK f1) s1))"
, " (elem@@sl$BLK (apply@@sl$TRAIN@@sl$BLK f1 x)"
, " (ran@@sl$TRAIN@@sl$BLK (dom-rest@@sl$TRAIN@@sl$BLK s1 f1))))"
, " :pattern"
, " ( (elem@@sl$BLK (apply@@sl$TRAIN@@sl$BLK f1 x)"
, " (ran@@sl$TRAIN@@sl$BLK (dom-rest@@sl$TRAIN@@sl$BLK s1 f1))) ))))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK))"
, " (x sl$TRAIN)"
, " (y sl$BLK) )"
, " (! (=> (and (elem@@sl$TRAIN x (dom@@sl$TRAIN@@sl$BLK f1))"
, " (injective@@sl$TRAIN@@sl$BLK f1))"
, " (= (ran@@sl$TRAIN@@sl$BLK (ovl@@sl$TRAIN@@sl$BLK f1 (mk-fun@@sl$TRAIN@@sl$BLK x y)))"
, " (union (set-diff@@sl$BLK (ran@@sl$TRAIN@@sl$BLK f1)"
, " (mk-set@@sl$BLK (apply@@sl$TRAIN@@sl$BLK f1 x)))"
, " (mk-set@@sl$BLK y))))"
, " :pattern"
, " ( (ran@@sl$TRAIN@@sl$BLK (ovl@@sl$TRAIN@@sl$BLK f1 (mk-fun@@sl$TRAIN@@sl$BLK x y))) ))))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK))"
, " (x sl$TRAIN)"
, " (y sl$BLK) )"
, " (! (=> (not (elem@@sl$TRAIN x (dom@@sl$TRAIN@@sl$BLK f1)))"
, " (= (ran@@sl$TRAIN@@sl$BLK (ovl@@sl$TRAIN@@sl$BLK f1 (mk-fun@@sl$TRAIN@@sl$BLK x y)))"
, " (union (ran@@sl$TRAIN@@sl$BLK f1) (mk-set@@sl$BLK y))))"
, " :pattern"
, " ( (ran@@sl$TRAIN@@sl$BLK (ovl@@sl$TRAIN@@sl$BLK f1 (mk-fun@@sl$TRAIN@@sl$BLK x y))) ))))"
, "(assert (forall ( (x sl$BLK)"
, " (y sl$BLK) )"
, " (! (= (elem@@sl$BLK x (mk-set@@sl$BLK y)) (= x y))"
, " :pattern"
, " ( (elem@@sl$BLK x (mk-set@@sl$BLK y)) ))))"
, "(assert (forall ( (x sl$TRAIN)"
, " (y sl$TRAIN) )"
, " (! (= (elem@@sl$TRAIN x (mk-set@@sl$TRAIN y)) (= x y))"
, " :pattern"
, " ( (elem@@sl$TRAIN x (mk-set@@sl$TRAIN y)) ))))"
, "(assert (forall ( (s1 (set sl$BLK))"
, " (s2 (set sl$BLK)) )"
, " (! (=> (finite@@sl$BLK s1)"
, " (finite@@sl$BLK (set-diff@@sl$BLK s1 s2)))"
, " :pattern"
, " ( (finite@@sl$BLK (set-diff@@sl$BLK s1 s2)) ))))"
, "(assert (forall ( (s1 (set sl$LOC))"
, " (s2 (set sl$LOC)) )"
, " (! (=> (finite@@sl$LOC s1)"
, " (finite@@sl$LOC (set-diff@@sl$LOC s1 s2)))"
, " :pattern"
, " ( (finite@@sl$LOC (set-diff@@sl$LOC s1 s2)) ))))"
, "(assert (forall ( (s1 (set sl$TRAIN))"
, " (s2 (set sl$TRAIN)) )"
, " (! (=> (finite@@sl$TRAIN s1)"
, " (finite@@sl$TRAIN (set-diff@@sl$TRAIN s1 s2)))"
, " :pattern"
, " ( (finite@@sl$TRAIN (set-diff@@sl$TRAIN s1 s2)) ))))"
, "(assert (forall ( (s1 (set sl$BLK))"
, " (s2 (set sl$BLK)) )"
, " (! (=> (and (finite@@sl$BLK s1) (finite@@sl$BLK s2))"
, " (finite@@sl$BLK (union s1 s2)))"
, " :pattern"
, " ( (finite@@sl$BLK (union s1 s2)) ))))"
, "(assert (forall ( (s1 (set sl$LOC))"
, " (s2 (set sl$LOC)) )"
, " (! (=> (and (finite@@sl$LOC s1) (finite@@sl$LOC s2))"
, " (finite@@sl$LOC (union s1 s2)))"
, " :pattern"
, " ( (finite@@sl$LOC (union s1 s2)) ))))"
, "(assert (forall ( (s1 (set sl$TRAIN))"
, " (s2 (set sl$TRAIN)) )"
, " (! (=> (and (finite@@sl$TRAIN s1) (finite@@sl$TRAIN s2))"
, " (finite@@sl$TRAIN (union s1 s2)))"
, " :pattern"
, " ( (finite@@sl$TRAIN (union s1 s2)) ))))"
, "(assert (forall ( (s1 (set sl$BLK))"
, " (s2 (set sl$BLK)) )"
, " (! (=> (and (finite@@sl$BLK s2) (not (finite@@sl$BLK s1)))"
, " (not (finite@@sl$BLK (set-diff@@sl$BLK s1 s2))))"
, " :pattern"
, " ( (finite@@sl$BLK (set-diff@@sl$BLK s1 s2)) ))))"
, "(assert (forall ( (s1 (set sl$LOC))"
, " (s2 (set sl$LOC)) )"
, " (! (=> (and (finite@@sl$LOC s2) (not (finite@@sl$LOC s1)))"
, " (not (finite@@sl$LOC (set-diff@@sl$LOC s1 s2))))"
, " :pattern"
, " ( (finite@@sl$LOC (set-diff@@sl$LOC s1 s2)) ))))"
, "(assert (forall ( (s1 (set sl$TRAIN))"
, " (s2 (set sl$TRAIN)) )"
, " (! (=> (and (finite@@sl$TRAIN s2) (not (finite@@sl$TRAIN s1)))"
, " (not (finite@@sl$TRAIN (set-diff@@sl$TRAIN s1 s2))))"
, " :pattern"
, " ( (finite@@sl$TRAIN (set-diff@@sl$TRAIN s1 s2)) ))))"
, "(assert (forall ( (x sl$BLK) )"
, " (! (finite@@sl$BLK (mk-set@@sl$BLK x))"
, " :pattern"
, " ( (finite@@sl$BLK (mk-set@@sl$BLK x)) ))))"
, "(assert (forall ( (x sl$TRAIN) )"
, " (! (finite@@sl$TRAIN (mk-set@@sl$TRAIN x))"
, " :pattern"
, " ( (finite@@sl$TRAIN (mk-set@@sl$TRAIN x)) ))))"
, "(assert (finite@@sl$BLK empty-set@@sl$BLK))"
, "(assert (finite@@sl$LOC empty-set@@sl$LOC))"
, "(assert (finite@@sl$TRAIN empty-set@@sl$TRAIN))"
, "(assert (not (exists ( (t@prime sl$TRAIN) ) (and true (= t@prime t)))))"
, "; asm2"
, "(assert (and (not (= ent ext))"
, " (not (elem@@sl$BLK ent PLF))"
, " (not (elem@@sl$BLK ext PLF))))"
, "; asm3"
, "(assert (forall ( (p sl$BLK) )"
, " (! (= (not (= p ext))"
, " (elem@@sl$BLK p (union (mk-set@@sl$BLK ent) PLF)))"
, " :pattern"
, " ( (elem@@sl$BLK p (union (mk-set@@sl$BLK ent) PLF)) ))))"
, "; asm4"
, "(assert (forall ( (p sl$BLK) )"
, " (! (= (not (= p ent))"
, " (elem@@sl$BLK p (union (mk-set@@sl$BLK ext) PLF)))"
, " :pattern"
, " ( (elem@@sl$BLK p (union (mk-set@@sl$BLK ext) PLF)) ))))"
, "; asm5"
, "(assert (forall ( (p sl$BLK) )"
, " (! (= (or (= p ent) (= p ext))"
, " (not (elem@@sl$BLK p PLF)))"
, " :pattern"
, " ( (elem@@sl$BLK p PLF) ))))"
, "; axm0"
, "(assert (= sl$BLK"
, " (union (union (mk-set@@sl$BLK ent) (mk-set@@sl$BLK ext))"
, " PLF)))"
, "; inv1"
, "(assert (forall ( (t sl$TRAIN) )"
, " (! (=> (elem@@sl$TRAIN t in)"
, " (elem@@sl$BLK (apply@@sl$TRAIN@@sl$BLK loc t) sl$BLK))"
, " :pattern"
, " ( (elem@@sl$BLK (apply@@sl$TRAIN@@sl$BLK loc t) sl$BLK) ))))"
, "; inv2"
, "(assert (= (dom@@sl$TRAIN@@sl$BLK loc) in))"
, "; tr0"
, "(assert (elem@@sl$TRAIN t in))"
, "(assert (not true))"
, "(check-sat-using (or-else (then qe smt)"
, " (then simplify smt)"
, " (then skip smt)"
, " (then (using-params simplify :expand-power true) smt)))"
, "; train0/tr0/TR/WFIS/t/t@prime"
]
case5 :: IO String
case5 = proof_obligation path0 "train0/tr0/TR/WFIS/t/t@prime" 0
result23 :: String
result23 = unlines
[ "; train0/tr0/TR/leave/EN"
, "(set-option :auto-config false)"
, "(set-option :smt.timeout 3000)"
, "(declare-datatypes (a) ( (Maybe (Just (fromJust a)) Nothing) ))"
, "(declare-datatypes () ( (Null null) ))"
, "(declare-datatypes (a b) ( (Pair (pair (first a) (second b))) ))"
, "(define-sort guarded (a) (Maybe a))"
, "(declare-sort sl$BLK 0)"
, "; comment: we don't need to declare the sort Bool"
, "; comment: we don't need to declare the sort Int"
, "(declare-sort sl$LOC 0)"
, "; comment: we don't need to declare the sort Real"
, "(declare-sort sl$TRAIN 0)"
, "(define-sort pfun (a b) (Array a (Maybe b)))"
, "(define-sort set (a) (Array a Bool))"
, "(declare-const PLF (set sl$BLK))"
, "(declare-const ent sl$BLK)"
, "(declare-const ext sl$BLK)"
, "(declare-const in (set sl$TRAIN))"
, "(declare-const in@prime (set sl$TRAIN))"
, "(declare-const loc (pfun sl$TRAIN sl$BLK))"
, "(declare-const loc@prime (pfun sl$TRAIN sl$BLK))"
, "(declare-const t sl$TRAIN)"
, "(declare-fun apply@@sl$TRAIN@@sl$BLK"
, " ( (pfun sl$TRAIN sl$BLK)"
, " sl$TRAIN )"
, " sl$BLK)"
, "(declare-fun card@@sl$BLK ( (set sl$BLK) ) Int)"
, "(declare-fun card@@sl$LOC ( (set sl$LOC) ) Int)"
, "(declare-fun card@@sl$TRAIN ( (set sl$TRAIN) ) Int)"
, "(declare-fun dom@@sl$TRAIN@@sl$BLK"
, " ( (pfun sl$TRAIN sl$BLK) )"
, " (set sl$TRAIN))"
, "(declare-fun dom-rest@@sl$TRAIN@@sl$BLK"
, " ( (set sl$TRAIN)"
, " (pfun sl$TRAIN sl$BLK) )"
, " (pfun sl$TRAIN sl$BLK))"
, "(declare-fun dom-subt@@sl$TRAIN@@sl$BLK"
, " ( (set sl$TRAIN)"
, " (pfun sl$TRAIN sl$BLK) )"
, " (pfun sl$TRAIN sl$BLK))"
, "(declare-fun empty-fun@@sl$TRAIN@@sl$BLK"
, " ()"
, " (pfun sl$TRAIN sl$BLK))"
, "(declare-fun finite@@sl$BLK ( (set sl$BLK) ) Bool)"
, "(declare-fun finite@@sl$LOC ( (set sl$LOC) ) Bool)"
, "(declare-fun finite@@sl$TRAIN ( (set sl$TRAIN) ) Bool)"
, "(declare-fun injective@@sl$TRAIN@@sl$BLK"
, " ( (pfun sl$TRAIN sl$BLK) )"
, " Bool)"
, "(declare-fun mk-fun@@sl$TRAIN@@sl$BLK"
, " (sl$TRAIN sl$BLK)"
, " (pfun sl$TRAIN sl$BLK))"
, "(declare-fun mk-set@@sl$BLK (sl$BLK) (set sl$BLK))"
, "(declare-fun mk-set@@sl$TRAIN (sl$TRAIN) (set sl$TRAIN))"
, "(declare-fun ovl@@sl$TRAIN@@sl$BLK"
, " ( (pfun sl$TRAIN sl$BLK)"
, " (pfun sl$TRAIN sl$BLK) )"
, " (pfun sl$TRAIN sl$BLK))"
, "(declare-fun ran@@sl$TRAIN@@sl$BLK"
, " ( (pfun sl$TRAIN sl$BLK) )"
, " (set sl$BLK))"
, "(declare-fun t@param () sl$TRAIN)"
, "(define-fun all@@sl$BLK"
, " ()"
, " (set sl$BLK)"
, " ( (as const (set sl$BLK))"
, " true ))"
, "(define-fun all@@sl$LOC"
, " ()"
, " (set sl$LOC)"
, " ( (as const (set sl$LOC))"
, " true ))"
, "(define-fun all@@sl$TRAIN"
, " ()"
, " (set sl$TRAIN)"
, " ( (as const (set sl$TRAIN))"
, " true ))"
, "(define-fun compl@@sl$BLK"
, " ( (s1 (set sl$BLK)) )"
, " (set sl$BLK)"
, " ( (_ map not)"
, " s1 ))"
, "(define-fun compl@@sl$LOC"
, " ( (s1 (set sl$LOC)) )"
, " (set sl$LOC)"
, " ( (_ map not)"
, " s1 ))"
, "(define-fun compl@@sl$TRAIN"
, " ( (s1 (set sl$TRAIN)) )"
, " (set sl$TRAIN)"
, " ( (_ map not)"
, " s1 ))"
, "(define-fun elem@@sl$BLK"
, " ( (x sl$BLK)"
, " (s1 (set sl$BLK)) )"
, " Bool"
, " (select s1 x))"
, "(define-fun elem@@sl$TRAIN"
, " ( (x sl$TRAIN)"
, " (s1 (set sl$TRAIN)) )"
, " Bool"
, " (select s1 x))"
, "(define-fun empty-set@@sl$BLK"
, " ()"
, " (set sl$BLK)"
, " ( (as const (set sl$BLK))"
, " false ))"
, "(define-fun empty-set@@sl$LOC"
, " ()"
, " (set sl$LOC)"
, " ( (as const (set sl$LOC))"
, " false ))"
, "(define-fun empty-set@@sl$TRAIN"
, " ()"
, " (set sl$TRAIN)"
, " ( (as const (set sl$TRAIN))"
, " false ))"
, "(define-fun set-diff@@sl$BLK"
, " ( (s1 (set sl$BLK))"
, " (s2 (set sl$BLK)) )"
, " (set sl$BLK)"
, " (intersect s1 ( (_ map not) s2 )))"
, "(define-fun set-diff@@sl$LOC"
, " ( (s1 (set sl$LOC))"
, " (s2 (set sl$LOC)) )"
, " (set sl$LOC)"
, " (intersect s1 ( (_ map not) s2 )))"
, "(define-fun set-diff@@sl$TRAIN"
, " ( (s1 (set sl$TRAIN))"
, " (s2 (set sl$TRAIN)) )"
, " (set sl$TRAIN)"
, " (intersect s1 ( (_ map not) s2 )))"
, "(define-fun st-subset@@sl$BLK"
, " ( (s1 (set sl$BLK))"
, " (s2 (set sl$BLK)) )"
, " Bool"
, " (and (subset s1 s2) (not (= s1 s2))))"
, "(define-fun st-subset@@sl$LOC"
, " ( (s1 (set sl$LOC))"
, " (s2 (set sl$LOC)) )"
, " Bool"
, " (and (subset s1 s2) (not (= s1 s2))))"
, "(define-fun st-subset@@sl$TRAIN"
, " ( (s1 (set sl$TRAIN))"
, " (s2 (set sl$TRAIN)) )"
, " Bool"
, " (and (subset s1 s2) (not (= s1 s2))))"
, "(define-fun sl$BLK"
, " ()"
, " (set sl$BLK)"
, " ( (as const (set sl$BLK))"
, " true ))"
, "(define-fun sl$LOC"
, " ()"
, " (set sl$LOC)"
, " ( (as const (set sl$LOC))"
, " true ))"
, "(define-fun sl$TRAIN"
, " ()"
, " (set sl$TRAIN)"
, " ( (as const (set sl$TRAIN))"
, " true ))"
, "(assert (forall ( (r (set sl$BLK)) )"
, " (! (=> (finite@@sl$BLK r) (<= 0 (card@@sl$BLK r)))"
, " :pattern"
, " ( (<= 0 (card@@sl$BLK r)) ))))"
, "(assert (forall ( (r (set sl$LOC)) )"
, " (! (=> (finite@@sl$LOC r) (<= 0 (card@@sl$LOC r)))"
, " :pattern"
, " ( (<= 0 (card@@sl$LOC r)) ))))"
, "(assert (forall ( (r (set sl$TRAIN)) )"
, " (! (=> (finite@@sl$TRAIN r) (<= 0 (card@@sl$TRAIN r)))"
, " :pattern"
, " ( (<= 0 (card@@sl$TRAIN r)) ))))"
, "(assert (forall ( (r (set sl$BLK)) )"
, " (! (= (= (card@@sl$BLK r) 0) (= r empty-set@@sl$BLK))"
, " :pattern"
, " ( (card@@sl$BLK r) ))))"
, "(assert (forall ( (r (set sl$LOC)) )"
, " (! (= (= (card@@sl$LOC r) 0) (= r empty-set@@sl$LOC))"
, " :pattern"
, " ( (card@@sl$LOC r) ))))"
, "(assert (forall ( (r (set sl$TRAIN)) )"
, " (! (= (= (card@@sl$TRAIN r) 0)"
, " (= r empty-set@@sl$TRAIN))"
, " :pattern"
, " ( (card@@sl$TRAIN r) ))))"
, "(assert (forall ( (x sl$BLK) )"
, " (! (= (card@@sl$BLK (mk-set@@sl$BLK x)) 1)"
, " :pattern"
, " ( (card@@sl$BLK (mk-set@@sl$BLK x)) ))))"
, "(assert (forall ( (x sl$TRAIN) )"
, " (! (= (card@@sl$TRAIN (mk-set@@sl$TRAIN x)) 1)"
, " :pattern"
, " ( (card@@sl$TRAIN (mk-set@@sl$TRAIN x)) ))))"
, "(assert (forall ( (r (set sl$BLK)) )"
, " (! (= (= (card@@sl$BLK r) 1)"
, " (exists ( (x sl$BLK) ) (and true (= r (mk-set@@sl$BLK x)))))"
, " :pattern"
, " ( (card@@sl$BLK r) ))))"
, "(assert (forall ( (r (set sl$TRAIN)) )"
, " (! (= (= (card@@sl$TRAIN r) 1)"
, " (exists ( (x sl$TRAIN) )"
, " (and true (= r (mk-set@@sl$TRAIN x)))))"
, " :pattern"
, " ( (card@@sl$TRAIN r) ))))"
, "(assert (forall ( (r (set sl$BLK))"
, " (r0 (set sl$BLK)) )"
, " (! (=> (= (intersect r r0) empty-set@@sl$BLK)"
, " (= (card@@sl$BLK (union r r0))"
, " (+ (card@@sl$BLK r) (card@@sl$BLK r0))))"
, " :pattern"
, " ( (card@@sl$BLK (union r r0)) ))))"
, "(assert (forall ( (r (set sl$LOC))"
, " (r0 (set sl$LOC)) )"
, " (! (=> (= (intersect r r0) empty-set@@sl$LOC)"
, " (= (card@@sl$LOC (union r r0))"
, " (+ (card@@sl$LOC r) (card@@sl$LOC r0))))"
, " :pattern"
, " ( (card@@sl$LOC (union r r0)) ))))"
, "(assert (forall ( (r (set sl$TRAIN))"
, " (r0 (set sl$TRAIN)) )"
, " (! (=> (= (intersect r r0) empty-set@@sl$TRAIN)"
, " (= (card@@sl$TRAIN (union r r0))"
, " (+ (card@@sl$TRAIN r) (card@@sl$TRAIN r0))))"
, " :pattern"
, " ( (card@@sl$TRAIN (union r r0)) ))))"
, "(assert (= (dom@@sl$TRAIN@@sl$BLK empty-fun@@sl$TRAIN@@sl$BLK)"
, " empty-set@@sl$TRAIN))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK)) )"
, " (! (= (ovl@@sl$TRAIN@@sl$BLK f1 empty-fun@@sl$TRAIN@@sl$BLK)"
, " f1)"
, " :pattern"
, " ( (ovl@@sl$TRAIN@@sl$BLK f1 empty-fun@@sl$TRAIN@@sl$BLK) ))))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK)) )"
, " (! (= (ovl@@sl$TRAIN@@sl$BLK empty-fun@@sl$TRAIN@@sl$BLK f1)"
, " f1)"
, " :pattern"
, " ( (ovl@@sl$TRAIN@@sl$BLK empty-fun@@sl$TRAIN@@sl$BLK f1) ))))"
, "(assert (forall ( (x sl$TRAIN)"
, " (y sl$BLK) )"
, " (! (= (dom@@sl$TRAIN@@sl$BLK (mk-fun@@sl$TRAIN@@sl$BLK x y))"
, " (mk-set@@sl$TRAIN x))"
, " :pattern"
, " ( (dom@@sl$TRAIN@@sl$BLK (mk-fun@@sl$TRAIN@@sl$BLK x y)) ))))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK))"
, " (f2 (pfun sl$TRAIN sl$BLK))"
, " (x sl$TRAIN) )"
, " (! (=> (elem@@sl$TRAIN x (dom@@sl$TRAIN@@sl$BLK f2))"
, " (= (apply@@sl$TRAIN@@sl$BLK (ovl@@sl$TRAIN@@sl$BLK f1 f2) x)"
, " (apply@@sl$TRAIN@@sl$BLK f2 x)))"
, " :pattern"
, " ( (apply@@sl$TRAIN@@sl$BLK (ovl@@sl$TRAIN@@sl$BLK f1 f2) x) ))))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK))"
, " (f2 (pfun sl$TRAIN sl$BLK))"
, " (x sl$TRAIN) )"
, " (! (=> (and (elem@@sl$TRAIN x (dom@@sl$TRAIN@@sl$BLK f1))"
, " (not (elem@@sl$TRAIN x (dom@@sl$TRAIN@@sl$BLK f2))))"
, " (= (apply@@sl$TRAIN@@sl$BLK (ovl@@sl$TRAIN@@sl$BLK f1 f2) x)"
, " (apply@@sl$TRAIN@@sl$BLK f1 x)))"
, " :pattern"
, " ( (apply@@sl$TRAIN@@sl$BLK (ovl@@sl$TRAIN@@sl$BLK f1 f2) x) ))))"
, "(assert (forall ( (x sl$TRAIN)"
, " (y sl$BLK) )"
, " (! (= (apply@@sl$TRAIN@@sl$BLK (mk-fun@@sl$TRAIN@@sl$BLK x y) x)"
, " y)"
, " :pattern"
, " ( (apply@@sl$TRAIN@@sl$BLK (mk-fun@@sl$TRAIN@@sl$BLK x y) x) ))))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK))"
, " (s1 (set sl$TRAIN))"
, " (x sl$TRAIN) )"
, " (! (=> (and (elem@@sl$TRAIN x s1)"
, " (elem@@sl$TRAIN x (dom@@sl$TRAIN@@sl$BLK f1)))"
, " (= (apply@@sl$TRAIN@@sl$BLK (dom-rest@@sl$TRAIN@@sl$BLK s1 f1) x)"
, " (apply@@sl$TRAIN@@sl$BLK f1 x)))"
, " :pattern"
, " ( (apply@@sl$TRAIN@@sl$BLK (dom-rest@@sl$TRAIN@@sl$BLK s1 f1) x) ))))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK))"
, " (s1 (set sl$TRAIN))"
, " (x sl$TRAIN) )"
, " (! (=> (elem@@sl$TRAIN x"
, " (set-diff@@sl$TRAIN (dom@@sl$TRAIN@@sl$BLK f1) s1))"
, " (= (apply@@sl$TRAIN@@sl$BLK (dom-subt@@sl$TRAIN@@sl$BLK s1 f1) x)"
, " (apply@@sl$TRAIN@@sl$BLK f1 x)))"
, " :pattern"
, " ( (apply@@sl$TRAIN@@sl$BLK (dom-subt@@sl$TRAIN@@sl$BLK s1 f1) x) ))))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK))"
, " (f2 (pfun sl$TRAIN sl$BLK)) )"
, " (! (= (dom@@sl$TRAIN@@sl$BLK (ovl@@sl$TRAIN@@sl$BLK f1 f2))"
, " (union (dom@@sl$TRAIN@@sl$BLK f1)"
, " (dom@@sl$TRAIN@@sl$BLK f2)))"
, " :pattern"
, " ( (dom@@sl$TRAIN@@sl$BLK (ovl@@sl$TRAIN@@sl$BLK f1 f2)) ))))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK))"
, " (s1 (set sl$TRAIN)) )"
, " (! (= (dom@@sl$TRAIN@@sl$BLK (dom-rest@@sl$TRAIN@@sl$BLK s1 f1))"
, " (intersect s1 (dom@@sl$TRAIN@@sl$BLK f1)))"
, " :pattern"
, " ( (dom@@sl$TRAIN@@sl$BLK (dom-rest@@sl$TRAIN@@sl$BLK s1 f1)) ))))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK))"
, " (s1 (set sl$TRAIN)) )"
, " (! (= (dom@@sl$TRAIN@@sl$BLK (dom-subt@@sl$TRAIN@@sl$BLK s1 f1))"
, " (set-diff@@sl$TRAIN (dom@@sl$TRAIN@@sl$BLK f1) s1))"
, " :pattern"
, " ( (dom@@sl$TRAIN@@sl$BLK (dom-subt@@sl$TRAIN@@sl$BLK s1 f1)) ))))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK))"
, " (x sl$TRAIN)"
, " (y sl$BLK) )"
, " (! (= (and (elem@@sl$TRAIN x (dom@@sl$TRAIN@@sl$BLK f1))"
, " (= (apply@@sl$TRAIN@@sl$BLK f1 x) y))"
, " (= (select f1 x) (Just y)))"
, " :pattern"
, " ( (elem@@sl$TRAIN x (dom@@sl$TRAIN@@sl$BLK f1))"
, " (apply@@sl$TRAIN@@sl$BLK f1 x)"
, " (select f1 x)"
, " (Just y) ))))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK))"
, " (x sl$TRAIN)"
, " (x2 sl$TRAIN)"
, " (y sl$BLK) )"
, " (! (=> (not (= x x2))"
, " (= (apply@@sl$TRAIN@@sl$BLK (ovl@@sl$TRAIN@@sl$BLK f1 (mk-fun@@sl$TRAIN@@sl$BLK x y))"
, " x2)"
, " (apply@@sl$TRAIN@@sl$BLK f1 x2)))"
, " :pattern"
, " ( (apply@@sl$TRAIN@@sl$BLK (ovl@@sl$TRAIN@@sl$BLK f1 (mk-fun@@sl$TRAIN@@sl$BLK x y))"
, " x2) ))))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK))"
, " (x sl$TRAIN)"
, " (y sl$BLK) )"
, " (! (= (apply@@sl$TRAIN@@sl$BLK (ovl@@sl$TRAIN@@sl$BLK f1 (mk-fun@@sl$TRAIN@@sl$BLK x y))"
, " x)"
, " y)"
, " :pattern"
, " ( (apply@@sl$TRAIN@@sl$BLK (ovl@@sl$TRAIN@@sl$BLK f1 (mk-fun@@sl$TRAIN@@sl$BLK x y))"
, " x) ))))"
, "(assert (= (ran@@sl$TRAIN@@sl$BLK empty-fun@@sl$TRAIN@@sl$BLK)"
, " empty-set@@sl$BLK))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK))"
, " (y sl$BLK) )"
, " (! (= (elem@@sl$BLK y (ran@@sl$TRAIN@@sl$BLK f1))"
, " (exists ( (x sl$TRAIN) )"
, " (and true"
, " (and (elem@@sl$TRAIN x (dom@@sl$TRAIN@@sl$BLK f1))"
, " (= (apply@@sl$TRAIN@@sl$BLK f1 x) y)))))"
, " :pattern"
, " ( (elem@@sl$BLK y (ran@@sl$TRAIN@@sl$BLK f1)) ))))"
, "(assert (forall ( (x sl$TRAIN)"
, " (y sl$BLK) )"
, " (! (= (ran@@sl$TRAIN@@sl$BLK (mk-fun@@sl$TRAIN@@sl$BLK x y))"
, " (mk-set@@sl$BLK y))"
, " :pattern"
, " ( (ran@@sl$TRAIN@@sl$BLK (mk-fun@@sl$TRAIN@@sl$BLK x y)) ))))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK)) )"
, " (! (= (injective@@sl$TRAIN@@sl$BLK f1)"
, " (forall ( (x sl$TRAIN)"
, " (x2 sl$TRAIN) )"
, " (=> (and (elem@@sl$TRAIN x (dom@@sl$TRAIN@@sl$BLK f1))"
, " (elem@@sl$TRAIN x2 (dom@@sl$TRAIN@@sl$BLK f1)))"
, " (=> (= (apply@@sl$TRAIN@@sl$BLK f1 x)"
, " (apply@@sl$TRAIN@@sl$BLK f1 x2))"
, " (= x x2)))))"
, " :pattern"
, " ( (injective@@sl$TRAIN@@sl$BLK f1) ))))"
, "(assert (injective@@sl$TRAIN@@sl$BLK empty-fun@@sl$TRAIN@@sl$BLK))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK))"
, " (x sl$TRAIN) )"
, " (! (=> (elem@@sl$TRAIN x (dom@@sl$TRAIN@@sl$BLK f1))"
, " (elem@@sl$BLK (apply@@sl$TRAIN@@sl$BLK f1 x)"
, " (ran@@sl$TRAIN@@sl$BLK f1)))"
, " :pattern"
, " ( (elem@@sl$BLK (apply@@sl$TRAIN@@sl$BLK f1 x)"
, " (ran@@sl$TRAIN@@sl$BLK f1)) ))))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK))"
, " (s1 (set sl$TRAIN))"
, " (x sl$TRAIN) )"
, " (! (=> (elem@@sl$TRAIN x"
, " (set-diff@@sl$TRAIN (dom@@sl$TRAIN@@sl$BLK f1) s1))"
, " (elem@@sl$BLK (apply@@sl$TRAIN@@sl$BLK f1 x)"
, " (ran@@sl$TRAIN@@sl$BLK (dom-subt@@sl$TRAIN@@sl$BLK s1 f1))))"
, " :pattern"
, " ( (elem@@sl$BLK (apply@@sl$TRAIN@@sl$BLK f1 x)"
, " (ran@@sl$TRAIN@@sl$BLK (dom-subt@@sl$TRAIN@@sl$BLK s1 f1))) ))))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK))"
, " (s1 (set sl$TRAIN))"
, " (x sl$TRAIN) )"
, " (! (=> (elem@@sl$TRAIN x (intersect (dom@@sl$TRAIN@@sl$BLK f1) s1))"
, " (elem@@sl$BLK (apply@@sl$TRAIN@@sl$BLK f1 x)"
, " (ran@@sl$TRAIN@@sl$BLK (dom-rest@@sl$TRAIN@@sl$BLK s1 f1))))"
, " :pattern"
, " ( (elem@@sl$BLK (apply@@sl$TRAIN@@sl$BLK f1 x)"
, " (ran@@sl$TRAIN@@sl$BLK (dom-rest@@sl$TRAIN@@sl$BLK s1 f1))) ))))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK))"
, " (x sl$TRAIN)"
, " (y sl$BLK) )"
, " (! (=> (and (elem@@sl$TRAIN x (dom@@sl$TRAIN@@sl$BLK f1))"
, " (injective@@sl$TRAIN@@sl$BLK f1))"
, " (= (ran@@sl$TRAIN@@sl$BLK (ovl@@sl$TRAIN@@sl$BLK f1 (mk-fun@@sl$TRAIN@@sl$BLK x y)))"
, " (union (set-diff@@sl$BLK (ran@@sl$TRAIN@@sl$BLK f1)"
, " (mk-set@@sl$BLK (apply@@sl$TRAIN@@sl$BLK f1 x)))"
, " (mk-set@@sl$BLK y))))"
, " :pattern"
, " ( (ran@@sl$TRAIN@@sl$BLK (ovl@@sl$TRAIN@@sl$BLK f1 (mk-fun@@sl$TRAIN@@sl$BLK x y))) ))))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK))"
, " (x sl$TRAIN)"
, " (y sl$BLK) )"
, " (! (=> (not (elem@@sl$TRAIN x (dom@@sl$TRAIN@@sl$BLK f1)))"
, " (= (ran@@sl$TRAIN@@sl$BLK (ovl@@sl$TRAIN@@sl$BLK f1 (mk-fun@@sl$TRAIN@@sl$BLK x y)))"
, " (union (ran@@sl$TRAIN@@sl$BLK f1) (mk-set@@sl$BLK y))))"
, " :pattern"
, " ( (ran@@sl$TRAIN@@sl$BLK (ovl@@sl$TRAIN@@sl$BLK f1 (mk-fun@@sl$TRAIN@@sl$BLK x y))) ))))"
, "(assert (forall ( (x sl$BLK)"
, " (y sl$BLK) )"
, " (! (= (elem@@sl$BLK x (mk-set@@sl$BLK y)) (= x y))"
, " :pattern"
, " ( (elem@@sl$BLK x (mk-set@@sl$BLK y)) ))))"
, "(assert (forall ( (x sl$TRAIN)"
, " (y sl$TRAIN) )"
, " (! (= (elem@@sl$TRAIN x (mk-set@@sl$TRAIN y)) (= x y))"
, " :pattern"
, " ( (elem@@sl$TRAIN x (mk-set@@sl$TRAIN y)) ))))"
, "(assert (forall ( (s1 (set sl$BLK))"
, " (s2 (set sl$BLK)) )"
, " (! (=> (finite@@sl$BLK s1)"
, " (finite@@sl$BLK (set-diff@@sl$BLK s1 s2)))"
, " :pattern"
, " ( (finite@@sl$BLK (set-diff@@sl$BLK s1 s2)) ))))"
, "(assert (forall ( (s1 (set sl$LOC))"
, " (s2 (set sl$LOC)) )"
, " (! (=> (finite@@sl$LOC s1)"
, " (finite@@sl$LOC (set-diff@@sl$LOC s1 s2)))"
, " :pattern"
, " ( (finite@@sl$LOC (set-diff@@sl$LOC s1 s2)) ))))"
, "(assert (forall ( (s1 (set sl$TRAIN))"
, " (s2 (set sl$TRAIN)) )"
, " (! (=> (finite@@sl$TRAIN s1)"
, " (finite@@sl$TRAIN (set-diff@@sl$TRAIN s1 s2)))"
, " :pattern"
, " ( (finite@@sl$TRAIN (set-diff@@sl$TRAIN s1 s2)) ))))"
, "(assert (forall ( (s1 (set sl$BLK))"
, " (s2 (set sl$BLK)) )"
, " (! (=> (and (finite@@sl$BLK s1) (finite@@sl$BLK s2))"
, " (finite@@sl$BLK (union s1 s2)))"
, " :pattern"
, " ( (finite@@sl$BLK (union s1 s2)) ))))"
, "(assert (forall ( (s1 (set sl$LOC))"
, " (s2 (set sl$LOC)) )"
, " (! (=> (and (finite@@sl$LOC s1) (finite@@sl$LOC s2))"
, " (finite@@sl$LOC (union s1 s2)))"
, " :pattern"
, " ( (finite@@sl$LOC (union s1 s2)) ))))"
, "(assert (forall ( (s1 (set sl$TRAIN))"
, " (s2 (set sl$TRAIN)) )"
, " (! (=> (and (finite@@sl$TRAIN s1) (finite@@sl$TRAIN s2))"
, " (finite@@sl$TRAIN (union s1 s2)))"
, " :pattern"
, " ( (finite@@sl$TRAIN (union s1 s2)) ))))"
, "(assert (forall ( (s1 (set sl$BLK))"
, " (s2 (set sl$BLK)) )"
, " (! (=> (and (finite@@sl$BLK s2) (not (finite@@sl$BLK s1)))"
, " (not (finite@@sl$BLK (set-diff@@sl$BLK s1 s2))))"
, " :pattern"
, " ( (finite@@sl$BLK (set-diff@@sl$BLK s1 s2)) ))))"
, "(assert (forall ( (s1 (set sl$LOC))"
, " (s2 (set sl$LOC)) )"
, " (! (=> (and (finite@@sl$LOC s2) (not (finite@@sl$LOC s1)))"
, " (not (finite@@sl$LOC (set-diff@@sl$LOC s1 s2))))"
, " :pattern"
, " ( (finite@@sl$LOC (set-diff@@sl$LOC s1 s2)) ))))"
, "(assert (forall ( (s1 (set sl$TRAIN))"
, " (s2 (set sl$TRAIN)) )"
, " (! (=> (and (finite@@sl$TRAIN s2) (not (finite@@sl$TRAIN s1)))"
, " (not (finite@@sl$TRAIN (set-diff@@sl$TRAIN s1 s2))))"
, " :pattern"
, " ( (finite@@sl$TRAIN (set-diff@@sl$TRAIN s1 s2)) ))))"
, "(assert (forall ( (x sl$BLK) )"
, " (! (finite@@sl$BLK (mk-set@@sl$BLK x))"
, " :pattern"
, " ( (finite@@sl$BLK (mk-set@@sl$BLK x)) ))))"
, "(assert (forall ( (x sl$TRAIN) )"
, " (! (finite@@sl$TRAIN (mk-set@@sl$TRAIN x))"
, " :pattern"
, " ( (finite@@sl$TRAIN (mk-set@@sl$TRAIN x)) ))))"
, "(assert (finite@@sl$BLK empty-set@@sl$BLK))"
, "(assert (finite@@sl$LOC empty-set@@sl$LOC))"
, "(assert (finite@@sl$TRAIN empty-set@@sl$TRAIN))"
, "(assert (= t@param t))"
, "; asm2"
, "(assert (and (not (= ent ext))"
, " (not (elem@@sl$BLK ent PLF))"
, " (not (elem@@sl$BLK ext PLF))))"
, "; asm3"
, "(assert (forall ( (p sl$BLK) )"
, " (! (= (not (= p ext))"
, " (elem@@sl$BLK p (union (mk-set@@sl$BLK ent) PLF)))"
, " :pattern"
, " ( (elem@@sl$BLK p (union (mk-set@@sl$BLK ent) PLF)) ))))"
, "; asm4"
, "(assert (forall ( (p sl$BLK) )"
, " (! (= (not (= p ent))"
, " (elem@@sl$BLK p (union (mk-set@@sl$BLK ext) PLF)))"
, " :pattern"
, " ( (elem@@sl$BLK p (union (mk-set@@sl$BLK ext) PLF)) ))))"
, "; asm5"
, "(assert (forall ( (p sl$BLK) )"
, " (! (= (or (= p ent) (= p ext))"
, " (not (elem@@sl$BLK p PLF)))"
, " :pattern"
, " ( (elem@@sl$BLK p PLF) ))))"
, "; axm0"
, "(assert (= sl$BLK"
, " (union (union (mk-set@@sl$BLK ent) (mk-set@@sl$BLK ext))"
, " PLF)))"
, "; inv1"
, "(assert (forall ( (t sl$TRAIN) )"
, " (! (=> (elem@@sl$TRAIN t in)"
, " (elem@@sl$BLK (apply@@sl$TRAIN@@sl$BLK loc t) sl$BLK))"
, " :pattern"
, " ( (elem@@sl$BLK (apply@@sl$TRAIN@@sl$BLK loc t) sl$BLK) ))))"
, "; inv2"
, "(assert (= (dom@@sl$TRAIN@@sl$BLK loc) in))"
, "(assert (not (=> (elem@@sl$TRAIN t in) (elem@@sl$TRAIN t@param in))))"
, "(check-sat-using (or-else (then qe smt)"
, " (then simplify smt)"
, " (then skip smt)"
, " (then (using-params simplify :expand-power true) smt)))"
, "; train0/tr0/TR/leave/EN"
]
case23 :: IO String
case23 = proof_obligation path0 "train0/tr0/TR/leave/EN" 0
result24 :: String
result24 = unlines
[ "; train0/tr0/TR/leave/NEG"
, "(set-option :auto-config false)"
, "(set-option :smt.timeout 3000)"
, "(declare-datatypes (a) ( (Maybe (Just (fromJust a)) Nothing) ))"
, "(declare-datatypes () ( (Null null) ))"
, "(declare-datatypes (a b) ( (Pair (pair (first a) (second b))) ))"
, "(define-sort guarded (a) (Maybe a))"
, "(declare-sort sl$BLK 0)"
, "; comment: we don't need to declare the sort Bool"
, "; comment: we don't need to declare the sort Int"
, "(declare-sort sl$LOC 0)"
, "; comment: we don't need to declare the sort Real"
, "(declare-sort sl$TRAIN 0)"
, "(define-sort pfun (a b) (Array a (Maybe b)))"
, "(define-sort set (a) (Array a Bool))"
, "(declare-const PLF (set sl$BLK))"
, "(declare-const ent sl$BLK)"
, "(declare-const ext sl$BLK)"
, "(declare-const in (set sl$TRAIN))"
, "(declare-const in@prime (set sl$TRAIN))"
, "(declare-const loc (pfun sl$TRAIN sl$BLK))"
, "(declare-const loc@prime (pfun sl$TRAIN sl$BLK))"
, "(declare-const t sl$TRAIN)"
, "(declare-fun apply@@sl$TRAIN@@sl$BLK"
, " ( (pfun sl$TRAIN sl$BLK)"
, " sl$TRAIN )"
, " sl$BLK)"
, "(declare-fun card@@sl$BLK ( (set sl$BLK) ) Int)"
, "(declare-fun card@@sl$LOC ( (set sl$LOC) ) Int)"
, "(declare-fun card@@sl$TRAIN ( (set sl$TRAIN) ) Int)"
, "(declare-fun dom@@sl$TRAIN@@sl$BLK"
, " ( (pfun sl$TRAIN sl$BLK) )"
, " (set sl$TRAIN))"
, "(declare-fun dom-rest@@sl$TRAIN@@sl$BLK"
, " ( (set sl$TRAIN)"
, " (pfun sl$TRAIN sl$BLK) )"
, " (pfun sl$TRAIN sl$BLK))"
, "(declare-fun dom-subt@@sl$TRAIN@@sl$BLK"
, " ( (set sl$TRAIN)"
, " (pfun sl$TRAIN sl$BLK) )"
, " (pfun sl$TRAIN sl$BLK))"
, "(declare-fun empty-fun@@sl$TRAIN@@sl$BLK"
, " ()"
, " (pfun sl$TRAIN sl$BLK))"
, "(declare-fun finite@@sl$BLK ( (set sl$BLK) ) Bool)"
, "(declare-fun finite@@sl$LOC ( (set sl$LOC) ) Bool)"
, "(declare-fun finite@@sl$TRAIN ( (set sl$TRAIN) ) Bool)"
, "(declare-fun injective@@sl$TRAIN@@sl$BLK"
, " ( (pfun sl$TRAIN sl$BLK) )"
, " Bool)"
, "(declare-fun mk-fun@@sl$TRAIN@@sl$BLK"
, " (sl$TRAIN sl$BLK)"
, " (pfun sl$TRAIN sl$BLK))"
, "(declare-fun mk-set@@sl$BLK (sl$BLK) (set sl$BLK))"
, "(declare-fun mk-set@@sl$TRAIN (sl$TRAIN) (set sl$TRAIN))"
, "(declare-fun ovl@@sl$TRAIN@@sl$BLK"
, " ( (pfun sl$TRAIN sl$BLK)"
, " (pfun sl$TRAIN sl$BLK) )"
, " (pfun sl$TRAIN sl$BLK))"
, "(declare-fun ran@@sl$TRAIN@@sl$BLK"
, " ( (pfun sl$TRAIN sl$BLK) )"
, " (set sl$BLK))"
, "(declare-fun t@param () sl$TRAIN)"
, "(define-fun all@@sl$BLK"
, " ()"
, " (set sl$BLK)"
, " ( (as const (set sl$BLK))"
, " true ))"
, "(define-fun all@@sl$LOC"
, " ()"
, " (set sl$LOC)"
, " ( (as const (set sl$LOC))"
, " true ))"
, "(define-fun all@@sl$TRAIN"
, " ()"
, " (set sl$TRAIN)"
, " ( (as const (set sl$TRAIN))"
, " true ))"
, "(define-fun compl@@sl$BLK"
, " ( (s1 (set sl$BLK)) )"
, " (set sl$BLK)"
, " ( (_ map not)"
, " s1 ))"
, "(define-fun compl@@sl$LOC"
, " ( (s1 (set sl$LOC)) )"
, " (set sl$LOC)"
, " ( (_ map not)"
, " s1 ))"
, "(define-fun compl@@sl$TRAIN"
, " ( (s1 (set sl$TRAIN)) )"
, " (set sl$TRAIN)"
, " ( (_ map not)"
, " s1 ))"
, "(define-fun elem@@sl$BLK"
, " ( (x sl$BLK)"
, " (s1 (set sl$BLK)) )"
, " Bool"
, " (select s1 x))"
, "(define-fun elem@@sl$TRAIN"
, " ( (x sl$TRAIN)"
, " (s1 (set sl$TRAIN)) )"
, " Bool"
, " (select s1 x))"
, "(define-fun empty-set@@sl$BLK"
, " ()"
, " (set sl$BLK)"
, " ( (as const (set sl$BLK))"
, " false ))"
, "(define-fun empty-set@@sl$LOC"
, " ()"
, " (set sl$LOC)"
, " ( (as const (set sl$LOC))"
, " false ))"
, "(define-fun empty-set@@sl$TRAIN"
, " ()"
, " (set sl$TRAIN)"
, " ( (as const (set sl$TRAIN))"
, " false ))"
, "(define-fun set-diff@@sl$BLK"
, " ( (s1 (set sl$BLK))"
, " (s2 (set sl$BLK)) )"
, " (set sl$BLK)"
, " (intersect s1 ( (_ map not) s2 )))"
, "(define-fun set-diff@@sl$LOC"
, " ( (s1 (set sl$LOC))"
, " (s2 (set sl$LOC)) )"
, " (set sl$LOC)"
, " (intersect s1 ( (_ map not) s2 )))"
, "(define-fun set-diff@@sl$TRAIN"
, " ( (s1 (set sl$TRAIN))"
, " (s2 (set sl$TRAIN)) )"
, " (set sl$TRAIN)"
, " (intersect s1 ( (_ map not) s2 )))"
, "(define-fun st-subset@@sl$BLK"
, " ( (s1 (set sl$BLK))"
, " (s2 (set sl$BLK)) )"
, " Bool"
, " (and (subset s1 s2) (not (= s1 s2))))"
, "(define-fun st-subset@@sl$LOC"
, " ( (s1 (set sl$LOC))"
, " (s2 (set sl$LOC)) )"
, " Bool"
, " (and (subset s1 s2) (not (= s1 s2))))"
, "(define-fun st-subset@@sl$TRAIN"
, " ( (s1 (set sl$TRAIN))"
, " (s2 (set sl$TRAIN)) )"
, " Bool"
, " (and (subset s1 s2) (not (= s1 s2))))"
, "(define-fun sl$BLK"
, " ()"
, " (set sl$BLK)"
, " ( (as const (set sl$BLK))"
, " true ))"
, "(define-fun sl$LOC"
, " ()"
, " (set sl$LOC)"
, " ( (as const (set sl$LOC))"
, " true ))"
, "(define-fun sl$TRAIN"
, " ()"
, " (set sl$TRAIN)"
, " ( (as const (set sl$TRAIN))"
, " true ))"
, "(assert (forall ( (r (set sl$BLK)) )"
, " (! (=> (finite@@sl$BLK r) (<= 0 (card@@sl$BLK r)))"
, " :pattern"
, " ( (<= 0 (card@@sl$BLK r)) ))))"
, "(assert (forall ( (r (set sl$LOC)) )"
, " (! (=> (finite@@sl$LOC r) (<= 0 (card@@sl$LOC r)))"
, " :pattern"
, " ( (<= 0 (card@@sl$LOC r)) ))))"
, "(assert (forall ( (r (set sl$TRAIN)) )"
, " (! (=> (finite@@sl$TRAIN r) (<= 0 (card@@sl$TRAIN r)))"
, " :pattern"
, " ( (<= 0 (card@@sl$TRAIN r)) ))))"
, "(assert (forall ( (r (set sl$BLK)) )"
, " (! (= (= (card@@sl$BLK r) 0) (= r empty-set@@sl$BLK))"
, " :pattern"
, " ( (card@@sl$BLK r) ))))"
, "(assert (forall ( (r (set sl$LOC)) )"
, " (! (= (= (card@@sl$LOC r) 0) (= r empty-set@@sl$LOC))"
, " :pattern"
, " ( (card@@sl$LOC r) ))))"
, "(assert (forall ( (r (set sl$TRAIN)) )"
, " (! (= (= (card@@sl$TRAIN r) 0)"
, " (= r empty-set@@sl$TRAIN))"
, " :pattern"
, " ( (card@@sl$TRAIN r) ))))"
, "(assert (forall ( (x sl$BLK) )"
, " (! (= (card@@sl$BLK (mk-set@@sl$BLK x)) 1)"
, " :pattern"
, " ( (card@@sl$BLK (mk-set@@sl$BLK x)) ))))"
, "(assert (forall ( (x sl$TRAIN) )"
, " (! (= (card@@sl$TRAIN (mk-set@@sl$TRAIN x)) 1)"
, " :pattern"
, " ( (card@@sl$TRAIN (mk-set@@sl$TRAIN x)) ))))"
, "(assert (forall ( (r (set sl$BLK)) )"
, " (! (= (= (card@@sl$BLK r) 1)"
, " (exists ( (x sl$BLK) ) (and true (= r (mk-set@@sl$BLK x)))))"
, " :pattern"
, " ( (card@@sl$BLK r) ))))"
, "(assert (forall ( (r (set sl$TRAIN)) )"
, " (! (= (= (card@@sl$TRAIN r) 1)"
, " (exists ( (x sl$TRAIN) )"
, " (and true (= r (mk-set@@sl$TRAIN x)))))"
, " :pattern"
, " ( (card@@sl$TRAIN r) ))))"
, "(assert (forall ( (r (set sl$BLK))"
, " (r0 (set sl$BLK)) )"
, " (! (=> (= (intersect r r0) empty-set@@sl$BLK)"
, " (= (card@@sl$BLK (union r r0))"
, " (+ (card@@sl$BLK r) (card@@sl$BLK r0))))"
, " :pattern"
, " ( (card@@sl$BLK (union r r0)) ))))"
, "(assert (forall ( (r (set sl$LOC))"
, " (r0 (set sl$LOC)) )"
, " (! (=> (= (intersect r r0) empty-set@@sl$LOC)"
, " (= (card@@sl$LOC (union r r0))"
, " (+ (card@@sl$LOC r) (card@@sl$LOC r0))))"
, " :pattern"
, " ( (card@@sl$LOC (union r r0)) ))))"
, "(assert (forall ( (r (set sl$TRAIN))"
, " (r0 (set sl$TRAIN)) )"
, " (! (=> (= (intersect r r0) empty-set@@sl$TRAIN)"
, " (= (card@@sl$TRAIN (union r r0))"
, " (+ (card@@sl$TRAIN r) (card@@sl$TRAIN r0))))"
, " :pattern"
, " ( (card@@sl$TRAIN (union r r0)) ))))"
, "(assert (= (dom@@sl$TRAIN@@sl$BLK empty-fun@@sl$TRAIN@@sl$BLK)"
, " empty-set@@sl$TRAIN))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK)) )"
, " (! (= (ovl@@sl$TRAIN@@sl$BLK f1 empty-fun@@sl$TRAIN@@sl$BLK)"
, " f1)"
, " :pattern"
, " ( (ovl@@sl$TRAIN@@sl$BLK f1 empty-fun@@sl$TRAIN@@sl$BLK) ))))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK)) )"
, " (! (= (ovl@@sl$TRAIN@@sl$BLK empty-fun@@sl$TRAIN@@sl$BLK f1)"
, " f1)"
, " :pattern"
, " ( (ovl@@sl$TRAIN@@sl$BLK empty-fun@@sl$TRAIN@@sl$BLK f1) ))))"
, "(assert (forall ( (x sl$TRAIN)"
, " (y sl$BLK) )"
, " (! (= (dom@@sl$TRAIN@@sl$BLK (mk-fun@@sl$TRAIN@@sl$BLK x y))"
, " (mk-set@@sl$TRAIN x))"
, " :pattern"
, " ( (dom@@sl$TRAIN@@sl$BLK (mk-fun@@sl$TRAIN@@sl$BLK x y)) ))))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK))"
, " (f2 (pfun sl$TRAIN sl$BLK))"
, " (x sl$TRAIN) )"
, " (! (=> (elem@@sl$TRAIN x (dom@@sl$TRAIN@@sl$BLK f2))"
, " (= (apply@@sl$TRAIN@@sl$BLK (ovl@@sl$TRAIN@@sl$BLK f1 f2) x)"
, " (apply@@sl$TRAIN@@sl$BLK f2 x)))"
, " :pattern"
, " ( (apply@@sl$TRAIN@@sl$BLK (ovl@@sl$TRAIN@@sl$BLK f1 f2) x) ))))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK))"
, " (f2 (pfun sl$TRAIN sl$BLK))"
, " (x sl$TRAIN) )"
, " (! (=> (and (elem@@sl$TRAIN x (dom@@sl$TRAIN@@sl$BLK f1))"
, " (not (elem@@sl$TRAIN x (dom@@sl$TRAIN@@sl$BLK f2))))"
, " (= (apply@@sl$TRAIN@@sl$BLK (ovl@@sl$TRAIN@@sl$BLK f1 f2) x)"
, " (apply@@sl$TRAIN@@sl$BLK f1 x)))"
, " :pattern"
, " ( (apply@@sl$TRAIN@@sl$BLK (ovl@@sl$TRAIN@@sl$BLK f1 f2) x) ))))"
, "(assert (forall ( (x sl$TRAIN)"
, " (y sl$BLK) )"
, " (! (= (apply@@sl$TRAIN@@sl$BLK (mk-fun@@sl$TRAIN@@sl$BLK x y) x)"
, " y)"
, " :pattern"
, " ( (apply@@sl$TRAIN@@sl$BLK (mk-fun@@sl$TRAIN@@sl$BLK x y) x) ))))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK))"
, " (s1 (set sl$TRAIN))"
, " (x sl$TRAIN) )"
, " (! (=> (and (elem@@sl$TRAIN x s1)"
, " (elem@@sl$TRAIN x (dom@@sl$TRAIN@@sl$BLK f1)))"
, " (= (apply@@sl$TRAIN@@sl$BLK (dom-rest@@sl$TRAIN@@sl$BLK s1 f1) x)"
, " (apply@@sl$TRAIN@@sl$BLK f1 x)))"
, " :pattern"
, " ( (apply@@sl$TRAIN@@sl$BLK (dom-rest@@sl$TRAIN@@sl$BLK s1 f1) x) ))))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK))"
, " (s1 (set sl$TRAIN))"
, " (x sl$TRAIN) )"
, " (! (=> (elem@@sl$TRAIN x"
, " (set-diff@@sl$TRAIN (dom@@sl$TRAIN@@sl$BLK f1) s1))"
, " (= (apply@@sl$TRAIN@@sl$BLK (dom-subt@@sl$TRAIN@@sl$BLK s1 f1) x)"
, " (apply@@sl$TRAIN@@sl$BLK f1 x)))"
, " :pattern"
, " ( (apply@@sl$TRAIN@@sl$BLK (dom-subt@@sl$TRAIN@@sl$BLK s1 f1) x) ))))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK))"
, " (f2 (pfun sl$TRAIN sl$BLK)) )"
, " (! (= (dom@@sl$TRAIN@@sl$BLK (ovl@@sl$TRAIN@@sl$BLK f1 f2))"
, " (union (dom@@sl$TRAIN@@sl$BLK f1)"
, " (dom@@sl$TRAIN@@sl$BLK f2)))"
, " :pattern"
, " ( (dom@@sl$TRAIN@@sl$BLK (ovl@@sl$TRAIN@@sl$BLK f1 f2)) ))))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK))"
, " (s1 (set sl$TRAIN)) )"
, " (! (= (dom@@sl$TRAIN@@sl$BLK (dom-rest@@sl$TRAIN@@sl$BLK s1 f1))"
, " (intersect s1 (dom@@sl$TRAIN@@sl$BLK f1)))"
, " :pattern"
, " ( (dom@@sl$TRAIN@@sl$BLK (dom-rest@@sl$TRAIN@@sl$BLK s1 f1)) ))))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK))"
, " (s1 (set sl$TRAIN)) )"
, " (! (= (dom@@sl$TRAIN@@sl$BLK (dom-subt@@sl$TRAIN@@sl$BLK s1 f1))"
, " (set-diff@@sl$TRAIN (dom@@sl$TRAIN@@sl$BLK f1) s1))"
, " :pattern"
, " ( (dom@@sl$TRAIN@@sl$BLK (dom-subt@@sl$TRAIN@@sl$BLK s1 f1)) ))))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK))"
, " (x sl$TRAIN)"
, " (y sl$BLK) )"
, " (! (= (and (elem@@sl$TRAIN x (dom@@sl$TRAIN@@sl$BLK f1))"
, " (= (apply@@sl$TRAIN@@sl$BLK f1 x) y))"
, " (= (select f1 x) (Just y)))"
, " :pattern"
, " ( (elem@@sl$TRAIN x (dom@@sl$TRAIN@@sl$BLK f1))"
, " (apply@@sl$TRAIN@@sl$BLK f1 x)"
, " (select f1 x)"
, " (Just y) ))))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK))"
, " (x sl$TRAIN)"
, " (x2 sl$TRAIN)"
, " (y sl$BLK) )"
, " (! (=> (not (= x x2))"
, " (= (apply@@sl$TRAIN@@sl$BLK (ovl@@sl$TRAIN@@sl$BLK f1 (mk-fun@@sl$TRAIN@@sl$BLK x y))"
, " x2)"
, " (apply@@sl$TRAIN@@sl$BLK f1 x2)))"
, " :pattern"
, " ( (apply@@sl$TRAIN@@sl$BLK (ovl@@sl$TRAIN@@sl$BLK f1 (mk-fun@@sl$TRAIN@@sl$BLK x y))"
, " x2) ))))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK))"
, " (x sl$TRAIN)"
, " (y sl$BLK) )"
, " (! (= (apply@@sl$TRAIN@@sl$BLK (ovl@@sl$TRAIN@@sl$BLK f1 (mk-fun@@sl$TRAIN@@sl$BLK x y))"
, " x)"
, " y)"
, " :pattern"
, " ( (apply@@sl$TRAIN@@sl$BLK (ovl@@sl$TRAIN@@sl$BLK f1 (mk-fun@@sl$TRAIN@@sl$BLK x y))"
, " x) ))))"
, "(assert (= (ran@@sl$TRAIN@@sl$BLK empty-fun@@sl$TRAIN@@sl$BLK)"
, " empty-set@@sl$BLK))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK))"
, " (y sl$BLK) )"
, " (! (= (elem@@sl$BLK y (ran@@sl$TRAIN@@sl$BLK f1))"
, " (exists ( (x sl$TRAIN) )"
, " (and true"
, " (and (elem@@sl$TRAIN x (dom@@sl$TRAIN@@sl$BLK f1))"
, " (= (apply@@sl$TRAIN@@sl$BLK f1 x) y)))))"
, " :pattern"
, " ( (elem@@sl$BLK y (ran@@sl$TRAIN@@sl$BLK f1)) ))))"
, "(assert (forall ( (x sl$TRAIN)"
, " (y sl$BLK) )"
, " (! (= (ran@@sl$TRAIN@@sl$BLK (mk-fun@@sl$TRAIN@@sl$BLK x y))"
, " (mk-set@@sl$BLK y))"
, " :pattern"
, " ( (ran@@sl$TRAIN@@sl$BLK (mk-fun@@sl$TRAIN@@sl$BLK x y)) ))))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK)) )"
, " (! (= (injective@@sl$TRAIN@@sl$BLK f1)"
, " (forall ( (x sl$TRAIN)"
, " (x2 sl$TRAIN) )"
, " (=> (and (elem@@sl$TRAIN x (dom@@sl$TRAIN@@sl$BLK f1))"
, " (elem@@sl$TRAIN x2 (dom@@sl$TRAIN@@sl$BLK f1)))"
, " (=> (= (apply@@sl$TRAIN@@sl$BLK f1 x)"
, " (apply@@sl$TRAIN@@sl$BLK f1 x2))"
, " (= x x2)))))"
, " :pattern"
, " ( (injective@@sl$TRAIN@@sl$BLK f1) ))))"
, "(assert (injective@@sl$TRAIN@@sl$BLK empty-fun@@sl$TRAIN@@sl$BLK))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK))"
, " (x sl$TRAIN) )"
, " (! (=> (elem@@sl$TRAIN x (dom@@sl$TRAIN@@sl$BLK f1))"
, " (elem@@sl$BLK (apply@@sl$TRAIN@@sl$BLK f1 x)"
, " (ran@@sl$TRAIN@@sl$BLK f1)))"
, " :pattern"
, " ( (elem@@sl$BLK (apply@@sl$TRAIN@@sl$BLK f1 x)"
, " (ran@@sl$TRAIN@@sl$BLK f1)) ))))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK))"
, " (s1 (set sl$TRAIN))"
, " (x sl$TRAIN) )"
, " (! (=> (elem@@sl$TRAIN x"
, " (set-diff@@sl$TRAIN (dom@@sl$TRAIN@@sl$BLK f1) s1))"
, " (elem@@sl$BLK (apply@@sl$TRAIN@@sl$BLK f1 x)"
, " (ran@@sl$TRAIN@@sl$BLK (dom-subt@@sl$TRAIN@@sl$BLK s1 f1))))"
, " :pattern"
, " ( (elem@@sl$BLK (apply@@sl$TRAIN@@sl$BLK f1 x)"
, " (ran@@sl$TRAIN@@sl$BLK (dom-subt@@sl$TRAIN@@sl$BLK s1 f1))) ))))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK))"
, " (s1 (set sl$TRAIN))"
, " (x sl$TRAIN) )"
, " (! (=> (elem@@sl$TRAIN x (intersect (dom@@sl$TRAIN@@sl$BLK f1) s1))"
, " (elem@@sl$BLK (apply@@sl$TRAIN@@sl$BLK f1 x)"
, " (ran@@sl$TRAIN@@sl$BLK (dom-rest@@sl$TRAIN@@sl$BLK s1 f1))))"
, " :pattern"
, " ( (elem@@sl$BLK (apply@@sl$TRAIN@@sl$BLK f1 x)"
, " (ran@@sl$TRAIN@@sl$BLK (dom-rest@@sl$TRAIN@@sl$BLK s1 f1))) ))))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK))"
, " (x sl$TRAIN)"
, " (y sl$BLK) )"
, " (! (=> (and (elem@@sl$TRAIN x (dom@@sl$TRAIN@@sl$BLK f1))"
, " (injective@@sl$TRAIN@@sl$BLK f1))"
, " (= (ran@@sl$TRAIN@@sl$BLK (ovl@@sl$TRAIN@@sl$BLK f1 (mk-fun@@sl$TRAIN@@sl$BLK x y)))"
, " (union (set-diff@@sl$BLK (ran@@sl$TRAIN@@sl$BLK f1)"
, " (mk-set@@sl$BLK (apply@@sl$TRAIN@@sl$BLK f1 x)))"
, " (mk-set@@sl$BLK y))))"
, " :pattern"
, " ( (ran@@sl$TRAIN@@sl$BLK (ovl@@sl$TRAIN@@sl$BLK f1 (mk-fun@@sl$TRAIN@@sl$BLK x y))) ))))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK))"
, " (x sl$TRAIN)"
, " (y sl$BLK) )"
, " (! (=> (not (elem@@sl$TRAIN x (dom@@sl$TRAIN@@sl$BLK f1)))"
, " (= (ran@@sl$TRAIN@@sl$BLK (ovl@@sl$TRAIN@@sl$BLK f1 (mk-fun@@sl$TRAIN@@sl$BLK x y)))"
, " (union (ran@@sl$TRAIN@@sl$BLK f1) (mk-set@@sl$BLK y))))"
, " :pattern"
, " ( (ran@@sl$TRAIN@@sl$BLK (ovl@@sl$TRAIN@@sl$BLK f1 (mk-fun@@sl$TRAIN@@sl$BLK x y))) ))))"
, "(assert (forall ( (x sl$BLK)"
, " (y sl$BLK) )"
, " (! (= (elem@@sl$BLK x (mk-set@@sl$BLK y)) (= x y))"
, " :pattern"
, " ( (elem@@sl$BLK x (mk-set@@sl$BLK y)) ))))"
, "(assert (forall ( (x sl$TRAIN)"
, " (y sl$TRAIN) )"
, " (! (= (elem@@sl$TRAIN x (mk-set@@sl$TRAIN y)) (= x y))"
, " :pattern"
, " ( (elem@@sl$TRAIN x (mk-set@@sl$TRAIN y)) ))))"
, "(assert (forall ( (s1 (set sl$BLK))"
, " (s2 (set sl$BLK)) )"
, " (! (=> (finite@@sl$BLK s1)"
, " (finite@@sl$BLK (set-diff@@sl$BLK s1 s2)))"
, " :pattern"
, " ( (finite@@sl$BLK (set-diff@@sl$BLK s1 s2)) ))))"
, "(assert (forall ( (s1 (set sl$LOC))"
, " (s2 (set sl$LOC)) )"
, " (! (=> (finite@@sl$LOC s1)"
, " (finite@@sl$LOC (set-diff@@sl$LOC s1 s2)))"
, " :pattern"
, " ( (finite@@sl$LOC (set-diff@@sl$LOC s1 s2)) ))))"
, "(assert (forall ( (s1 (set sl$TRAIN))"
, " (s2 (set sl$TRAIN)) )"
, " (! (=> (finite@@sl$TRAIN s1)"
, " (finite@@sl$TRAIN (set-diff@@sl$TRAIN s1 s2)))"
, " :pattern"
, " ( (finite@@sl$TRAIN (set-diff@@sl$TRAIN s1 s2)) ))))"
, "(assert (forall ( (s1 (set sl$BLK))"
, " (s2 (set sl$BLK)) )"
, " (! (=> (and (finite@@sl$BLK s1) (finite@@sl$BLK s2))"
, " (finite@@sl$BLK (union s1 s2)))"
, " :pattern"
, " ( (finite@@sl$BLK (union s1 s2)) ))))"
, "(assert (forall ( (s1 (set sl$LOC))"
, " (s2 (set sl$LOC)) )"
, " (! (=> (and (finite@@sl$LOC s1) (finite@@sl$LOC s2))"
, " (finite@@sl$LOC (union s1 s2)))"
, " :pattern"
, " ( (finite@@sl$LOC (union s1 s2)) ))))"
, "(assert (forall ( (s1 (set sl$TRAIN))"
, " (s2 (set sl$TRAIN)) )"
, " (! (=> (and (finite@@sl$TRAIN s1) (finite@@sl$TRAIN s2))"
, " (finite@@sl$TRAIN (union s1 s2)))"
, " :pattern"
, " ( (finite@@sl$TRAIN (union s1 s2)) ))))"
, "(assert (forall ( (s1 (set sl$BLK))"
, " (s2 (set sl$BLK)) )"
, " (! (=> (and (finite@@sl$BLK s2) (not (finite@@sl$BLK s1)))"
, " (not (finite@@sl$BLK (set-diff@@sl$BLK s1 s2))))"
, " :pattern"
, " ( (finite@@sl$BLK (set-diff@@sl$BLK s1 s2)) ))))"
, "(assert (forall ( (s1 (set sl$LOC))"
, " (s2 (set sl$LOC)) )"
, " (! (=> (and (finite@@sl$LOC s2) (not (finite@@sl$LOC s1)))"
, " (not (finite@@sl$LOC (set-diff@@sl$LOC s1 s2))))"
, " :pattern"
, " ( (finite@@sl$LOC (set-diff@@sl$LOC s1 s2)) ))))"
, "(assert (forall ( (s1 (set sl$TRAIN))"
, " (s2 (set sl$TRAIN)) )"
, " (! (=> (and (finite@@sl$TRAIN s2) (not (finite@@sl$TRAIN s1)))"
, " (not (finite@@sl$TRAIN (set-diff@@sl$TRAIN s1 s2))))"
, " :pattern"
, " ( (finite@@sl$TRAIN (set-diff@@sl$TRAIN s1 s2)) ))))"
, "(assert (forall ( (x sl$BLK) )"
, " (! (finite@@sl$BLK (mk-set@@sl$BLK x))"
, " :pattern"
, " ( (finite@@sl$BLK (mk-set@@sl$BLK x)) ))))"
, "(assert (forall ( (x sl$TRAIN) )"
, " (! (finite@@sl$TRAIN (mk-set@@sl$TRAIN x))"
, " :pattern"
, " ( (finite@@sl$TRAIN (mk-set@@sl$TRAIN x)) ))))"
, "(assert (finite@@sl$BLK empty-set@@sl$BLK))"
, "(assert (finite@@sl$LOC empty-set@@sl$LOC))"
, "(assert (finite@@sl$TRAIN empty-set@@sl$TRAIN))"
, "(assert (= t@param t))"
, "; a0"
, "(assert (= in@prime"
, " (set-diff@@sl$TRAIN in (mk-set@@sl$TRAIN t@param))))"
, "; a3"
, "(assert (= loc@prime"
, " (dom-subt@@sl$TRAIN@@sl$BLK (mk-set@@sl$TRAIN t@param) loc)))"
, "; asm2"
, "(assert (and (not (= ent ext))"
, " (not (elem@@sl$BLK ent PLF))"
, " (not (elem@@sl$BLK ext PLF))))"
, "; asm3"
, "(assert (forall ( (p sl$BLK) )"
, " (! (= (not (= p ext))"
, " (elem@@sl$BLK p (union (mk-set@@sl$BLK ent) PLF)))"
, " :pattern"
, " ( (elem@@sl$BLK p (union (mk-set@@sl$BLK ent) PLF)) ))))"
, "; asm4"
, "(assert (forall ( (p sl$BLK) )"
, " (! (= (not (= p ent))"
, " (elem@@sl$BLK p (union (mk-set@@sl$BLK ext) PLF)))"
, " :pattern"
, " ( (elem@@sl$BLK p (union (mk-set@@sl$BLK ext) PLF)) ))))"
, "; asm5"
, "(assert (forall ( (p sl$BLK) )"
, " (! (= (or (= p ent) (= p ext))"
, " (not (elem@@sl$BLK p PLF)))"
, " :pattern"
, " ( (elem@@sl$BLK p PLF) ))))"
, "; axm0"
, "(assert (= sl$BLK"
, " (union (union (mk-set@@sl$BLK ent) (mk-set@@sl$BLK ext))"
, " PLF)))"
, "; c0"
, "(assert (elem@@sl$TRAIN t@param in))"
, "; grd0"
, "(assert (and (= (apply@@sl$TRAIN@@sl$BLK loc t@param) ext)"
, " (elem@@sl$TRAIN t@param in)))"
, "; inv1"
, "(assert (forall ( (t sl$TRAIN) )"
, " (! (=> (elem@@sl$TRAIN t in)"
, " (elem@@sl$BLK (apply@@sl$TRAIN@@sl$BLK loc t) sl$BLK))"
, " :pattern"
, " ( (elem@@sl$BLK (apply@@sl$TRAIN@@sl$BLK loc t) sl$BLK) ))))"
, "; inv2"
, "(assert (= (dom@@sl$TRAIN@@sl$BLK loc) in))"
, "(assert (not (=> (elem@@sl$TRAIN t in)"
, " (not (elem@@sl$TRAIN t in@prime)))))"
, "(check-sat-using (or-else (then qe smt)"
, " (then simplify smt)"
, " (then skip smt)"
, " (then (using-params simplify :expand-power true) smt)))"
, "; train0/tr0/TR/leave/NEG"
]
case24 :: IO String
case24 = proof_obligation path0 "train0/tr0/TR/leave/NEG" 0
result12 :: String
result12 = unlines
[ "; train0/leave/INV/inv2"
, "(set-option :auto-config false)"
, "(set-option :smt.timeout 3000)"
, "(declare-datatypes (a) ( (Maybe (Just (fromJust a)) Nothing) ))"
, "(declare-datatypes () ( (Null null) ))"
, "(declare-datatypes (a b) ( (Pair (pair (first a) (second b))) ))"
, "(define-sort guarded (a) (Maybe a))"
, "(declare-sort sl$BLK 0)"
, "; comment: we don't need to declare the sort Bool"
, "; comment: we don't need to declare the sort Int"
, "(declare-sort sl$LOC 0)"
, "; comment: we don't need to declare the sort Real"
, "(declare-sort sl$TRAIN 0)"
, "(define-sort pfun (a b) (Array a (Maybe b)))"
, "(define-sort set (a) (Array a Bool))"
, "(declare-const PLF (set sl$BLK))"
, "(declare-const ent sl$BLK)"
, "(declare-const ext sl$BLK)"
, "(declare-const in (set sl$TRAIN))"
, "(declare-const in@prime (set sl$TRAIN))"
, "(declare-const loc (pfun sl$TRAIN sl$BLK))"
, "(declare-const loc@prime (pfun sl$TRAIN sl$BLK))"
, "(declare-const t sl$TRAIN)"
, "(declare-fun apply@@sl$TRAIN@@sl$BLK"
, " ( (pfun sl$TRAIN sl$BLK)"
, " sl$TRAIN )"
, " sl$BLK)"
, "(declare-fun card@@sl$BLK ( (set sl$BLK) ) Int)"
, "(declare-fun card@@sl$LOC ( (set sl$LOC) ) Int)"
, "(declare-fun card@@sl$TRAIN ( (set sl$TRAIN) ) Int)"
, "(declare-fun dom@@sl$TRAIN@@sl$BLK"
, " ( (pfun sl$TRAIN sl$BLK) )"
, " (set sl$TRAIN))"
, "(declare-fun dom-rest@@sl$TRAIN@@sl$BLK"
, " ( (set sl$TRAIN)"
, " (pfun sl$TRAIN sl$BLK) )"
, " (pfun sl$TRAIN sl$BLK))"
, "(declare-fun dom-subt@@sl$TRAIN@@sl$BLK"
, " ( (set sl$TRAIN)"
, " (pfun sl$TRAIN sl$BLK) )"
, " (pfun sl$TRAIN sl$BLK))"
, "(declare-fun empty-fun@@sl$TRAIN@@sl$BLK"
, " ()"
, " (pfun sl$TRAIN sl$BLK))"
, "(declare-fun finite@@sl$BLK ( (set sl$BLK) ) Bool)"
, "(declare-fun finite@@sl$LOC ( (set sl$LOC) ) Bool)"
, "(declare-fun finite@@sl$TRAIN ( (set sl$TRAIN) ) Bool)"
, "(declare-fun injective@@sl$TRAIN@@sl$BLK"
, " ( (pfun sl$TRAIN sl$BLK) )"
, " Bool)"
, "(declare-fun mk-fun@@sl$TRAIN@@sl$BLK"
, " (sl$TRAIN sl$BLK)"
, " (pfun sl$TRAIN sl$BLK))"
, "(declare-fun mk-set@@sl$BLK (sl$BLK) (set sl$BLK))"
, "(declare-fun mk-set@@sl$TRAIN (sl$TRAIN) (set sl$TRAIN))"
, "(declare-fun ovl@@sl$TRAIN@@sl$BLK"
, " ( (pfun sl$TRAIN sl$BLK)"
, " (pfun sl$TRAIN sl$BLK) )"
, " (pfun sl$TRAIN sl$BLK))"
, "(declare-fun ran@@sl$TRAIN@@sl$BLK"
, " ( (pfun sl$TRAIN sl$BLK) )"
, " (set sl$BLK))"
, "(define-fun all@@sl$BLK"
, " ()"
, " (set sl$BLK)"
, " ( (as const (set sl$BLK))"
, " true ))"
, "(define-fun all@@sl$LOC"
, " ()"
, " (set sl$LOC)"
, " ( (as const (set sl$LOC))"
, " true ))"
, "(define-fun all@@sl$TRAIN"
, " ()"
, " (set sl$TRAIN)"
, " ( (as const (set sl$TRAIN))"
, " true ))"
, "(define-fun compl@@sl$BLK"
, " ( (s1 (set sl$BLK)) )"
, " (set sl$BLK)"
, " ( (_ map not)"
, " s1 ))"
, "(define-fun compl@@sl$LOC"
, " ( (s1 (set sl$LOC)) )"
, " (set sl$LOC)"
, " ( (_ map not)"
, " s1 ))"
, "(define-fun compl@@sl$TRAIN"
, " ( (s1 (set sl$TRAIN)) )"
, " (set sl$TRAIN)"
, " ( (_ map not)"
, " s1 ))"
, "(define-fun elem@@sl$BLK"
, " ( (x sl$BLK)"
, " (s1 (set sl$BLK)) )"
, " Bool"
, " (select s1 x))"
, "(define-fun elem@@sl$TRAIN"
, " ( (x sl$TRAIN)"
, " (s1 (set sl$TRAIN)) )"
, " Bool"
, " (select s1 x))"
, "(define-fun empty-set@@sl$BLK"
, " ()"
, " (set sl$BLK)"
, " ( (as const (set sl$BLK))"
, " false ))"
, "(define-fun empty-set@@sl$LOC"
, " ()"
, " (set sl$LOC)"
, " ( (as const (set sl$LOC))"
, " false ))"
, "(define-fun empty-set@@sl$TRAIN"
, " ()"
, " (set sl$TRAIN)"
, " ( (as const (set sl$TRAIN))"
, " false ))"
, "(define-fun set-diff@@sl$BLK"
, " ( (s1 (set sl$BLK))"
, " (s2 (set sl$BLK)) )"
, " (set sl$BLK)"
, " (intersect s1 ( (_ map not) s2 )))"
, "(define-fun set-diff@@sl$LOC"
, " ( (s1 (set sl$LOC))"
, " (s2 (set sl$LOC)) )"
, " (set sl$LOC)"
, " (intersect s1 ( (_ map not) s2 )))"
, "(define-fun set-diff@@sl$TRAIN"
, " ( (s1 (set sl$TRAIN))"
, " (s2 (set sl$TRAIN)) )"
, " (set sl$TRAIN)"
, " (intersect s1 ( (_ map not) s2 )))"
, "(define-fun st-subset@@sl$BLK"
, " ( (s1 (set sl$BLK))"
, " (s2 (set sl$BLK)) )"
, " Bool"
, " (and (subset s1 s2) (not (= s1 s2))))"
, "(define-fun st-subset@@sl$LOC"
, " ( (s1 (set sl$LOC))"
, " (s2 (set sl$LOC)) )"
, " Bool"
, " (and (subset s1 s2) (not (= s1 s2))))"
, "(define-fun st-subset@@sl$TRAIN"
, " ( (s1 (set sl$TRAIN))"
, " (s2 (set sl$TRAIN)) )"
, " Bool"
, " (and (subset s1 s2) (not (= s1 s2))))"
, "(define-fun sl$BLK"
, " ()"
, " (set sl$BLK)"
, " ( (as const (set sl$BLK))"
, " true ))"
, "(define-fun sl$LOC"
, " ()"
, " (set sl$LOC)"
, " ( (as const (set sl$LOC))"
, " true ))"
, "(define-fun sl$TRAIN"
, " ()"
, " (set sl$TRAIN)"
, " ( (as const (set sl$TRAIN))"
, " true ))"
, "(assert (forall ( (r (set sl$BLK)) )"
, " (! (=> (finite@@sl$BLK r) (<= 0 (card@@sl$BLK r)))"
, " :pattern"
, " ( (<= 0 (card@@sl$BLK r)) ))))"
, "(assert (forall ( (r (set sl$LOC)) )"
, " (! (=> (finite@@sl$LOC r) (<= 0 (card@@sl$LOC r)))"
, " :pattern"
, " ( (<= 0 (card@@sl$LOC r)) ))))"
, "(assert (forall ( (r (set sl$TRAIN)) )"
, " (! (=> (finite@@sl$TRAIN r) (<= 0 (card@@sl$TRAIN r)))"
, " :pattern"
, " ( (<= 0 (card@@sl$TRAIN r)) ))))"
, "(assert (forall ( (r (set sl$BLK)) )"
, " (! (= (= (card@@sl$BLK r) 0) (= r empty-set@@sl$BLK))"
, " :pattern"
, " ( (card@@sl$BLK r) ))))"
, "(assert (forall ( (r (set sl$LOC)) )"
, " (! (= (= (card@@sl$LOC r) 0) (= r empty-set@@sl$LOC))"
, " :pattern"
, " ( (card@@sl$LOC r) ))))"
, "(assert (forall ( (r (set sl$TRAIN)) )"
, " (! (= (= (card@@sl$TRAIN r) 0)"
, " (= r empty-set@@sl$TRAIN))"
, " :pattern"
, " ( (card@@sl$TRAIN r) ))))"
, "(assert (forall ( (x sl$BLK) )"
, " (! (= (card@@sl$BLK (mk-set@@sl$BLK x)) 1)"
, " :pattern"
, " ( (card@@sl$BLK (mk-set@@sl$BLK x)) ))))"
, "(assert (forall ( (x sl$TRAIN) )"
, " (! (= (card@@sl$TRAIN (mk-set@@sl$TRAIN x)) 1)"
, " :pattern"
, " ( (card@@sl$TRAIN (mk-set@@sl$TRAIN x)) ))))"
, "(assert (forall ( (r (set sl$BLK)) )"
, " (! (= (= (card@@sl$BLK r) 1)"
, " (exists ( (x sl$BLK) ) (and true (= r (mk-set@@sl$BLK x)))))"
, " :pattern"
, " ( (card@@sl$BLK r) ))))"
, "(assert (forall ( (r (set sl$TRAIN)) )"
, " (! (= (= (card@@sl$TRAIN r) 1)"
, " (exists ( (x sl$TRAIN) )"
, " (and true (= r (mk-set@@sl$TRAIN x)))))"
, " :pattern"
, " ( (card@@sl$TRAIN r) ))))"
, "(assert (forall ( (r (set sl$BLK))"
, " (r0 (set sl$BLK)) )"
, " (! (=> (= (intersect r r0) empty-set@@sl$BLK)"
, " (= (card@@sl$BLK (union r r0))"
, " (+ (card@@sl$BLK r) (card@@sl$BLK r0))))"
, " :pattern"
, " ( (card@@sl$BLK (union r r0)) ))))"
, "(assert (forall ( (r (set sl$LOC))"
, " (r0 (set sl$LOC)) )"
, " (! (=> (= (intersect r r0) empty-set@@sl$LOC)"
, " (= (card@@sl$LOC (union r r0))"
, " (+ (card@@sl$LOC r) (card@@sl$LOC r0))))"
, " :pattern"
, " ( (card@@sl$LOC (union r r0)) ))))"
, "(assert (forall ( (r (set sl$TRAIN))"
, " (r0 (set sl$TRAIN)) )"
, " (! (=> (= (intersect r r0) empty-set@@sl$TRAIN)"
, " (= (card@@sl$TRAIN (union r r0))"
, " (+ (card@@sl$TRAIN r) (card@@sl$TRAIN r0))))"
, " :pattern"
, " ( (card@@sl$TRAIN (union r r0)) ))))"
, "(assert (= (dom@@sl$TRAIN@@sl$BLK empty-fun@@sl$TRAIN@@sl$BLK)"
, " empty-set@@sl$TRAIN))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK)) )"
, " (! (= (ovl@@sl$TRAIN@@sl$BLK f1 empty-fun@@sl$TRAIN@@sl$BLK)"
, " f1)"
, " :pattern"
, " ( (ovl@@sl$TRAIN@@sl$BLK f1 empty-fun@@sl$TRAIN@@sl$BLK) ))))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK)) )"
, " (! (= (ovl@@sl$TRAIN@@sl$BLK empty-fun@@sl$TRAIN@@sl$BLK f1)"
, " f1)"
, " :pattern"
, " ( (ovl@@sl$TRAIN@@sl$BLK empty-fun@@sl$TRAIN@@sl$BLK f1) ))))"
, "(assert (forall ( (x sl$TRAIN)"
, " (y sl$BLK) )"
, " (! (= (dom@@sl$TRAIN@@sl$BLK (mk-fun@@sl$TRAIN@@sl$BLK x y))"
, " (mk-set@@sl$TRAIN x))"
, " :pattern"
, " ( (dom@@sl$TRAIN@@sl$BLK (mk-fun@@sl$TRAIN@@sl$BLK x y)) ))))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK))"
, " (f2 (pfun sl$TRAIN sl$BLK))"
, " (x sl$TRAIN) )"
, " (! (=> (elem@@sl$TRAIN x (dom@@sl$TRAIN@@sl$BLK f2))"
, " (= (apply@@sl$TRAIN@@sl$BLK (ovl@@sl$TRAIN@@sl$BLK f1 f2) x)"
, " (apply@@sl$TRAIN@@sl$BLK f2 x)))"
, " :pattern"
, " ( (apply@@sl$TRAIN@@sl$BLK (ovl@@sl$TRAIN@@sl$BLK f1 f2) x) ))))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK))"
, " (f2 (pfun sl$TRAIN sl$BLK))"
, " (x sl$TRAIN) )"
, " (! (=> (and (elem@@sl$TRAIN x (dom@@sl$TRAIN@@sl$BLK f1))"
, " (not (elem@@sl$TRAIN x (dom@@sl$TRAIN@@sl$BLK f2))))"
, " (= (apply@@sl$TRAIN@@sl$BLK (ovl@@sl$TRAIN@@sl$BLK f1 f2) x)"
, " (apply@@sl$TRAIN@@sl$BLK f1 x)))"
, " :pattern"
, " ( (apply@@sl$TRAIN@@sl$BLK (ovl@@sl$TRAIN@@sl$BLK f1 f2) x) ))))"
, "(assert (forall ( (x sl$TRAIN)"
, " (y sl$BLK) )"
, " (! (= (apply@@sl$TRAIN@@sl$BLK (mk-fun@@sl$TRAIN@@sl$BLK x y) x)"
, " y)"
, " :pattern"
, " ( (apply@@sl$TRAIN@@sl$BLK (mk-fun@@sl$TRAIN@@sl$BLK x y) x) ))))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK))"
, " (s1 (set sl$TRAIN))"
, " (x sl$TRAIN) )"
, " (! (=> (and (elem@@sl$TRAIN x s1)"
, " (elem@@sl$TRAIN x (dom@@sl$TRAIN@@sl$BLK f1)))"
, " (= (apply@@sl$TRAIN@@sl$BLK (dom-rest@@sl$TRAIN@@sl$BLK s1 f1) x)"
, " (apply@@sl$TRAIN@@sl$BLK f1 x)))"
, " :pattern"
, " ( (apply@@sl$TRAIN@@sl$BLK (dom-rest@@sl$TRAIN@@sl$BLK s1 f1) x) ))))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK))"
, " (s1 (set sl$TRAIN))"
, " (x sl$TRAIN) )"
, " (! (=> (elem@@sl$TRAIN x"
, " (set-diff@@sl$TRAIN (dom@@sl$TRAIN@@sl$BLK f1) s1))"
, " (= (apply@@sl$TRAIN@@sl$BLK (dom-subt@@sl$TRAIN@@sl$BLK s1 f1) x)"
, " (apply@@sl$TRAIN@@sl$BLK f1 x)))"
, " :pattern"
, " ( (apply@@sl$TRAIN@@sl$BLK (dom-subt@@sl$TRAIN@@sl$BLK s1 f1) x) ))))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK))"
, " (f2 (pfun sl$TRAIN sl$BLK)) )"
, " (! (= (dom@@sl$TRAIN@@sl$BLK (ovl@@sl$TRAIN@@sl$BLK f1 f2))"
, " (union (dom@@sl$TRAIN@@sl$BLK f1)"
, " (dom@@sl$TRAIN@@sl$BLK f2)))"
, " :pattern"
, " ( (dom@@sl$TRAIN@@sl$BLK (ovl@@sl$TRAIN@@sl$BLK f1 f2)) ))))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK))"
, " (s1 (set sl$TRAIN)) )"
, " (! (= (dom@@sl$TRAIN@@sl$BLK (dom-rest@@sl$TRAIN@@sl$BLK s1 f1))"
, " (intersect s1 (dom@@sl$TRAIN@@sl$BLK f1)))"
, " :pattern"
, " ( (dom@@sl$TRAIN@@sl$BLK (dom-rest@@sl$TRAIN@@sl$BLK s1 f1)) ))))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK))"
, " (s1 (set sl$TRAIN)) )"
, " (! (= (dom@@sl$TRAIN@@sl$BLK (dom-subt@@sl$TRAIN@@sl$BLK s1 f1))"
, " (set-diff@@sl$TRAIN (dom@@sl$TRAIN@@sl$BLK f1) s1))"
, " :pattern"
, " ( (dom@@sl$TRAIN@@sl$BLK (dom-subt@@sl$TRAIN@@sl$BLK s1 f1)) ))))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK))"
, " (x sl$TRAIN)"
, " (y sl$BLK) )"
, " (! (= (and (elem@@sl$TRAIN x (dom@@sl$TRAIN@@sl$BLK f1))"
, " (= (apply@@sl$TRAIN@@sl$BLK f1 x) y))"
, " (= (select f1 x) (Just y)))"
, " :pattern"
, " ( (elem@@sl$TRAIN x (dom@@sl$TRAIN@@sl$BLK f1))"
, " (apply@@sl$TRAIN@@sl$BLK f1 x)"
, " (select f1 x)"
, " (Just y) ))))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK))"
, " (x sl$TRAIN)"
, " (x2 sl$TRAIN)"
, " (y sl$BLK) )"
, " (! (=> (not (= x x2))"
, " (= (apply@@sl$TRAIN@@sl$BLK (ovl@@sl$TRAIN@@sl$BLK f1 (mk-fun@@sl$TRAIN@@sl$BLK x y))"
, " x2)"
, " (apply@@sl$TRAIN@@sl$BLK f1 x2)))"
, " :pattern"
, " ( (apply@@sl$TRAIN@@sl$BLK (ovl@@sl$TRAIN@@sl$BLK f1 (mk-fun@@sl$TRAIN@@sl$BLK x y))"
, " x2) ))))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK))"
, " (x sl$TRAIN)"
, " (y sl$BLK) )"
, " (! (= (apply@@sl$TRAIN@@sl$BLK (ovl@@sl$TRAIN@@sl$BLK f1 (mk-fun@@sl$TRAIN@@sl$BLK x y))"
, " x)"
, " y)"
, " :pattern"
, " ( (apply@@sl$TRAIN@@sl$BLK (ovl@@sl$TRAIN@@sl$BLK f1 (mk-fun@@sl$TRAIN@@sl$BLK x y))"
, " x) ))))"
, "(assert (= (ran@@sl$TRAIN@@sl$BLK empty-fun@@sl$TRAIN@@sl$BLK)"
, " empty-set@@sl$BLK))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK))"
, " (y sl$BLK) )"
, " (! (= (elem@@sl$BLK y (ran@@sl$TRAIN@@sl$BLK f1))"
, " (exists ( (x sl$TRAIN) )"
, " (and true"
, " (and (elem@@sl$TRAIN x (dom@@sl$TRAIN@@sl$BLK f1))"
, " (= (apply@@sl$TRAIN@@sl$BLK f1 x) y)))))"
, " :pattern"
, " ( (elem@@sl$BLK y (ran@@sl$TRAIN@@sl$BLK f1)) ))))"
, "(assert (forall ( (x sl$TRAIN)"
, " (y sl$BLK) )"
, " (! (= (ran@@sl$TRAIN@@sl$BLK (mk-fun@@sl$TRAIN@@sl$BLK x y))"
, " (mk-set@@sl$BLK y))"
, " :pattern"
, " ( (ran@@sl$TRAIN@@sl$BLK (mk-fun@@sl$TRAIN@@sl$BLK x y)) ))))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK)) )"
, " (! (= (injective@@sl$TRAIN@@sl$BLK f1)"
, " (forall ( (x sl$TRAIN)"
, " (x2 sl$TRAIN) )"
, " (=> (and (elem@@sl$TRAIN x (dom@@sl$TRAIN@@sl$BLK f1))"
, " (elem@@sl$TRAIN x2 (dom@@sl$TRAIN@@sl$BLK f1)))"
, " (=> (= (apply@@sl$TRAIN@@sl$BLK f1 x)"
, " (apply@@sl$TRAIN@@sl$BLK f1 x2))"
, " (= x x2)))))"
, " :pattern"
, " ( (injective@@sl$TRAIN@@sl$BLK f1) ))))"
, "(assert (injective@@sl$TRAIN@@sl$BLK empty-fun@@sl$TRAIN@@sl$BLK))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK))"
, " (x sl$TRAIN) )"
, " (! (=> (elem@@sl$TRAIN x (dom@@sl$TRAIN@@sl$BLK f1))"
, " (elem@@sl$BLK (apply@@sl$TRAIN@@sl$BLK f1 x)"
, " (ran@@sl$TRAIN@@sl$BLK f1)))"
, " :pattern"
, " ( (elem@@sl$BLK (apply@@sl$TRAIN@@sl$BLK f1 x)"
, " (ran@@sl$TRAIN@@sl$BLK f1)) ))))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK))"
, " (s1 (set sl$TRAIN))"
, " (x sl$TRAIN) )"
, " (! (=> (elem@@sl$TRAIN x"
, " (set-diff@@sl$TRAIN (dom@@sl$TRAIN@@sl$BLK f1) s1))"
, " (elem@@sl$BLK (apply@@sl$TRAIN@@sl$BLK f1 x)"
, " (ran@@sl$TRAIN@@sl$BLK (dom-subt@@sl$TRAIN@@sl$BLK s1 f1))))"
, " :pattern"
, " ( (elem@@sl$BLK (apply@@sl$TRAIN@@sl$BLK f1 x)"
, " (ran@@sl$TRAIN@@sl$BLK (dom-subt@@sl$TRAIN@@sl$BLK s1 f1))) ))))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK))"
, " (s1 (set sl$TRAIN))"
, " (x sl$TRAIN) )"
, " (! (=> (elem@@sl$TRAIN x (intersect (dom@@sl$TRAIN@@sl$BLK f1) s1))"
, " (elem@@sl$BLK (apply@@sl$TRAIN@@sl$BLK f1 x)"
, " (ran@@sl$TRAIN@@sl$BLK (dom-rest@@sl$TRAIN@@sl$BLK s1 f1))))"
, " :pattern"
, " ( (elem@@sl$BLK (apply@@sl$TRAIN@@sl$BLK f1 x)"
, " (ran@@sl$TRAIN@@sl$BLK (dom-rest@@sl$TRAIN@@sl$BLK s1 f1))) ))))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK))"
, " (x sl$TRAIN)"
, " (y sl$BLK) )"
, " (! (=> (and (elem@@sl$TRAIN x (dom@@sl$TRAIN@@sl$BLK f1))"
, " (injective@@sl$TRAIN@@sl$BLK f1))"
, " (= (ran@@sl$TRAIN@@sl$BLK (ovl@@sl$TRAIN@@sl$BLK f1 (mk-fun@@sl$TRAIN@@sl$BLK x y)))"
, " (union (set-diff@@sl$BLK (ran@@sl$TRAIN@@sl$BLK f1)"
, " (mk-set@@sl$BLK (apply@@sl$TRAIN@@sl$BLK f1 x)))"
, " (mk-set@@sl$BLK y))))"
, " :pattern"
, " ( (ran@@sl$TRAIN@@sl$BLK (ovl@@sl$TRAIN@@sl$BLK f1 (mk-fun@@sl$TRAIN@@sl$BLK x y))) ))))"
, "(assert (forall ( (f1 (pfun sl$TRAIN sl$BLK))"
, " (x sl$TRAIN)"
, " (y sl$BLK) )"
, " (! (=> (not (elem@@sl$TRAIN x (dom@@sl$TRAIN@@sl$BLK f1)))"
, " (= (ran@@sl$TRAIN@@sl$BLK (ovl@@sl$TRAIN@@sl$BLK f1 (mk-fun@@sl$TRAIN@@sl$BLK x y)))"
, " (union (ran@@sl$TRAIN@@sl$BLK f1) (mk-set@@sl$BLK y))))"
, " :pattern"
, " ( (ran@@sl$TRAIN@@sl$BLK (ovl@@sl$TRAIN@@sl$BLK f1 (mk-fun@@sl$TRAIN@@sl$BLK x y))) ))))"
, "(assert (forall ( (x sl$BLK)"
, " (y sl$BLK) )"
, " (! (= (elem@@sl$BLK x (mk-set@@sl$BLK y)) (= x y))"
, " :pattern"
, " ( (elem@@sl$BLK x (mk-set@@sl$BLK y)) ))))"
, "(assert (forall ( (x sl$TRAIN)"
, " (y sl$TRAIN) )"
, " (! (= (elem@@sl$TRAIN x (mk-set@@sl$TRAIN y)) (= x y))"
, " :pattern"
, " ( (elem@@sl$TRAIN x (mk-set@@sl$TRAIN y)) ))))"
, "(assert (forall ( (s1 (set sl$BLK))"
, " (s2 (set sl$BLK)) )"
, " (! (=> (finite@@sl$BLK s1)"
, " (finite@@sl$BLK (set-diff@@sl$BLK s1 s2)))"
, " :pattern"
, " ( (finite@@sl$BLK (set-diff@@sl$BLK s1 s2)) ))))"
, "(assert (forall ( (s1 (set sl$LOC))"
, " (s2 (set sl$LOC)) )"
, " (! (=> (finite@@sl$LOC s1)"
, " (finite@@sl$LOC (set-diff@@sl$LOC s1 s2)))"
, " :pattern"
, " ( (finite@@sl$LOC (set-diff@@sl$LOC s1 s2)) ))))"
, "(assert (forall ( (s1 (set sl$TRAIN))"
, " (s2 (set sl$TRAIN)) )"
, " (! (=> (finite@@sl$TRAIN s1)"
, " (finite@@sl$TRAIN (set-diff@@sl$TRAIN s1 s2)))"
, " :pattern"
, " ( (finite@@sl$TRAIN (set-diff@@sl$TRAIN s1 s2)) ))))"
, "(assert (forall ( (s1 (set sl$BLK))"
, " (s2 (set sl$BLK)) )"
, " (! (=> (and (finite@@sl$BLK s1) (finite@@sl$BLK s2))"
, " (finite@@sl$BLK (union s1 s2)))"
, " :pattern"
, " ( (finite@@sl$BLK (union s1 s2)) ))))"
, "(assert (forall ( (s1 (set sl$LOC))"
, " (s2 (set sl$LOC)) )"
, " (! (=> (and (finite@@sl$LOC s1) (finite@@sl$LOC s2))"
, " (finite@@sl$LOC (union s1 s2)))"
, " :pattern"
, " ( (finite@@sl$LOC (union s1 s2)) ))))"
, "(assert (forall ( (s1 (set sl$TRAIN))"
, " (s2 (set sl$TRAIN)) )"
, " (! (=> (and (finite@@sl$TRAIN s1) (finite@@sl$TRAIN s2))"
, " (finite@@sl$TRAIN (union s1 s2)))"
, " :pattern"
, " ( (finite@@sl$TRAIN (union s1 s2)) ))))"
, "(assert (forall ( (s1 (set sl$BLK))"
, " (s2 (set sl$BLK)) )"
, " (! (=> (and (finite@@sl$BLK s2) (not (finite@@sl$BLK s1)))"
, " (not (finite@@sl$BLK (set-diff@@sl$BLK s1 s2))))"
, " :pattern"
, " ( (finite@@sl$BLK (set-diff@@sl$BLK s1 s2)) ))))"
, "(assert (forall ( (s1 (set sl$LOC))"
, " (s2 (set sl$LOC)) )"
, " (! (=> (and (finite@@sl$LOC s2) (not (finite@@sl$LOC s1)))"
, " (not (finite@@sl$LOC (set-diff@@sl$LOC s1 s2))))"
, " :pattern"
, " ( (finite@@sl$LOC (set-diff@@sl$LOC s1 s2)) ))))"
, "(assert (forall ( (s1 (set sl$TRAIN))"
, " (s2 (set sl$TRAIN)) )"
, " (! (=> (and (finite@@sl$TRAIN s2) (not (finite@@sl$TRAIN s1)))"
, " (not (finite@@sl$TRAIN (set-diff@@sl$TRAIN s1 s2))))"
, " :pattern"
, " ( (finite@@sl$TRAIN (set-diff@@sl$TRAIN s1 s2)) ))))"
, "(assert (forall ( (x sl$BLK) )"
, " (! (finite@@sl$BLK (mk-set@@sl$BLK x))"
, " :pattern"
, " ( (finite@@sl$BLK (mk-set@@sl$BLK x)) ))))"
, "(assert (forall ( (x sl$TRAIN) )"
, " (! (finite@@sl$TRAIN (mk-set@@sl$TRAIN x))"
, " :pattern"
, " ( (finite@@sl$TRAIN (mk-set@@sl$TRAIN x)) ))))"
, "(assert (finite@@sl$BLK empty-set@@sl$BLK))"
, "(assert (finite@@sl$LOC empty-set@@sl$LOC))"
, "(assert (finite@@sl$TRAIN empty-set@@sl$TRAIN))"
, "; a0"
, "(assert (= in@prime"
, " (set-diff@@sl$TRAIN in (mk-set@@sl$TRAIN t))))"
, "; a3"
, "(assert (= loc@prime"
, " (dom-subt@@sl$TRAIN@@sl$BLK (mk-set@@sl$TRAIN t) loc)))"
, "; asm2"
, "(assert (and (not (= ent ext))"
, " (not (elem@@sl$BLK ent PLF))"
, " (not (elem@@sl$BLK ext PLF))))"
, "; asm3"
, "(assert (forall ( (p sl$BLK) )"
, " (! (= (not (= p ext))"
, " (elem@@sl$BLK p (union (mk-set@@sl$BLK ent) PLF)))"
, " :pattern"
, " ( (elem@@sl$BLK p (union (mk-set@@sl$BLK ent) PLF)) ))))"
, "; asm4"
, "(assert (forall ( (p sl$BLK) )"
, " (! (= (not (= p ent))"
, " (elem@@sl$BLK p (union (mk-set@@sl$BLK ext) PLF)))"
, " :pattern"
, " ( (elem@@sl$BLK p (union (mk-set@@sl$BLK ext) PLF)) ))))"
, "; asm5"
, "(assert (forall ( (p sl$BLK) )"
, " (! (= (or (= p ent) (= p ext))"
, " (not (elem@@sl$BLK p PLF)))"
, " :pattern"
, " ( (elem@@sl$BLK p PLF) ))))"
, "; axm0"
, "(assert (= sl$BLK"
, " (union (union (mk-set@@sl$BLK ent) (mk-set@@sl$BLK ext))"
, " PLF)))"
, "; c0"
, "(assert (elem@@sl$TRAIN t in))"
, "; grd0"
, "(assert (and (= (apply@@sl$TRAIN@@sl$BLK loc t) ext)"
, " (elem@@sl$TRAIN t in)))"
, "; inv1"
, "(assert (forall ( (t sl$TRAIN) )"
, " (! (=> (elem@@sl$TRAIN t in)"
, " (elem@@sl$BLK (apply@@sl$TRAIN@@sl$BLK loc t) sl$BLK))"
, " :pattern"
, " ( (elem@@sl$BLK (apply@@sl$TRAIN@@sl$BLK loc t) sl$BLK) ))))"
, "; inv2"
, "(assert (= (dom@@sl$TRAIN@@sl$BLK loc) in))"
, "(assert (not (= (dom@@sl$TRAIN@@sl$BLK loc@prime) in@prime)))"
, "(check-sat-using (or-else (then qe smt)"
, " (then simplify smt)"
, " (then skip smt)"
, " (then (using-params simplify :expand-power true) smt)))"
, "; train0/leave/INV/inv2"
]
case12 :: IO String
case12 = raw_proof_obligation path0 "train0/leave/INV/inv2" 0
--------------------
-- Error handling --
--------------------
result7 :: String
result7 = unlines
[ "error 54:4:"
, " unrecognized term: t"
]
path7 :: FilePath
path7 = [path|Tests/train-station-err0.tex|]
case7 :: IO String
case7 = find_errors path7
result8 :: String
result8 = unlines
[ "error 43:1:"
, " event 'leave' is undeclared"
]
path8 :: FilePath
path8 = [path|Tests/train-station-err1.tex|]
case8 :: IO String
case8 = find_errors path8
result9 :: String
result9 = unlines
[ "error 52:1:"
, " event 'leave' is undeclared"
]
path9 :: FilePath
path9 = [path|Tests/train-station-err2.tex|]
case9 :: IO String
case9 = find_errors path9
result10 :: String
result10 = unlines
[ "error 56:1:"
, " event 'leave' is undeclared"
]
path10 :: FilePath
path10 = [path|Tests/train-station-err3.tex|]
case10 :: IO String
case10 = find_errors path10
result11 :: String
result11 = unlines
[ "error 60:1:"
, " event 'leave' is undeclared"
]
path11 :: FilePath
path11 = [path|Tests/train-station-err4.tex|]
case11 :: IO String
case11 = find_errors path11
path13 :: FilePath
path13 = [path|Tests/train-station-err5.tex|]
result13 :: String
result13 = unlines
[ "error 176:5:"
, " unrecognized term: t0"
, "Perhaps you meant:"
, "t (variable)"
, ""
, "error 178:5:"
, " unrecognized term: t0"
, "Perhaps you meant:"
, "t (variable)"
, ""
, "error 180:5:"
, " unrecognized term: t0"
, "Perhaps you meant:"
, "t (variable)"
, ""
, "error 182:5:"
, " unrecognized term: t0"
, "Perhaps you meant:"
, "t (variable)"
, ""
, "error 186:34:"
, " unrecognized term: t0"
, "Perhaps you meant:"
, "t (variable)"
, ""
, "error 251:5:"
, " unrecognized term: t0"
, "Perhaps you meant:"
, "t (variable)"
, ""
, "error 253:5:"
, " unrecognized term: t0"
, "Perhaps you meant:"
, "t (variable)"
, ""
, "error 256:7:"
, " unrecognized term: t0"
, "Perhaps you meant:"
, "t (variable)"
, ""
, "error 261:6:"
, " unrecognized term: t0"
, "Perhaps you meant:"
, "t (variable)"
, ""
, "error 264:5:"
, " unrecognized term: t0"
, "Perhaps you meant:"
, "t (variable)"
, ""
, "error 267:5:"
, " unrecognized term: t0"
, "Perhaps you meant:"
, "t (variable)"
, ""
, "error 269:6:"
, " unrecognized term: t0"
, "Perhaps you meant:"
, "t (variable)"
, ""
, "error 272:6:"
, " unrecognized term: t0"
, "Perhaps you meant:"
, "t (variable)"
, ""
, "error 274:6:"
, " unrecognized term: t0"
, "Perhaps you meant:"
, "t (variable)"
]
case13 :: IO String
case13 = find_errors path13
path14 :: FilePath
path14 = [path|Tests/train-station-err6.tex|]
result14 :: String
result14 = unlines
[ " o train0/INIT/INV/inv1"
, " o train0/INIT/INV/inv2"
, " o train0/INV/WD"
, " o train0/SKIP/CO/co0"
, " o train0/SKIP/CO/co1"
, " o train0/co0/CO/WD"
, " o train0/co1/CO/WD"
, " o train0/enter/CO/co0/case 1/goal"
, " o train0/enter/CO/co0/case 1/hypotheses"
, " o train0/enter/CO/co0/case 1/relation"
, " o train0/enter/CO/co0/case 1/step 1"
, " o train0/enter/CO/co0/case 1/step 2"
, " xxx train0/enter/CO/co0/completeness"
, " o train0/enter/CO/co1"
, " o train0/enter/FIS/in@prime"
, " o train0/enter/FIS/loc@prime"
, " o train0/enter/INV/inv1"
, " o train0/enter/INV/inv2/goal"
, " o train0/enter/INV/inv2/hypotheses"
, " o train0/enter/INV/inv2/relation"
, " o train0/enter/INV/inv2/step 1"
, " o train0/enter/INV/inv2/step 2"
, " o train0/enter/INV/inv2/step 3"
, " o train0/enter/INV/inv2/step 4"
, " o train0/enter/INV/inv2/step 5"
, " o train0/enter/SAF/s0"
, " o train0/enter/SAF/s1"
, " o train0/enter/SCH/grd1"
, " o train0/leave/CO/co0/goal"
, " o train0/leave/CO/co0/hypotheses"
, " o train0/leave/CO/co0/relation"
, " o train0/leave/CO/co0/step 1"
, " o train0/leave/CO/co0/step 2"
, " o train0/leave/CO/co0/step 3"
, " o train0/leave/CO/co0/step 4"
, " o train0/leave/CO/co1/goal"
, " o train0/leave/CO/co1/hypotheses"
, " o train0/leave/CO/co1/relation"
, " o train0/leave/CO/co1/step 1"
, " o train0/leave/CO/co1/step 2"
, " o train0/leave/CO/co1/step 3"
, " o train0/leave/CO/co1/step 4"
, " o train0/leave/CO/co1/step 5"
, " o train0/leave/CO/co1/step 6"
, " o train0/leave/CO/co1/step 7"
, " o train0/leave/CO/co1/step 8"
, " o train0/leave/FIS/in@prime"
, " o train0/leave/FIS/loc@prime"
, " o train0/leave/INV/inv1"
, " o train0/leave/INV/inv2/goal"
, " o train0/leave/INV/inv2/hypotheses"
, " o train0/leave/INV/inv2/relation"
, " o train0/leave/INV/inv2/step 1"
, " o train0/leave/INV/inv2/step 2"
, " o train0/leave/INV/inv2/step 3"
, " o train0/leave/INV/inv2/step 4"
, " o train0/leave/SAF/s0"
, " o train0/leave/SAF/s1"
, " xxx train0/leave/SCH/grd0"
, " o train0/leave/WD/GRD"
, " o train0/s0/SAF/WD/rhs"
, " o train0/s1/SAF/WD/lhs"
, " o train0/s1/SAF/WD/rhs"
, " o train0/tr0/TR/WFIS/t/t@prime"
, " o train0/tr0/TR/leave/EN"
, " o train0/tr0/TR/leave/NEG"
, "passed 64 / 66"
]
case14 :: IO (String, Map Label Sequent)
case14 = verify path14 0
path15 :: FilePath
path15 = [path|Tests/train-station-err7.tex|]
result15 :: String
result15 = unlines
[ " o train0/INIT/INV/inv1"
, " o train0/INIT/INV/inv2"
, " o train0/INV/WD"
, " o train0/SKIP/CO/co0"
, " o train0/SKIP/CO/co1"
, " o train0/co0/CO/WD"
, " o train0/co1/CO/WD"
, " o train0/enter/CO/co0/case 1/goal"
, " o train0/enter/CO/co0/case 1/hypotheses"
, " o train0/enter/CO/co0/case 1/relation"
, " o train0/enter/CO/co0/case 1/step 1"
, " o train0/enter/CO/co0/case 1/step 2"
, " o train0/enter/CO/co0/case 2/goal"
, " o train0/enter/CO/co0/case 2/hypotheses"
, " o train0/enter/CO/co0/case 2/relation"
, " o train0/enter/CO/co0/case 2/step 1"
, " o train0/enter/CO/co0/case 2/step 2"
, " o train0/enter/CO/co0/case 2/step 3"
, " o train0/enter/CO/co0/case 2/step 4"
, " o train0/enter/CO/co0/completeness"
, " o train0/enter/CO/co1"
, " o train0/enter/FIS/in@prime"
, " o train0/enter/FIS/loc@prime"
, " o train0/enter/INV/inv1"
, " o train0/enter/INV/inv2/goal"
, " o train0/enter/INV/inv2/hypotheses"
, " o train0/enter/INV/inv2/relation"
, " o train0/enter/INV/inv2/step 1"
, " o train0/enter/INV/inv2/step 2"
, " o train0/enter/INV/inv2/step 3"
, " o train0/enter/INV/inv2/step 4"
, " o train0/enter/INV/inv2/step 5"
, " o train0/enter/SAF/s0"
, " o train0/enter/SAF/s1"
, " o train0/enter/SCH/grd1"
, " o train0/leave/CO/co0/goal"
, " o train0/leave/CO/co0/hypotheses"
, " xxx train0/leave/CO/co0/new assumption"
, " o train0/leave/CO/co0/relation"
, " o train0/leave/CO/co0/step 1"
, " xxx train0/leave/CO/co0/step 2"
, " o train0/leave/CO/co1/goal"
, " o train0/leave/CO/co1/hypotheses"
, " o train0/leave/CO/co1/relation"
, " o train0/leave/CO/co1/step 1"
, " o train0/leave/CO/co1/step 2"
, " o train0/leave/CO/co1/step 3"
, " o train0/leave/CO/co1/step 4"
, " o train0/leave/CO/co1/step 5"
, " o train0/leave/CO/co1/step 6"
, " o train0/leave/CO/co1/step 7"
, " o train0/leave/CO/co1/step 8"
, " o train0/leave/FIS/in@prime"
, " o train0/leave/FIS/loc@prime"
, " o train0/leave/INV/inv1"
, " o train0/leave/INV/inv2/goal"
, " o train0/leave/INV/inv2/hypotheses"
, " o train0/leave/INV/inv2/relation"
, " o train0/leave/INV/inv2/step 1"
, " o train0/leave/INV/inv2/step 2"
, " o train0/leave/INV/inv2/step 3"
, " o train0/leave/INV/inv2/step 4"
, " o train0/leave/SAF/s0"
, " o train0/leave/SAF/s1"
, " xxx train0/leave/SCH/grd0"
, " o train0/leave/WD/GRD"
, " o train0/s0/SAF/WD/rhs"
, " o train0/s1/SAF/WD/lhs"
, " o train0/s1/SAF/WD/rhs"
, " o train0/tr0/TR/WFIS/t/t@prime"
, " o train0/tr0/TR/leave/EN"
, " o train0/tr0/TR/leave/NEG"
, "passed 69 / 72"
]
case15 :: IO (String, Map Label Sequent)
case15 = verify path15 0
path16 :: FilePath
path16 = [path|Tests/train-station-t2.tex|]
result16 :: String
result16 = unlines
[ " o train0/INIT/INV/inv1"
, " o train0/INIT/INV/inv2"
, " o train0/INV/WD"
, " o train0/SKIP/CO/co0"
, " o train0/SKIP/CO/co1"
, " o train0/co0/CO/WD"
, " o train0/co1/CO/WD"
, " o train0/enter/CO/co0/case 1/goal"
, " o train0/enter/CO/co0/case 1/hypotheses"
, " o train0/enter/CO/co0/case 1/relation"
, " o train0/enter/CO/co0/case 1/step 1"
, " o train0/enter/CO/co0/case 1/step 2"
, " o train0/enter/CO/co0/case 2/goal"
, " o train0/enter/CO/co0/case 2/hypotheses"
, " o train0/enter/CO/co0/case 2/relation"
, " o train0/enter/CO/co0/case 2/step 1"
, " o train0/enter/CO/co0/case 2/step 2"
, " o train0/enter/CO/co0/case 2/step 3"
, " o train0/enter/CO/co0/case 2/step 4"
, " o train0/enter/CO/co0/completeness"
, " o train0/enter/CO/co1/completeness"
, " o train0/enter/CO/co1/new assumption"
, " o train0/enter/CO/co1/part 1/goal"
, " o train0/enter/CO/co1/part 1/hypotheses"
, " o train0/enter/CO/co1/part 1/relation"
, " o train0/enter/CO/co1/part 1/step 1"
, " o train0/enter/CO/co1/part 1/step 2"
, " o train0/enter/CO/co1/part 2/case 1/goal"
, " o train0/enter/CO/co1/part 2/case 1/hypotheses"
, " o train0/enter/CO/co1/part 2/case 1/relation"
, " o train0/enter/CO/co1/part 2/case 1/step 1"
, " o train0/enter/CO/co1/part 2/case 1/step 2"
, " o train0/enter/CO/co1/part 2/case 2/goal"
, " o train0/enter/CO/co1/part 2/case 2/hypotheses"
, " o train0/enter/CO/co1/part 2/case 2/relation"
, " o train0/enter/CO/co1/part 2/case 2/step 1"
, " o train0/enter/CO/co1/part 2/case 2/step 2"
, " o train0/enter/CO/co1/part 2/case 2/step 3"
, " o train0/enter/CO/co1/part 2/completeness"
, " o train0/enter/FIS/in@prime"
, " o train0/enter/FIS/loc@prime"
, " o train0/enter/INV/inv1"
, " o train0/enter/INV/inv2/goal"
, " o train0/enter/INV/inv2/hypotheses"
, " o train0/enter/INV/inv2/relation"
, " o train0/enter/INV/inv2/step 1"
, " o train0/enter/INV/inv2/step 2"
, " o train0/enter/INV/inv2/step 3"
, " o train0/enter/INV/inv2/step 4"
, " o train0/enter/INV/inv2/step 5"
, " o train0/enter/SAF/s0"
, " o train0/enter/SAF/s1"
, " o train0/enter/SCH/grd1"
, " o train0/leave/CO/co0/goal"
, " o train0/leave/CO/co0/hypotheses"
, " o train0/leave/CO/co0/relation"
, " o train0/leave/CO/co0/step 1"
, " o train0/leave/CO/co0/step 2"
, " o train0/leave/CO/co0/step 3"
, " o train0/leave/CO/co0/step 4"
, " o train0/leave/CO/co1/goal"
, " o train0/leave/CO/co1/hypotheses"
, " o train0/leave/CO/co1/relation"
, " o train0/leave/CO/co1/step 1"
, " o train0/leave/CO/co1/step 2"
, " o train0/leave/CO/co1/step 3"
, " o train0/leave/CO/co1/step 4"
, " o train0/leave/CO/co1/step 5"
, " o train0/leave/CO/co1/step 6"
, " o train0/leave/CO/co1/step 7"
, " o train0/leave/CO/co1/step 8"
, " o train0/leave/FIS/in@prime"
, " o train0/leave/FIS/loc@prime"
, " o train0/leave/INV/inv1"
, " o train0/leave/INV/inv2/goal"
, " o train0/leave/INV/inv2/hypotheses"
, " o train0/leave/INV/inv2/relation"
, " o train0/leave/INV/inv2/step 1"
, " o train0/leave/INV/inv2/step 2"
, " o train0/leave/INV/inv2/step 3"
, " o train0/leave/INV/inv2/step 4"
, " o train0/leave/SAF/s0"
, " o train0/leave/SAF/s1"
, " xxx train0/leave/SCH/grd0"
, " o train0/leave/WD/GRD"
, " o train0/s0/SAF/WD/rhs"
, " o train0/s1/SAF/WD/lhs"
, " o train0/s1/SAF/WD/rhs"
, " o train0/tr0/TR/WFIS/t/t@prime"
, " o train0/tr0/TR/leave/EN"
, " o train0/tr0/TR/leave/NEG"
, "passed 90 / 91"
]
case16 :: IO (String, Map Label Sequent)
case16 = verify path16 0
path17 :: FilePath
path17 = [path|Tests/train-station-err8.tex|]
result17 :: String
result17 = unlines
[ "error 75:4:\n type of empty-fun is ill-defined: \\pfun [\\TRAIN,_a]"
, ""
, "error 75:4:\n type of empty-fun is ill-defined: \\pfun [\\TRAIN,_b]"
, ""
, "error 77:3:\n type of empty-fun is ill-defined: \\pfun [\\TRAIN,_a]"
]
case17 :: IO String
case17 = find_errors path17
path22 :: FilePath
path22 = [path|Tests/train-station-err11.tex|]
result22 :: String
result22 = unlines
[ "error 48:1:\n event(s) leave have indices and require witnesses"
]
case22 :: IO String
case22 = find_errors path22
path18 :: FilePath
path18 = [path|Tests/train-station-err9.tex|]
result18 :: String
result18 = unlines
[ "error 68:3:\n expression has type incompatible with its expected type:"
, " expression: (dom loc)"
, " actual type: \\set [\\TRAIN]"
, " expected type: \\Bool "
, ""
, "error 73:3:\n expression has type incompatible with its expected type:"
, " expression: (union in (mk-set t))"
, " actual type: \\set [\\TRAIN]"
, " expected type: \\Bool "
, ""
, "error 118:3:\n expression has type incompatible with its expected type:"
, " expression: t"
, " actual type: \\TRAIN"
, " expected type: \\Bool "
, ""
, "error 123:3:\n expression has type incompatible with its expected type:"
, " expression: empty-set"
, " actual type: \\set [_a]"
, " expected type: \\Bool "
]
case18 :: IO String
case18 = find_errors path18
path21 :: FilePath
path21 = [path|Tests/train-station-err10.tex|]
case21 :: IO String
case21 = find_errors path21
result21 :: String
result21 = unlines
[ "Theory imported multiple times"
, "error 130:1:"
, "\tsets"
, ""
, "error 131:1:"
, "\tsets"
, ""
, "error 132:1:"
, "\tsets"
, ""
]
|
literate-unitb/literate-unitb
|
src/Document/Tests/TrainStation.hs
|
mit
| 283,395 | 1 | 22 | 118,973 | 18,913 | 12,285 | 6,628 | -1 | -1 |
module Levenshtein where
levenshtein :: String -> String -> Int
levenshtein "" b = 0
levenshtein a "" = 0
levenshtein a b = compare a b + levenshtein (tail a) (tail b) where
compare a b = if head a == head b then 0 else 1
|
ostera/asdf
|
haskell/Levenshtein.hs
|
mit
| 225 | 0 | 9 | 51 | 103 | 52 | 51 | 6 | 2 |
-- | This module is an extension of the "RectBinPacker.Bin" module and provides an interface that
-- allows you to insert a rotatable object into a 'Bin'. The orientation of the object will be
-- automatically determined to be the best fit.
----------------------------------------------------------------------------------------------------
module RectBinPacker.BinRotatable
( module RectBinPacker.Bin
-- * Orientation Type
, Orientation(..)
, Rotatable(..)
-- * Insertion
, insertRotate
) where
----------------------------------------------------------------------------------------------------
import Control.Lens (view)
----------------------------------------------------------------------------------------------------
import RectBinPacker.Bin
import RectBinPacker.Geometry
-- * Orientation Type
----------------------------------------------------------------------------------------------------
data Orientation = Upright | Rotated
deriving (Eq, Show)
----------------------------------------------------------------------------------------------------
-- | Represents a type that has an 'Orientation' that can rotated.
class Rotatable a where
rotate :: a -> a
----------------------------------------------------------------------------------------------------
instance Rotatable Orientation where
rotate Upright = Rotated
rotate Rotated = Upright
----------------------------------------------------------------------------------------------------
instance Rotatable Dim where
rotate (Dim w h) = Dim h w
-- * Insertion
----------------------------------------------------------------------------------------------------
-- | Insert an object into a tree. It is inserted in both the upright and rotated position. The
-- smaller tree is kept.
insertRotate :: (HasDim a, Rotatable a) => a -> Bin a -> Bin a
insertRotate val tree
| view maxExtent normal > view maxExtent rotated = rotated
| otherwise = normal
where
normal = insert val tree
rotated = insert (rotate val) tree
|
jochu/image-bin-packing
|
src/RectBinPacker/BinRotatable.hs
|
mit
| 2,037 | 0 | 9 | 259 | 262 | 146 | 116 | 23 | 1 |
{-----------------------------------------------------------------------------------------
Module name: WebSockets
Made by: Tomas Möre 2015
Usage: This is a WebSockets module inteded to run over an instance of the standard Server
IMPORTANT: If you start a websockets session DO NOT attempt to send any kind of HTTP request upon completion
------------------------------------------------------------------------------------------}
--http://datatracker.ietf.org/doc/rfc6455/?include_text=1
{-# LANGUAGE OverloadedStrings #-}
module WebSocket.Server.WebSocket where
import qualified HTTP
import qualified Headers as H
import Smutt.Utility.Utility
import Smutt.HTTP.ErrorResponses
import qualified Data.ByteString as B
import Data.ByteString.Internal (c2w)
import qualified Data.ByteString.Lazy as BL
import qualified Data.CaseInsensitive as CI
import qualified Data.Text as T
import qualified Data.Text.Lazy as TL
import qualified BufferedSocket as BS
import qualified Data.Text.Lazy.Encoding as ENC
import qualified Data.Text.Encoding as STRICTENC
import qualified Data.Text.Encoding.Error as ENC
import qualified Network.Socket as NS
import Data.Maybe
import Data.Either
import Data.Monoid
import Data.Bits
import Data.List
import qualified Data.ByteString.Base64 as B64
import qualified Crypto.Hash.SHA1 as SHA1
import qualified Data.Binary as BINARY
type PayloadLength = Word64
type Mask = Maybe [Word8] -- Should be infinte list
type Fin = Bool
type FrameSize = Int -- Positive Int either 16 or 64
type Masked = Bool
type CloseText = T.Text
type PingPongData = ByteString
type WebSocketThunk = (WebSocket -> Request -> IO Response)
type CloseStatusCode = Word16
-- Websocket magic number, don't blame me!! :'(
guid = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
data Message = TextMessage TL.Text
| BinaryMessage BL.ByteString
| CloseMessage StatusCode CloseReasonText
data ControllFrame = Ping ByteString
| Pong ByteString
| Close StatusCode Text
type ControllFrames = [ControllFrame]
type CloseReasonText = TL.ByteString
type Response = Message
type Request = Message
type MessageWriter = (Message -> IO ())
type MessageReader = Message
data WebSocket = WebSocket { bufferedSocket :: BS.BufferedSocket -- reference to the underlying bufferedSocket
, messageReader :: (MVar Message) -- When reading a message this will be read. The message is a lazy Text or bytestring. IF
, messageWriter :: (MVar MessageWriter) --
, controllFrames :: (IORef ControllFrames) -- Should be treated with atomic operations
, onPing :: (WebSocket -> PingPongData -> IO ())
, onPong :: (WebSocket -> PingPongData -> IO())
, onClose :: (WebSocket -> StatusCode -> CloseText -> IO ())
, closeStatus :: IORef (Maybe (StatusCode, CloseMessage)) -- When a close frame is recieved or sent This will be set
}
data AuthenticationError = InvalidVersion | InvalidMethod | MissingHeader H.HeaderName | InvalidHeader H.HeaderName
data AuthenticationData = {
, webSocketKey :: ByteString
, origin :: Maybe ByteString
, webSocketVersion :: Int
, webSocketProtocol :: [ByteString]
, socketExtensions :: [ByteString]
}
data FrameHeader = FrameHeader Fin OpCode Masked Mask PayloadLength
isFin (FrameHeader fin _ _ _ _ ) = fin
opCode (FrameHeader _ code _ _ _ ) = code
isMasked (FrameHeader _ _ masked _ _ ) = masked
getMask (FrameHeader _ _ _ mask _ ) = mask
getPayLoadLength (FrameHeader _ _ _ _ len ) = len
{-
Opcode: 4 bits
Defines the interpretation of the "Payload data". If an unknown
opcode is received, the receiving endpoint MUST _Fail the
WebSocket Connection_. The following values are defined.
* %x0 denotes a continuation frame
* %x1 denotes a text frame
* %x2 denotes a binary frame
* %x3-7 are reserved for further non-control frames
* %x8 denotes a connection close
* %x9 denotes a ping
* %xA denotes a pong
* %xB-F are reserved for further control frames
-}
data OpCode = ConinuationFrame
| TextFrame
| BinaryFrame
| ConnectionClose
| Ping
| Pong
| Reserved
| Undefined
data StatusCode = NormalClose
| GoingAway
| ProtocolError
| NonAcceptableData
| InvalidData
| ViolatedPolicy
| MessageTooBig
| NeedsExtension
| UnexpectedCondition
| CusomCode Word16
{-- Util --}
bufferedSocket :: WebSocket -> BS.BufferedSocket
bufferedSocket (WebSocket bSocket _ _ ) = bSocket
closeRead :: WebSocket -> IO ()
closeRead (WebSocket bSocket _ _ ) = BS.closeRead bSocket
closeWrite :: WebSocket -> IO ()
closeWrite (WebSocket bSocket _ _ ) = BS.closeWrite bSocket
isReadable :: WebSocket -> IO Bool
isReadable (WebSocket bSocket _ _ ) = BS.isReadable bSocket
isWriteable :: WebSocket -> IO Bool
isWriteable WebSocket bSocket _ _ ) = BS.isWriteable bSocket
{-- Utility --}
-- When a controll frame should be sent this frame is added to the controll que.
-- This function adds the specific frame to the end of the que
-- The frame will be sent in between normal frame sending
queControllFrame:: WebSocket -> ControllFrame -> IO ()
queControllFrame webSocket controllFrame =
atomicModifyIORef' controllQue (\currentList -> (currentList ++ [controllFrame],()))
where
controllQue = controllFrames webSocket
handOverRead :: WebSocket -> IO ()
handOverRead = (>>= putMVar (messageReader webSocket)) . unsafeInterLeaveIO . readMessage
handOverWrite :: Websocket -> IO ()
handOverRead = (>>= putMVar (messageWriter webSocket)) . unsafeInterLeaveIO . writeMessage
{-- Writing --}
writeFreamHeader :: WebSocket -> FrameHeader -> IO ()
writeFreamHeader webSocket (FrameHeader fin opcode masked maskList messageLength) =
let finBit = if fin then 128 else 0
payloadLength = if messageLength < 126
then messageLength
else if messageLength <= 65535
then 126
else 127
maskBit = if mask then 128 else 0
extendedPayloadLength = if payloadLength >= 127
then case payloadLength of
126 -> numToWord8List (fromIntegral payloadLength :: Word32)
127 -> numToWord8List (fromIntegral payloadLength :: Word64) --- FIX THIS SHIT
else []
firstByte = fromOpCode opcode .|. if fin then 128 else 0 -- Byte for fin and opcode
secondByte = maskBit .|. payloadLength
frameList = [firstByte, secondByte] ++ extendedPayloadLength ++ maskList
in -- SEND SHIT HERE
where
nSocket = BS.nativeSocket $ bufferedSocket webSocket
writeBinaryFrame :: WebSocket -> FrameHeader -> BL.ByteString -> IO ()
writeTextFrame :: WebSocket -> FrameHeader -> TL.Text -> IO ()
writeMessage :: WebSocket -> Message -> IO ()
writeMessage webSocket (CloseMessage statusCode statusText) =
BS.send bSocket statusCodeData >>
BS.sendText bSocket statusText >>
where
bSocket = bufferedSocket webSocket
statusCodeData = statusCodeToByteString statusCode
{-
Table From http://datatracker.ietf.org/doc/rfc6455/?include_text=1 describing the bit table of a frame.
This is used to make the functions under
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+d-+-+-------+-+-------------+-------------------------------+
|F|R|R|R| opcode|M| Payload len | Extended payload length |
|I|S|S|S| (4) |A| (7) | (16/64) |
|N|V|V|V| |S| | (if payload len==126/127) |
| |1|2|3| |K| | |
+-+-+-+-+-------+-+-------------+ - - - - - - - - - - - - - - - +
| Extended payload length continued, if payload len == 127 |
+ - - - - - - - - - - - - - - - +-------------------------------+
| |Masking-key, if MASK set to 1 |
+-------------------------------+-------------------------------+
| Masking-key (continued) | Payload Data |
+-------------------------------- - - - - - - - - - - - - - - - +
: Payload Data continued ... :
+ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +
| Payload Data continued ... |
+---------------------------------------------------------------+
-}
{-- Reading --}
readFrameHeader :: WebSocket -> IO FrameHeader
readFrameHeader webSocket =
do byte1 <- BS.readByte bSocket
byte2 <- BS.readByte bSocket
let fin = isFin byte1
opCode = toOpCode $ extractOpCode byte1
hasMask = extractIsMaksed byte2
eitherPayload = (payloadLength8 byte2)
Right smallPayload = eitherPayload
nExtendedBytes = if isRight eitherPayload
then 0
else let Left a = eitherPayload
in a
extendedBytes <- B.unpack <$> BS.read bSocket nExtendedBytes
let extendedPayloadLength = shiftWordTo extendedBytes
realPayload = if nExtendedBytes == 0
then smallPayload
else extendedPayloadLength
maskString <- BS.read bSocket (if hasMask then 4 else 0)
let maskList = case maskString of
"" -> Nothing
_ -> Just $ cycle $ B.unpack maskString
return $ FrameHeader fin opcode masked maskList realPayload
where
bSocket = bufferedSocket webSocket
--
readFrames :: WebSocket -> IO Bl.ByteString
readFrames webSocket = do
readable <- isReadable webSocket
if readable
then do
fHead@(FrameHeader fin frameOpCode masked mask payloadLength) <- readFrameHeader bSocket
if frameOpCode == ConinuationFrame
-- If the frameOP is a continuation frame We will return a lazy bytestring
-- if fin is set the "next" step is set to an empry bytestring. And will not continue reading
then do
next <- unsafeInterLeaveIO $ nextStep
inBytes <- readBody
return $ inBytes <> next
-- If the frameOpCode isn't
else controllFrameHandler webSocket fHead >> loop
else handOverRead webSocket >> return ""
where
bSocket = bufferedSocket webSocket
loop = readFrames webSocket
nextStep = if if fin then return "" else unsafeInterLeaveIO loop
outData bytes = if isMaked fHead
then unmask mask a
else a
readBody = outData <$> BS.readLazy bSocket payloadLength
readMessage :: WebSocket -> IO Request
readMessage webSocket = do
readable <- isReadable webSocket
if readable
-- if the socket is readable then read as normal
then do
fHead@(FrameHeader fin opCode masked mask payloadLength) <- readFrameHeader webSocket
if elem opCode [TextFrame, BinaryFrame]
then do
firstFrame <- readLazy bSocket payloadLength >>=
frameRest <- if fin
then return ""
else unsafeInterLeaveIO $ readFrames websocket
let inData = firstFrame <> frameRest
case opCode of
TextFrame -> return $ TextMessage $ ENC.decodeUtf8With (ENC.replace '\xfffd') inData
BinaryFrame -> return $ BinaryMessage inData
else
if payloadLength <= 125
then controllFrameHandler webSocket fHead >> loop
else error "Controll frame data to big"
-- If the socket isn't readable we will get the close status and message from the websockets IORef.
-- We will then send the requesting function a "Closed" Frame
else do
(statusCode, message) <- readIORef (closeStatus webSocket)
handOverRead webSocket
return $ Closed statusCode message
where
bSocket = bufferedSocket webSocket
loop = readMessage webSocket
controllFrameHandler :: WebSocket -> FrameHeader -> IO ()
-- All controll frames MUST have a FIN set
controllFrameHandler webSocket (FrameHeader False _ _ _ _) = error "Invalid ControllFrame Fin is not True"
-- When we get a close frame we will close the read port. Set the status code and message to the websockets
-- Status code IORef and run the onclose function
controllFrameHandler webSocket (FrameHeader fin CloseFrame masked mask payloadLength) =
do (statusCode, statusMessage) <- readCloseMessage webSocket fHead
(onClose webSocket) webSocket statusCode statusMessage
controllFrameHandler webSocket (FrameHeader fin opCode masked mask payloadLength) = do
inBytes <- read bSocket payloadLength
let pingPongData = if masked
then unmaskStrict mask inBytes
else inBytes
case opCode of
Ping -> (onPing webSocket) pingPongData fHead
Pong -> (onPong webSocket) pingPongData fHead
where
bSocket = bufferedSocket webSocket
case frameOpCode of
Ping -> do
inBytes <- readBody
(onPing webSocket) respondToPing bSocket fHead
loop
Pong -> do
inBytes <- readBody
thunk $ PongRequest $ BL.fromChunks
respondToPing bSocket fHead inBytes
inBytes `seq` loop
ConnectionClose -> do
(statusCode, statusMessage) <- readCloseMessage
(onClose webSocket) webSocket statusCode statusMessage
return ""
-- This reads the entire message of a close frame.
-- Note that this function WILL close the readPort
readCloseMessage :: WebSocket -> FrameHeader -> IO (StatusCode, CloseMessage)
readCloseMessage webSocket (FrameHeader _ _ _ _ 0) = wsClose >> return (NormalClose, "")
readCloseMessage webSocket (FrameHeader _ _ _ mask payloadLength) =
if payloadLength <= 125
then do inData <- unmaskStrict mask $ read bSocket payloadLength
let statusCode = bytestringToStatusCode $ B.take 2 inData
message = (STRICTENC.decodeUtf8With (ENC.replace '\xfffd')) $ B.drop 2 inData
closeData = (statusCode, message)
writeIORef (closeStatus webSocket) $ Just closeData
wsClose
return closeData
else
wsClose >> error "Invalid payloadlength of socket"
where
bSocket = bufferedSocket webSocket
wsClose = cloaseRead webSocket
{-- Frame Header handeling --}
{-
Table From http://datatracker.ietf.org/doc/rfc6455/?include_text=1 describing the bit table of a frame.
This is used to make the functions under
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+d-+-+-------+-+-------------+-------------------------------+
|F|R|R|R| opcode|M| Payload len | Extended payload length |
|I|S|S|S| (4) |A| (7) | (16/64) |
|N|V|V|V| |S| | (if payload len==126/127) |
| |1|2|3| |K| | |
+-+-+-+-+-------+-+-------------+ - - - - - - - - - - - - - - - +
| Extended payload length continued, if payload len == 127 |
+ - - - - - - - - - - - - - - - +-------------------------------+
| |Masking-key, if MASK set to 1 |
+-------------------------------+-------------------------------+
| Masking-key (continued) | Payload Data |
+-------------------------------- - - - - - - - - - - - - - - - +
: Payload Data continued ... :
+ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +
| Payload Data continued ... |
+---------------------------------------------------------------+
-}
{-
FIN: 1 bit
Indicates that this is the final fragment in a message. The first
fragment MAY also be the final fragment.
-}
isFin :: Word8 -> Fin
isFin b = (shift b (-7)) == 1
toOpCode :: Word8 -> OpCode
toOpCode 0x0 = ConinuationFrame
toOpCode 0x1 = TextFrame
toOpCode 0x2 = BinaryFrame
toOpCode 0x8 = ConnectionClose
toOpCode 0x9 = Ping
toOpCode 0xA = Pong
toOpCode n
| isUndefined = Undefined
| isReserved = Reserved
where
isUndefined = (0x3 >= n && 0x7 <= n)
isReserved = n >= 0xB
-- zeroes any FIN or RSV bits
extractOpCode :: Word8 -> OpCode
extractOpCode = toOpCode . (240 .&.)
fromOpCode :: OpCode -> Word8
fromOpCode ConinuationFrame = 0x0
fromOpCode TextFrame = 0x1
fromOpCode BinaryFrame = 0x2
fromOpCode ConnectionClose = 0x8
fromOpCode Ping = 0x9
fromOpCode Pong = 0xA
{-
Mask: 1 bit
Defines whether the "Payload data" is masked. If set to 1, a
masking key is present in masking-key, and this is used to unmask
the "Payload data" as per Section 5.3. All frames sent from
client to server have this bit set to 1.
-}
-- Same function as isFin
extractIsMaksed :: Word8 -> Bool
extractIsMaksed = isFin
-- Nulls the leftmost bit. IF the remaing is 126 then read extended payload of 16 bytes or if 127 read extended payload of
payloadLength8 :: Word8 -> Either FrameSize PayloadLength
payloadLength8 b
| n < 126 = Right n
| n == 126 = Left smallFrame
| otherwise = Left bigFrame
where
n = 128 .&. b -- nulls the first bit
smallFrame = 2 -- 16 bits
bigFrame = 8 -- 8 bytes
statusCodeToByteString :: StatusCode -> B.ByteString
statusCodeToByteString NormalClose = "\ETX\232" -- 1000
statusCodeToByteString GoingAway = "\ETX\233" -- 1001
statusCodeToByteString ProtocolError = "\ETX\234" -- 1002
statusCodeToByteString NonAcceptableData = "\ETX\235" -- 1003
statusCodeToByteString InvalidData = "\ETX\239" -- 1007
statusCodeToByteString ViolatedPolicy = "\ETX\240" -- 1008
statusCodeToByteString MessageTooBig = "\ETX\241" -- 1009
statusCodeToByteString NeedsExtension = "\ETX\242" -- 1010
statusCodeToByteString UnexpectedCondition = "\ETX\243" -- 1011
statusCodeToByteString CustomCode w16 = BINARY.encode w16
bytestringToStatusCode :: B.ByteString -> StatusCode
bytestringToStatusCode "\ETX\232" = NormalClose
bytestringToStatusCode "\ETX\233" = GoingAway
bytestringToStatusCode "\ETX\234" = ProtocolError
bytestringToStatusCode "\ETX\235" = NonAcceptableData
bytestringToStatusCode "\ETX\239" = InvalidData
bytestringToStatusCode "\ETX\240" = ViolatedPolicy
bytestringToStatusCode "\ETX\241" = MessageTooBig
bytestringToStatusCode "\ETX\242" = NeedsExtension
bytestringToStatusCode "\ETX\243" = UnexpectedCondition
bytestringToStatusCode _ = CustomCode (BINARY.decode w16)
-- First argument MUST be a cycled mask of bytes
unmasker :: Mask -> Word8 -> (CycledMask, Word8)
unmasker (maskByte:maskRest) byte = (maskRest, xor byte maskByte)
unmask :: Mask -> [ByteString] -> [ByteString]
unmask _ [] = []
unmask mask (currentString:unmakskedRest) =
let (maskRest, unmasked) = B.mapAccumL (unmasker mask) currentString
in (unmasked:unmask maskRest unmakskedRest)
unmaskStrict :: Mask -> ByteString -> ByteString
unmaskStrict mask string =
let (_, unmasked) = B.mapAccumL (unmasker mask) currentString
in unmasked
{-- Opening handshake --}
makeWebsocketExtensionList :: H.Headers -> [ByteString]
makeWebsocketExtensionList [] = []
makeWebsocketExtensionList ((H.SecWebSocketExtensions, hdrValue):xs) = (hdrValue:makeWebsocketExtensionList xs)
makeWebsocketExtensionList (_:xs) = makeWebsocketExtensionList xs
makeWebsocketProtoclList :: ByteString -> [ByteString]
makeWebsocketProtoclList = map stripWhitespace . B.split (c2w ',')
authenticateHandshake :: HTTP.Request -> Either AuthenticationError AuthenticationData
authenticateHandshake req =
case lookup True conditions of
Just a -> Left a
Nothing -> Right authenticationData
where
headers = HTTP.requestHeaders req
-- Lookups off diffrent header values and making just variables
maybeHost = lookup H.Host $ headers
Just host = maybeHost
maybeUpgrade = lookup H.Upgrade $ headers
Just upgrade = maybeUpgrade
maybeConnection = lookup H.Host $connection
Just connection = maybeConnection
maybeOrigin = lookup H.Origin $ headers
maybeWebSocketKey = lookup H.SecWebSocketKey $ headers
Just webSocketKey = maybeWebSocketKey
maybeWebSocketVersion = lookup H.SecWebSocketVersion $ headers
Just webSocketVersion = maybeWebSocketVersion
maybeWebSocketProtocol = lookup H.SecWebSocketProtocol $ headers
Just webSocketProtocol = maybeWebSocketProtocol
--maybeWebSocketExtensions@(Just webSocketExtensions) = lookup H.SecWebSocketExtensions $ headers
keyDecoded = B64.decode webSocketKey
Right keyBytestring = keyDecoded
keyIsValid = and [isRight keyDecoded, (B.length keyBytestring) == 16]
webSocketVersonInt = byteStringToInteger webSocketVersion
conditions = [ ( not $ HTTP.reqIsGET req , InvalidMethod)
, ( not $ HTTP.reqIsHTTP11 req , InvalidVersion)
, ( isNothing maybeHost , MissingHeader H.Host)
, ( isNothing maybeUpgrade , MissingHeader H.Upgrade)
, ( isNothing maybeConnection , MissingHeader H.Connection)
, ( isNothing maybeWebSocketKey , MissingHeader H.SecWebSocketKey)
, ( isNothing maybeWebSocketVersion , MissingHeader H.SecWebSocketVersion)
, ( quickQIEqual upgrade "websocket" , InvalidHeader H.Upgrade)
, ( quickQIEqual connection "upgrade" , InvalidHeader H.Connection)
, ( not keyIsValid , InvalidHeader H.SecWebSocketKey)
, (webSocketVersion == "13" , InvalidHeader H.SecWebSocketVersion)
]
authenticationData = AuthenticationData { webSocketKey = webSocketKey
, origin = maybeOrigin
, webSocketVersion = webSocketVersonInt
, webSocketProtocol = maybe [] makeWebsocketProtoclList webSocketProtocol
, socketExtensions = makeWebsocketExtensionList headers
}
acceptHandshake :: HTTP.Request -> AuthenticationData -> IO ()
acceptHandshake req authData =
BS.send bSocket fullResponseString
where
statusLine = "HTTP/1.1 101 Switching Protocols\r\n"
respondKey = (B64.encode (SHA1.hash ((webSocketKey req) <> guid)))
respondHeaders = [(H.Connection, "Upgrade"),(H.Upgrade, "websocket"),(H.SecWebSocketAccept, respondKey)]
fullResponseString = statusLine <> (H.headersToString respondHeaders) <> crlf
bSocket = HTTP.bufSocket req
withWebSockets :: HTTTP.Request -> WebSocketThunk -> IO HTTP.Response
withWebSockets req thunk =
if isRight eitherAuthentication
then do
let Right authData = eitherAuthentication
acceptHandshake req authData
return HTTP.Manual
else return $ HTTP.HeadersResponse 400 [(H.Connection, "close")]
where
eitherAuthentication = authenticateHandshake request
bSocket = HTTP.bufSocket req
|
black0range/Smutt
|
src/Smutt/WebSocket/Server/WebSocket.hs
|
mit
| 25,956 | 267 | 15 | 8,664 | 4,108 | 2,245 | 1,863 | -1 | -1 |
{-# OPTIONS_GHC -fno-warn-incomplete-patterns #-}
module PrintC where
-- pretty-printer generated by the BNF converter
import AbsC
import Data.Char
-- the top-level printing method
printTree :: Print a => a -> String
printTree = render . prt 0
type Doc = [ShowS] -> [ShowS]
doc :: ShowS -> Doc
doc = (:)
render :: Doc -> String
render d = rend 0 (map ($ "") $ d []) "" where
rend i ss = case ss of
"[" :ts -> showChar '[' . rend i ts
"(" :ts -> showChar '(' . rend i ts
"{" :ts -> showChar '{' . new (i+1) . rend (i+1) ts
"}" : ";":ts -> new (i-1) . space "}" . showChar ';' . new (i-1) . rend (i-1) ts
"}" :ts -> new (i-1) . showChar '}' . new (i-1) . rend (i-1) ts
";" :ts -> showChar ';' . new i . rend i ts
t : "," :ts -> showString t . space "," . rend i ts
t : ")" :ts -> showString t . showChar ')' . rend i ts
t : "]" :ts -> showString t . showChar ']' . rend i ts
t :ts -> space t . rend i ts
_ -> id
new i = showChar '\n' . replicateS (2*i) (showChar ' ') . dropWhile isSpace
space t = showString t . (\s -> if null s then "" else (' ':s))
parenth :: Doc -> Doc
parenth ss = doc (showChar '(') . ss . doc (showChar ')')
concatS :: [ShowS] -> ShowS
concatS = foldr (.) id
concatD :: [Doc] -> Doc
concatD = foldr (.) id
replicateS :: Int -> ShowS -> ShowS
replicateS n f = concatS (replicate n f)
-- the printer class does the job
class Print a where
prt :: Int -> a -> Doc
prtList :: Int -> [a] -> Doc
prtList i = concatD . map (prt i)
instance Print a => Print [a] where
prt = prtList
instance Print Char where
prt _ s = doc (showChar '\'' . mkEsc '\'' s . showChar '\'')
prtList _ s = doc (showChar '"' . concatS (map (mkEsc '"') s) . showChar '"')
mkEsc :: Char -> Char -> ShowS
mkEsc q s = case s of
_ | s == q -> showChar '\\' . showChar s
'\\'-> showString "\\\\"
'\n' -> showString "\\n"
'\t' -> showString "\\t"
_ -> showChar s
prPrec :: Int -> Int -> Doc -> Doc
prPrec i j = if j<i then parenth else id
instance Print Integer where
prt _ x = doc (shows x)
instance Print Double where
prt _ x = doc (shows x)
instance Print Ident where
prt _ (Ident i) = doc (showString ( i))
prtList _ [x] = (concatD [prt 0 x])
prtList _ (x:xs) = (concatD [prt 0 x, doc (showString ","), prt 0 xs])
instance Print Unsigned where
prt _ (Unsigned i) = doc (showString ( i))
instance Print Long where
prt _ (Long i) = doc (showString ( i))
instance Print UnsignedLong where
prt _ (UnsignedLong i) = doc (showString ( i))
instance Print Hexadecimal where
prt _ (Hexadecimal i) = doc (showString ( i))
instance Print HexUnsigned where
prt _ (HexUnsigned i) = doc (showString ( i))
instance Print HexLong where
prt _ (HexLong i) = doc (showString ( i))
instance Print HexUnsLong where
prt _ (HexUnsLong i) = doc (showString ( i))
instance Print Octal where
prt _ (Octal i) = doc (showString ( i))
instance Print OctalUnsigned where
prt _ (OctalUnsigned i) = doc (showString ( i))
instance Print OctalLong where
prt _ (OctalLong i) = doc (showString ( i))
instance Print OctalUnsLong where
prt _ (OctalUnsLong i) = doc (showString ( i))
instance Print CDouble where
prt _ (CDouble i) = doc (showString ( i))
instance Print CFloat where
prt _ (CFloat i) = doc (showString ( i))
instance Print CLongDouble where
prt _ (CLongDouble i) = doc (showString ( i))
instance Print Program where
prt i e = case e of
Progr externaldeclarations -> prPrec i 0 (concatD [prt 0 externaldeclarations])
instance Print External_declaration where
prt i e = case e of
Afunc functiondef -> prPrec i 0 (concatD [prt 0 functiondef])
Global dec -> prPrec i 0 (concatD [prt 0 dec])
prtList _ [x] = (concatD [prt 0 x])
prtList _ (x:xs) = (concatD [prt 0 x, prt 0 xs])
instance Print Function_def where
prt i e = case e of
OldFunc declarationspecifiers declarator decs compoundstm -> prPrec i 0 (concatD [prt 0 declarationspecifiers, prt 0 declarator, prt 0 decs, prt 0 compoundstm])
NewFunc declarationspecifiers declarator compoundstm -> prPrec i 0 (concatD [prt 0 declarationspecifiers, prt 0 declarator, prt 0 compoundstm])
OldFuncInt declarator decs compoundstm -> prPrec i 0 (concatD [prt 0 declarator, prt 0 decs, prt 0 compoundstm])
NewFuncInt declarator compoundstm -> prPrec i 0 (concatD [prt 0 declarator, prt 0 compoundstm])
instance Print Dec where
prt i e = case e of
NoDeclarator declarationspecifiers -> prPrec i 0 (concatD [prt 0 declarationspecifiers, doc (showString ";")])
Declarators declarationspecifiers initdeclarators -> prPrec i 0 (concatD [prt 0 declarationspecifiers, prt 0 initdeclarators, doc (showString ";")])
prtList _ [x] = (concatD [prt 0 x])
prtList _ (x:xs) = (concatD [prt 0 x, prt 0 xs])
instance Print Declaration_specifier where
prt i e = case e of
Type typespecifier -> prPrec i 0 (concatD [prt 0 typespecifier])
Storage storageclassspecifier -> prPrec i 0 (concatD [prt 0 storageclassspecifier])
SpecProp typequalifier -> prPrec i 0 (concatD [prt 0 typequalifier])
prtList _ [x] = (concatD [prt 0 x])
prtList _ (x:xs) = (concatD [prt 0 x, prt 0 xs])
instance Print Init_declarator where
prt i e = case e of
OnlyDecl declarator -> prPrec i 0 (concatD [prt 0 declarator])
InitDecl declarator initializer -> prPrec i 0 (concatD [prt 0 declarator, doc (showString "="), prt 0 initializer])
prtList _ [x] = (concatD [prt 0 x])
prtList _ (x:xs) = (concatD [prt 0 x, doc (showString ","), prt 0 xs])
instance Print Type_specifier where
prt i e = case e of
Tvoid -> prPrec i 0 (concatD [doc (showString "void")])
Tchar -> prPrec i 0 (concatD [doc (showString "char")])
Tshort -> prPrec i 0 (concatD [doc (showString "short")])
Tint -> prPrec i 0 (concatD [doc (showString "int")])
Tlong -> prPrec i 0 (concatD [doc (showString "long")])
Tfloat -> prPrec i 0 (concatD [doc (showString "float")])
Tdouble -> prPrec i 0 (concatD [doc (showString "double")])
Tsigned -> prPrec i 0 (concatD [doc (showString "signed")])
Tunsigned -> prPrec i 0 (concatD [doc (showString "unsigned")])
Tstruct structorunionspec -> prPrec i 0 (concatD [prt 0 structorunionspec])
Tenum enumspecifier -> prPrec i 0 (concatD [prt 0 enumspecifier])
Tname -> prPrec i 0 (concatD [doc (showString "Typedef_name")])
instance Print Storage_class_specifier where
prt i e = case e of
MyType -> prPrec i 0 (concatD [doc (showString "typedef")])
GlobalPrograms -> prPrec i 0 (concatD [doc (showString "extern")])
LocalProgram -> prPrec i 0 (concatD [doc (showString "static")])
LocalBlock -> prPrec i 0 (concatD [doc (showString "auto")])
LocalReg -> prPrec i 0 (concatD [doc (showString "register")])
instance Print Type_qualifier where
prt i e = case e of
Const -> prPrec i 0 (concatD [doc (showString "const")])
NoOptim -> prPrec i 0 (concatD [doc (showString "volatile")])
prtList _ [x] = (concatD [prt 0 x])
prtList _ (x:xs) = (concatD [prt 0 x, prt 0 xs])
instance Print Struct_or_union_spec where
prt i e = case e of
Tag structorunion id structdecs -> prPrec i 0 (concatD [prt 0 structorunion, prt 0 id, doc (showString "{"), prt 0 structdecs, doc (showString "}")])
Unique structorunion structdecs -> prPrec i 0 (concatD [prt 0 structorunion, doc (showString "{"), prt 0 structdecs, doc (showString "}")])
TagType structorunion id -> prPrec i 0 (concatD [prt 0 structorunion, prt 0 id])
instance Print Struct_or_union where
prt i e = case e of
Struct -> prPrec i 0 (concatD [doc (showString "struct")])
Union -> prPrec i 0 (concatD [doc (showString "union")])
instance Print Struct_dec where
prt i e = case e of
Structen specquals structdeclarators -> prPrec i 0 (concatD [prt 0 specquals, prt 0 structdeclarators, doc (showString ";")])
prtList _ [x] = (concatD [prt 0 x])
prtList _ (x:xs) = (concatD [prt 0 x, prt 0 xs])
instance Print Spec_qual where
prt i e = case e of
TypeSpec typespecifier -> prPrec i 0 (concatD [prt 0 typespecifier])
QualSpec typequalifier -> prPrec i 0 (concatD [prt 0 typequalifier])
prtList _ [x] = (concatD [prt 0 x])
prtList _ (x:xs) = (concatD [prt 0 x, prt 0 xs])
instance Print Struct_declarator where
prt i e = case e of
Decl declarator -> prPrec i 0 (concatD [prt 0 declarator])
Field constantexpression -> prPrec i 0 (concatD [doc (showString ":"), prt 0 constantexpression])
DecField declarator constantexpression -> prPrec i 0 (concatD [prt 0 declarator, doc (showString ":"), prt 0 constantexpression])
prtList _ [x] = (concatD [prt 0 x])
prtList _ (x:xs) = (concatD [prt 0 x, doc (showString ","), prt 0 xs])
instance Print Enum_specifier where
prt i e = case e of
EnumDec enumerators -> prPrec i 0 (concatD [doc (showString "enum"), doc (showString "{"), prt 0 enumerators, doc (showString "}")])
EnumName id enumerators -> prPrec i 0 (concatD [doc (showString "enum"), prt 0 id, doc (showString "{"), prt 0 enumerators, doc (showString "}")])
EnumVar id -> prPrec i 0 (concatD [doc (showString "enum"), prt 0 id])
instance Print Enumerator where
prt i e = case e of
Plain id -> prPrec i 0 (concatD [prt 0 id])
EnumInit id constantexpression -> prPrec i 0 (concatD [prt 0 id, doc (showString "="), prt 0 constantexpression])
prtList _ [x] = (concatD [prt 0 x])
prtList _ (x:xs) = (concatD [prt 0 x, doc (showString ","), prt 0 xs])
instance Print Declarator where
prt i e = case e of
BeginPointer pointer directdeclarator -> prPrec i 0 (concatD [prt 0 pointer, prt 0 directdeclarator])
NoPointer directdeclarator -> prPrec i 0 (concatD [prt 0 directdeclarator])
instance Print Direct_declarator where
prt i e = case e of
Name id -> prPrec i 0 (concatD [prt 0 id])
ParenDecl declarator -> prPrec i 0 (concatD [doc (showString "("), prt 0 declarator, doc (showString ")")])
InnitArray directdeclarator constantexpression -> prPrec i 0 (concatD [prt 0 directdeclarator, doc (showString "["), prt 0 constantexpression, doc (showString "]")])
Incomplete directdeclarator -> prPrec i 0 (concatD [prt 0 directdeclarator, doc (showString "["), doc (showString "]")])
NewFuncDec directdeclarator parametertype -> prPrec i 0 (concatD [prt 0 directdeclarator, doc (showString "("), prt 0 parametertype, doc (showString ")")])
OldFuncDef directdeclarator ids -> prPrec i 0 (concatD [prt 0 directdeclarator, doc (showString "("), prt 0 ids, doc (showString ")")])
OldFuncDec directdeclarator -> prPrec i 0 (concatD [prt 0 directdeclarator, doc (showString "("), doc (showString ")")])
instance Print Pointer where
prt i e = case e of
Point -> prPrec i 0 (concatD [doc (showString "*")])
PointQual typequalifiers -> prPrec i 0 (concatD [doc (showString "*"), prt 0 typequalifiers])
PointPoint pointer -> prPrec i 0 (concatD [doc (showString "*"), prt 0 pointer])
PointQualPoint typequalifiers pointer -> prPrec i 0 (concatD [doc (showString "*"), prt 0 typequalifiers, prt 0 pointer])
instance Print Parameter_type where
prt i e = case e of
AllSpec parameterdeclarations -> prPrec i 0 (concatD [prt 0 parameterdeclarations])
More parameterdeclarations -> prPrec i 0 (concatD [prt 0 parameterdeclarations, doc (showString ","), doc (showString "...")])
instance Print Parameter_declarations where
prt i e = case e of
ParamDec parameterdeclaration -> prPrec i 0 (concatD [prt 0 parameterdeclaration])
MoreParamDec parameterdeclarations parameterdeclaration -> prPrec i 0 (concatD [prt 0 parameterdeclarations, doc (showString ","), prt 0 parameterdeclaration])
instance Print Parameter_declaration where
prt i e = case e of
OnlyType declarationspecifiers -> prPrec i 0 (concatD [prt 0 declarationspecifiers])
TypeAndParam declarationspecifiers declarator -> prPrec i 0 (concatD [prt 0 declarationspecifiers, prt 0 declarator])
Abstract declarationspecifiers abstractdeclarator -> prPrec i 0 (concatD [prt 0 declarationspecifiers, prt 0 abstractdeclarator])
instance Print Initializer where
prt i e = case e of
InitExpr exp -> prPrec i 0 (concatD [prt 2 exp])
InitListOne initializers -> prPrec i 0 (concatD [doc (showString "{"), prt 0 initializers, doc (showString "}")])
InitListTwo initializers -> prPrec i 0 (concatD [doc (showString "{"), prt 0 initializers, doc (showString ","), doc (showString "}")])
instance Print Initializers where
prt i e = case e of
AnInit initializer -> prPrec i 0 (concatD [prt 0 initializer])
MoreInit initializers initializer -> prPrec i 0 (concatD [prt 0 initializers, doc (showString ","), prt 0 initializer])
instance Print Type_name where
prt i e = case e of
PlainType specquals -> prPrec i 0 (concatD [prt 0 specquals])
ExtendedType specquals abstractdeclarator -> prPrec i 0 (concatD [prt 0 specquals, prt 0 abstractdeclarator])
instance Print Abstract_declarator where
prt i e = case e of
PointerStart pointer -> prPrec i 0 (concatD [prt 0 pointer])
Advanced dirabsdec -> prPrec i 0 (concatD [prt 0 dirabsdec])
PointAdvanced pointer dirabsdec -> prPrec i 0 (concatD [prt 0 pointer, prt 0 dirabsdec])
instance Print Dir_abs_dec where
prt i e = case e of
WithinParentes abstractdeclarator -> prPrec i 0 (concatD [doc (showString "("), prt 0 abstractdeclarator, doc (showString ")")])
Array -> prPrec i 0 (concatD [doc (showString "["), doc (showString "]")])
InitiatedArray constantexpression -> prPrec i 0 (concatD [doc (showString "["), prt 0 constantexpression, doc (showString "]")])
UnInitiated dirabsdec -> prPrec i 0 (concatD [prt 0 dirabsdec, doc (showString "["), doc (showString "]")])
Initiated dirabsdec constantexpression -> prPrec i 0 (concatD [prt 0 dirabsdec, doc (showString "["), prt 0 constantexpression, doc (showString "]")])
OldFunction -> prPrec i 0 (concatD [doc (showString "("), doc (showString ")")])
NewFunction parametertype -> prPrec i 0 (concatD [doc (showString "("), prt 0 parametertype, doc (showString ")")])
OldFuncExpr dirabsdec -> prPrec i 0 (concatD [prt 0 dirabsdec, doc (showString "("), doc (showString ")")])
NewFuncExpr dirabsdec parametertype -> prPrec i 0 (concatD [prt 0 dirabsdec, doc (showString "("), prt 0 parametertype, doc (showString ")")])
instance Print Stm where
prt i e = case e of
LabelS labeledstm -> prPrec i 0 (concatD [prt 0 labeledstm])
CompS compoundstm -> prPrec i 0 (concatD [prt 0 compoundstm])
ExprS expressionstm -> prPrec i 0 (concatD [prt 0 expressionstm])
SelS selectionstm -> prPrec i 0 (concatD [prt 0 selectionstm])
IterS iterstm -> prPrec i 0 (concatD [prt 0 iterstm])
JumpS jumpstm -> prPrec i 0 (concatD [prt 0 jumpstm])
prtList _ [x] = (concatD [prt 0 x])
prtList _ (x:xs) = (concatD [prt 0 x, prt 0 xs])
instance Print Labeled_stm where
prt i e = case e of
SlabelOne id stm -> prPrec i 0 (concatD [prt 0 id, doc (showString ":"), prt 0 stm])
SlabelTwo constantexpression stm -> prPrec i 0 (concatD [doc (showString "case"), prt 0 constantexpression, doc (showString ":"), prt 0 stm])
SlabelThree stm -> prPrec i 0 (concatD [doc (showString "default"), doc (showString ":"), prt 0 stm])
instance Print Compound_stm where
prt i e = case e of
ScompOne -> prPrec i 0 (concatD [doc (showString "{"), doc (showString "}")])
ScompTwo stms -> prPrec i 0 (concatD [doc (showString "{"), prt 0 stms, doc (showString "}")])
ScompThree decs -> prPrec i 0 (concatD [doc (showString "{"), prt 0 decs, doc (showString "}")])
ScompFour decs stms -> prPrec i 0 (concatD [doc (showString "{"), prt 0 decs, prt 0 stms, doc (showString "}")])
instance Print Expression_stm where
prt i e = case e of
SexprOne -> prPrec i 0 (concatD [doc (showString ";")])
SexprTwo exp -> prPrec i 0 (concatD [prt 0 exp, doc (showString ";")])
instance Print Selection_stm where
prt i e = case e of
SselOne exp stm -> prPrec i 0 (concatD [doc (showString "if"), doc (showString "("), prt 0 exp, doc (showString ")"), prt 0 stm])
SselTwo exp stm1 stm2 -> prPrec i 0 (concatD [doc (showString "if"), doc (showString "("), prt 0 exp, doc (showString ")"), prt 0 stm1, doc (showString "else"), prt 0 stm2])
SselThree exp stm -> prPrec i 0 (concatD [doc (showString "switch"), doc (showString "("), prt 0 exp, doc (showString ")"), prt 0 stm])
instance Print Iter_stm where
prt i e = case e of
SiterOne exp stm -> prPrec i 0 (concatD [doc (showString "while"), doc (showString "("), prt 0 exp, doc (showString ")"), prt 0 stm])
SiterTwo stm exp -> prPrec i 0 (concatD [doc (showString "do"), prt 0 stm, doc (showString "while"), doc (showString "("), prt 0 exp, doc (showString ")"), doc (showString ";")])
SiterThree expressionstm1 expressionstm2 stm -> prPrec i 0 (concatD [doc (showString "for"), doc (showString "("), prt 0 expressionstm1, prt 0 expressionstm2, doc (showString ")"), prt 0 stm])
SiterFour expressionstm1 expressionstm2 exp stm -> prPrec i 0 (concatD [doc (showString "for"), doc (showString "("), prt 0 expressionstm1, prt 0 expressionstm2, prt 0 exp, doc (showString ")"), prt 0 stm])
instance Print Jump_stm where
prt i e = case e of
SjumpOne id -> prPrec i 0 (concatD [doc (showString "goto"), prt 0 id, doc (showString ";")])
SjumpTwo -> prPrec i 0 (concatD [doc (showString "continue"), doc (showString ";")])
SjumpThree -> prPrec i 0 (concatD [doc (showString "break"), doc (showString ";")])
SjumpFour -> prPrec i 0 (concatD [doc (showString "return"), doc (showString ";")])
SjumpFive exp -> prPrec i 0 (concatD [doc (showString "return"), prt 0 exp, doc (showString ";")])
instance Print Exp where
prt i e = case e of
Ecomma exp1 exp2 -> prPrec i 0 (concatD [prt 0 exp1, doc (showString ","), prt 2 exp2])
Eassign exp1 assignmentop exp2 -> prPrec i 2 (concatD [prt 15 exp1, prt 0 assignmentop, prt 2 exp2])
Econdition exp1 exp2 exp3 -> prPrec i 3 (concatD [prt 4 exp1, doc (showString "?"), prt 0 exp2, doc (showString ":"), prt 3 exp3])
Elor exp1 exp2 -> prPrec i 4 (concatD [prt 4 exp1, doc (showString "||"), prt 5 exp2])
Eland exp1 exp2 -> prPrec i 5 (concatD [prt 5 exp1, doc (showString "&&"), prt 6 exp2])
Ebitor exp1 exp2 -> prPrec i 6 (concatD [prt 6 exp1, doc (showString "|"), prt 7 exp2])
Ebitexor exp1 exp2 -> prPrec i 7 (concatD [prt 7 exp1, doc (showString "^"), prt 8 exp2])
Ebitand exp1 exp2 -> prPrec i 8 (concatD [prt 8 exp1, doc (showString "&"), prt 9 exp2])
Eeq exp1 exp2 -> prPrec i 9 (concatD [prt 9 exp1, doc (showString "=="), prt 10 exp2])
Eneq exp1 exp2 -> prPrec i 9 (concatD [prt 9 exp1, doc (showString "!="), prt 10 exp2])
Elthen exp1 exp2 -> prPrec i 10 (concatD [prt 10 exp1, doc (showString "<"), prt 11 exp2])
Egrthen exp1 exp2 -> prPrec i 10 (concatD [prt 10 exp1, doc (showString ">"), prt 11 exp2])
Ele exp1 exp2 -> prPrec i 10 (concatD [prt 10 exp1, doc (showString "<="), prt 11 exp2])
Ege exp1 exp2 -> prPrec i 10 (concatD [prt 10 exp1, doc (showString ">="), prt 11 exp2])
Eleft exp1 exp2 -> prPrec i 11 (concatD [prt 11 exp1, doc (showString "<<"), prt 12 exp2])
Eright exp1 exp2 -> prPrec i 11 (concatD [prt 11 exp1, doc (showString ">>"), prt 12 exp2])
Eplus exp1 exp2 -> prPrec i 12 (concatD [prt 12 exp1, doc (showString "+"), prt 13 exp2])
Eminus exp1 exp2 -> prPrec i 12 (concatD [prt 12 exp1, doc (showString "-"), prt 13 exp2])
Etimes exp1 exp2 -> prPrec i 13 (concatD [prt 13 exp1, doc (showString "*"), prt 14 exp2])
Ediv exp1 exp2 -> prPrec i 13 (concatD [prt 13 exp1, doc (showString "/"), prt 14 exp2])
Emod exp1 exp2 -> prPrec i 13 (concatD [prt 13 exp1, doc (showString "%"), prt 14 exp2])
Etypeconv typename exp -> prPrec i 14 (concatD [doc (showString "("), prt 0 typename, doc (showString ")"), prt 14 exp])
Epreinc exp -> prPrec i 15 (concatD [doc (showString "++"), prt 15 exp])
Epredec exp -> prPrec i 15 (concatD [doc (showString "--"), prt 15 exp])
Epreop unaryoperator exp -> prPrec i 15 (concatD [prt 0 unaryoperator, prt 14 exp])
Ebytesexpr exp -> prPrec i 15 (concatD [doc (showString "sizeof"), prt 15 exp])
Ebytestype typename -> prPrec i 15 (concatD [doc (showString "sizeof"), doc (showString "("), prt 0 typename, doc (showString ")")])
Earray exp1 exp2 -> prPrec i 16 (concatD [prt 16 exp1, doc (showString "["), prt 0 exp2, doc (showString "]")])
Efunk exp -> prPrec i 16 (concatD [prt 16 exp, doc (showString "("), doc (showString ")")])
Efunkpar exp exps -> prPrec i 16 (concatD [prt 16 exp, doc (showString "("), prt 2 exps, doc (showString ")")])
Eselect exp id -> prPrec i 16 (concatD [prt 16 exp, doc (showString "."), prt 0 id])
Epoint exp id -> prPrec i 16 (concatD [prt 16 exp, doc (showString "->"), prt 0 id])
Epostinc exp -> prPrec i 16 (concatD [prt 16 exp, doc (showString "++")])
Epostdec exp -> prPrec i 16 (concatD [prt 16 exp, doc (showString "--")])
Evar id -> prPrec i 17 (concatD [prt 0 id])
Econst constant -> prPrec i 17 (concatD [prt 0 constant])
Estring str -> prPrec i 17 (concatD [prt 0 str])
prtList 2 [x] = (concatD [prt 2 x])
prtList 2 (x:xs) = (concatD [prt 2 x, doc (showString ","), prt 2 xs])
instance Print Constant where
prt i e = case e of
Efloat d -> prPrec i 0 (concatD [prt 0 d])
Echar c -> prPrec i 0 (concatD [prt 0 c])
Eunsigned unsigned -> prPrec i 0 (concatD [prt 0 unsigned])
Elong long -> prPrec i 0 (concatD [prt 0 long])
Eunsignlong unsignedlong -> prPrec i 0 (concatD [prt 0 unsignedlong])
Ehexadec hexadecimal -> prPrec i 0 (concatD [prt 0 hexadecimal])
Ehexaunsign hexunsigned -> prPrec i 0 (concatD [prt 0 hexunsigned])
Ehexalong hexlong -> prPrec i 0 (concatD [prt 0 hexlong])
Ehexaunslong hexunslong -> prPrec i 0 (concatD [prt 0 hexunslong])
Eoctal octal -> prPrec i 0 (concatD [prt 0 octal])
Eoctalunsign octalunsigned -> prPrec i 0 (concatD [prt 0 octalunsigned])
Eoctallong octallong -> prPrec i 0 (concatD [prt 0 octallong])
Eoctalunslong octalunslong -> prPrec i 0 (concatD [prt 0 octalunslong])
Ecdouble cdouble -> prPrec i 0 (concatD [prt 0 cdouble])
Ecfloat cfloat -> prPrec i 0 (concatD [prt 0 cfloat])
Eclongdouble clongdouble -> prPrec i 0 (concatD [prt 0 clongdouble])
Eint n -> prPrec i 0 (concatD [prt 0 n])
Elonger n -> prPrec i 0 (concatD [prt 0 n])
Edouble d -> prPrec i 0 (concatD [prt 0 d])
instance Print Constant_expression where
prt i e = case e of
Especial exp -> prPrec i 0 (concatD [prt 3 exp])
instance Print Unary_operator where
prt i e = case e of
Address -> prPrec i 0 (concatD [doc (showString "&")])
Indirection -> prPrec i 0 (concatD [doc (showString "*")])
Plus -> prPrec i 0 (concatD [doc (showString "+")])
Negative -> prPrec i 0 (concatD [doc (showString "-")])
Complement -> prPrec i 0 (concatD [doc (showString "~")])
Logicalneg -> prPrec i 0 (concatD [doc (showString "!")])
instance Print Assignment_op where
prt i e = case e of
Assign -> prPrec i 0 (concatD [doc (showString "=")])
AssignMul -> prPrec i 0 (concatD [doc (showString "*=")])
AssignDiv -> prPrec i 0 (concatD [doc (showString "/=")])
AssignMod -> prPrec i 0 (concatD [doc (showString "%=")])
AssignAdd -> prPrec i 0 (concatD [doc (showString "+=")])
AssignSub -> prPrec i 0 (concatD [doc (showString "-=")])
AssignLeft -> prPrec i 0 (concatD [doc (showString "<<=")])
AssignRight -> prPrec i 0 (concatD [doc (showString ">>=")])
AssignAnd -> prPrec i 0 (concatD [doc (showString "&=")])
AssignXor -> prPrec i 0 (concatD [doc (showString "^=")])
AssignOr -> prPrec i 0 (concatD [doc (showString "|=")])
|
aufheben/Y86
|
Compiler/lab/C/PrintC.hs
|
mit
| 23,864 | 0 | 16 | 4,995 | 11,459 | 5,571 | 5,888 | 376 | 12 |
module Mortgage.Money (
Money
) where
import Test.QuickCheck
import Text.Printf
import Data.Ratio
data Money = Money {-# UNPACK #-} !Double
instance Show Money where
show (Money amt) = printf "%.2f" amt
-- round to 0.01
instance Eq Money where
(Money x) == (Money y) = round (100*x) == round (100*y)
instance Ord Money where
compare (Money x) (Money y) = compare (round (100*x)) (round (100*y))
instance Num Money where
(+) (Money x) (Money y) = Money (x+y)
(-) (Money x) (Money y) = Money (x-y)
(*) (Money x) (Money y) = Money (x*y)
negate (Money x) = Money (negate x)
abs (Money x) = Money (abs x)
signum (Money x)
| x == 0 = 0
| x > 0 = 1
| x < 0 = -1
fromInteger i = Money (fromIntegral i)
instance Fractional Money where
(/) (Money x) (Money y) = Money (x / y)
fromRational r = Money $ (fromIntegral . numerator $ r) / (fromIntegral . denominator $ r)
instance Real Money where
toRational (Money x) = toRational x
instance RealFrac Money where
properFraction (Money x) = (y, Money (x - fromIntegral y))
where y = floor x
instance Arbitrary Money where
arbitrary = fmap Money (choose (0, 1000000000))
|
wangbj/MortageCalc
|
src/Mortgage/Money.hs
|
mit
| 1,247 | 0 | 10 | 346 | 592 | 302 | 290 | 33 | 0 |
{-****************************************************************************
* Hamster Balls *
* Purpose: Common data types shared by other modules *
* Author: David, Harley, Alex, Matt *
* Copyright (c) Yale University, 2010 *
****************************************************************************-}
module Common where
import Vec3d
import FRP.Yampa
import Graphics.Rendering.OpenGL
import Graphics.Rendering.OpenGL.GL.CoordTrans
import System.IO
import System.IO.Unsafe (unsafePerformIO)
import Control.Concurrent
------------------------------------------------------------------------------
-- Debugging routines. Couldn't have made it without these
------------------------------------------------------------------------------
debug :: (Show a) => a -> t -> t
debug s x = unsafePerformIO (print s) `seq` x
debugShow, debugShow2 :: (Show a) => a -> a
debugShow x = debug ("debug: " ++ show x) x -- only for SHOWable objects
debugShow2 x = debug (show x) x -- only for SHOWable objects
debugMaybe :: String -> t -> t
debugMaybe s x = if s /= "" then debug s x else x
-- The following is for debugging purposes only
--instance Show a => Show (Event a) where
-- show NoEvent = "NoEvent"
-- show (Event a) = "Event " ++ (show a)
----------------------------------------------
------------------------------------------------------------------------------
-- ReactChan: queue changes requested from different threads to apply sequentially
------------------------------------------------------------------------------
type ReactChan a = Chan (a -> a)
addToReact :: ReactChan a -> (a -> a) -> IO ()
addToReact rch f = writeChan rch f
getReactInput :: ReactChan a -> a -> IO a
getReactInput rch old = do
f <- readChan rch
return $ f old
data GameConfig = GameConfig {
gcFullscreen :: Bool,
gcPlayerName :: String,
gcTracker :: String}
-- width MUST be divisible by 4
-- height MUST be divisible by 3
width, height :: GLint
(width,height) = (640, 480) --if fullscreen then (1600,1200) else (640,480)
widthf, heightf :: GLdouble
widthf = fromRational $ toRational width
heightf = fromRational $ toRational height
centerCoordX, centerCoordY :: Float
centerCoordX = fromIntegral width / 2
centerCoordY = fromIntegral height / 2
sensitivity :: Float
sensitivity = pi/(fromIntegral $ width `div` 4)
initFrustum :: IO ()
initFrustum = do
loadIdentity
let near = 0.8
far = 1000
right = 0.4
top = 0.3
frustum (-right) right (-top) top near far
-- TODO: explain this
lookAt (Vertex3 0 0 0) (Vertex3 1 0 0) (Vector3 0 0 1)
--bound lo hi a = max lo $ min hi a
type ID = Int
type Position3 = Vec3d
type Velocity3 = Vec3d
type Acceleration3 = Vec3d
type Color3 = Vec3d
data Player = Player {
playerID :: !ID,
playerPos :: !Position3,
playerVel :: !Velocity3,
playerAcc :: !Acceleration3,
playerView :: !(Float,Float), -- theta, phi
playerRadius :: !Float,
playerLife :: !Float,
playerEnergy :: !Float,
playerColor :: !Common.Color3,
playerName :: !String
}
deriving (Show, Eq)
data Laser = Laser {
laserID :: !ID,
laserpID :: !ID,
laserPos :: !Position3,
laserVel :: !Velocity3,
laserStr :: !Float,
laserColor :: !Common.Color3
}
deriving (Show, Eq)
data Hit = Hit {
player1ID :: !ID,
player2ID :: !ID,
hitLaserID :: !ID,
hitStr :: !Float
}
deriving (Show, Eq)
-- Particle Position Depth
data Particle = Particle {
particlePos :: !Position3,
particleVel :: !Vec3d,
particleEnergy :: !Float,
particleDepth :: !Int
}
deriving (Show, Eq)
-- Not in use now. Instead, model as a list of ObjectSFs (representing particles). Makes simpler
data ParticleSystem = ParticleSystem {
particlePV :: [(Vec3d,Vec3d)],
particlesMax :: Float,
particlesEnergy :: !Float
}
deriving (Show, Eq)
-- TODO: keep track of previous location of display text
data ScoreBoard = ScoreBoard {
sbScores :: ![(Player, Int)] -- Player and Score
}
deriving (Show, Eq)
data PowerUpType = StrengthenLaser !Float
| XRayVision
| DecreaseRadius !Float
deriving Eq
data PowerUp = PowerUp {
powerupPos :: !Position3,
powerupRadius :: !Float,
powerupType :: !PowerUpType,
powerupView :: !(Float,Float) -- theta, phi -- make it spin
}
deriving Eq
instance Show PowerUp where
show PowerUp{powerupType=t} = "^" ++ show t ++ "^"
instance Show PowerUpType where
show (StrengthenLaser f) = "Plus " ++ show f
show XRayVision = "XRay"
show (DecreaseRadius f) = "Smaller by " ++ show f
data Obj = PlayerObj !Player
| LaserObj !Laser
deriving (Show, Eq)
------------------------------------------------------------------------------
-- Network messages between Server and Client
------------------------------------------------------------------------------
data SCMsg' = SCMsgInitialize !Player -- To initiatiate the joining player
| SCMsgPlayer !Player -- For updating pos
| SCMsgHit !Hit -- Announcing hits
| SCMsgSpawn !Obj -- For creating new objects
| SCMsgFrag !Player !Player -- For telling everyone player1 killed player2
| SCMsgRemove !Int -- Remove exiting player
deriving (Show, Eq)
data CSMsg' = CSMsgPlayer !Player -- Send when velocity changes
| CSMsgUpdate !Player -- Send periodic updates
| CSMsgLaser !Laser -- Send when a laser is shot by client
| CSMsgKillLaser !ID
| CSMsgDeath !Hit -- ID of killer and killed
| CSMsgExit !String -- Name of player that exits, requires unique player names
| CSMsgJoin !String -- Name of player that enters the game
deriving (Show, Eq)
type SCMsg = (ID, SCMsg') -- Server to Client, i.e. runs on Client
type CSMsg = (ID, CSMsg') -- Client to Server, i.e. runs on Server
dummySCMsg :: SCMsg
dummySCMsg = (-1,SCMsgHit (Hit {player1ID= -1,player2ID= -1,hitLaserID= -1,hitStr= -1}))
dummyCSMsg :: CSMsg
dummyCSMsg = (-1,CSMsgExit "dummy")
dummyPlayer :: Player
dummyPlayer = Player {playerID = 0,
playerPos = zeroVector,
playerVel = zeroVector,
playerAcc = zeroVector,
playerView = (0,0),
playerRadius = defRadius,
playerLife = maxLife,
playerEnergy = maxEnergy,
playerColor = Vec3d(0.5, 0.2, 0.7),
playerName = "Dummy"}
-- Values for initializing objects
defRadius :: Float
defRadius = 1.5
maxLife :: Float
maxLife = 100
maxEnergy :: Float
maxEnergy = 100
defLaserStr :: Float
defLaserStr = 10
printFlush :: String -> IO ()
printFlush s = do
print s
hFlush stdout
hFlush stderr
doIOevent :: Event (IO ()) -> IO ()
doIOevent (Event io) = io
doIOevent NoEvent = return ()
vecToColor :: Vec3d -> Color4 GLfloat
vecToColor (Vec3d (x,y,z)) = Color4 x y z 1
computeColor :: Player -> Color4 GLfloat
computeColor (Player {playerColor = Vec3d (r,g,b),
playerLife = life}) = vecToColor (Vec3d ((1 - life/maxLife) * (1-r) + r, g, b))
--deprecated in favor of edgeBy
--detectChangeSF :: Eq a => SF (a, a) (Event a, a)
--detectChangeSF = arr (\(new,old) -> (if new == old then NoEvent else Event new, new))
|
harley/hamball
|
src/Common.hs
|
mit
| 7,661 | 0 | 13 | 1,981 | 1,735 | 978 | 757 | 258 | 2 |
f x = if x > 2
then do
print "x"
else do
print "y"
|
itchyny/vim-haskell-indent
|
test/if/ifthendo.in.hs
|
mit
| 51 | 1 | 8 | 15 | 36 | 15 | 21 | -1 | -1 |
module Test where
import TambaraYamagami as TY
import Stringnet as S
import Data.Tree as T
import Data.Matrix as M
import Data.Maybe
import Finite
import Algebra
obj = (toObject M) `TY.tensorO` (toObject M) `TY.tensorO` (toObject M)
m = toObject M
o = toObject one
notOne = toObject $ AE $ AElement 1
-- a snake equation
snake o = idMorphism o == ((ev o) `TY.tensorM` (idMorphism o))
`TY.compose` (alpha o o o)
`TY.compose` ((idMorphism o) `TY.tensorM` (coev o))
-- ((ab)c)d) -> (ab)(cd) -> a(b(cd))
pentagonLHS a b c d =
(alpha a b (c `TY.tensorO` d))
`TY.compose` (alpha (a `TY.tensorO` b) c d)
-- ((ab)c)d -> (a(bc))d -> a((bc)d) -> a(b(cd))
pentagonRHS a b c d =
((idMorphism a) `tensorM` (alpha b c d))
`TY.compose` (alpha a (b `TY.tensorO` c) d)
`TY.compose` ((alpha a b c) `tensorM` idMorphism d)
--FIXME: pentagon m m m m
pentagon a b c d = (pentagonLHS a b c d) == (pentagonRHS a b c d)
-- 81 is interesting
-- finalET = map (\ib -> map (substO (initialLabel ib)) $ map (S.objectLabel S.finalSN) $ S.flatten S.finalEdgeTree) (allElements :: [InitialBasisElement])
-- old (finalMorphism) testing
tree = fmap (\x -> case x of
Nothing -> "+"
Just e -> show e
) $ toTree S.finalMorphism
prin = (putStr. T.drawTree) tree
cList = toCompositionList S.finalMorphism
leaves = catMaybes $ T.flatten $ toTree S.finalMorphism
leftT (TensorM a b) = a
rightT (TensorM a b) = b
-- leftC (Compose a b) = a
-- rightC (Compose a b) = b
-- bad = Compose (AlphaI (Star (OVar RightLoop)) (OVar RightLoop) (Star One)) (Compose (RhoI (OVar RightLoop)) (Coev (OVar RightLoop)))
-- small = (Compose (TensorM (PivotalJI (Star (OVar RightLoop))) (LambdaI (OVar RightLoop))) (Coev (OVar RightLoop)))
-- -- new testing
-- -- TODO: Calculate a matrix for addCoev. What I need to do is figure
-- -- out how to turn the monad actions into a list of actions.
|
PaulGustafson/stringnet
|
Test.hs
|
mit
| 1,938 | 0 | 12 | 422 | 541 | 303 | 238 | 32 | 2 |
-- |Module for representing and manipulating complex numbers.
module Cplx where
-- |Basic data type for storing complex numbers.
data Cplx = Cplx {re :: Double, im :: Double } deriving (Eq)
-- re Cplx a b = a
-- im Cplx a b = b
-- |Function 'conj' returns a complex conjugate of a complex number.
conj :: Cplx -> Cplx
conj c = Cplx (re c) (-1*( im c))
-- |Funciton 'cabs' returns the absolute value of a complex number. In contrast
-- to the 'abs' function overloaded from 'Num', this function returns 'Double'.
cabs :: Cplx -> Double
cabs c = (sqrt $ (re c)^2 + (im c)^2)
-- |Operator for creating new complex number from two 'Double' numbers used as
-- a real and as an imaginary part.
(+:) :: Double -> Double -> Cplx
a +: b = Cplx a b
-- |Functions overloaded from Num class. In particular they implement the
-- arithmetic on complex numbers.
instance Num Cplx where
a + b = (re a + re b) +: (im a + im b)
a * b = (re a * re b - im a * im b) +: (im a * re b + re a * im b)
abs a = Cplx (cabs a) 0
negate a = (negate $ re a) +: (negate $ im a)
signum a = a
fromInteger a = ((fromInteger a) :: Double) +: 0.0
-- |Function 'show' overloaded from 'Show' class. Complex numbers are displayed
-- as pairs.
instance Show Cplx where
show (Cplx a b) = "(" ++ show a ++ "," ++ show b ++ ")"
|
jmiszczak/hoqus
|
alternative/Cplx.hs
|
mit
| 1,306 | 0 | 11 | 295 | 414 | 214 | 200 | 17 | 1 |
{-# LANGUAGE PatternSignatures #-}
{-# LANGUAGE PatternSignatures #-}
{-# LANGUAGE DoAndIfThenElse #-}
module Operate.Tutor where
import Operate.Types
import Types.Signed
import Types.Config
import Operate.Bank
import Gateway.CGI
import qualified Operate.Param as P
import qualified Control.Aufgabe as A
import qualified Control.Student as S
import Challenger.Partial
import Control.Types
( toString, fromCGI, Name, Typ , Remark, HiLo (..), Status (..)
, Oks (..), Nos (..), Time , Wert (..), MNr, SNr, VNr, ANr(..), UNr
, TimeStatus (..)
)
import Control.Time
import Control.Time.CGI
import qualified Control.Time.CGI as Control.Time
import Autolib.Reporter.IO.Type
import Autolib.ToDoc
import Autolib.Reader
-- import qualified Text.XHtml
import System.Random
import Data.Maybe
import Data.Tree ( flatten )
import qualified Debug
import qualified Control.Exception as CE
-- | ändere aufgaben-konfiguration (nur für tutor).
-- NOTE: do not use "server" argument,
-- since the server URL is contained in "mk"
edit_aufgabe server mk mauf vnr manr type_click =
edit_aufgabe_extra server mk mauf vnr manr type_click ( \ a -> True )
edit_aufgabe_extra _ mk mauf vnr manr type_click prop = case mk of
-- Make p doc ( fun :: conf -> Var p i b ) verify ex -> do
mk -> do
let t = fromCGI $ Operate.Types.task mk
server = Operate.Types.server mk
candidates <- io $ A.get_typed t
`CE.catch` \ (CE.SomeException any) -> return []
let others = filter prop candidates
( name :: Name ) <- fmap fromCGI
$ defaulted_textfield "Name"
$ case mauf of Nothing -> foldl1 (++)
[ toString t , "-"
, show $ succ $ length others
]
Just auf -> toString $ A.name auf
( remark :: Remark ) <- fmap fromCGI
$ defaulted_textarea "Remark"
$ case mauf of Nothing -> "noch keine Hinweise"
Just auf -> toString $ A.remark auf
open row
plain "Highscore"
( mhilo :: Maybe HiLo ) <- selector'
( case mauf of Nothing -> "XX"
Just auf -> show $ A.highscore auf )
$ do
( x :: HiLo ) <- [ minBound .. maxBound ]
return ( show x, x )
close -- row
open row
plain "Status"
( mstatus :: Maybe Status ) <- selector'
( case mauf of Nothing -> "XX"
Just auf -> show $ A.status auf )
$ do
( x :: Status ) <- [ minBound .. maxBound ]
return ( show x, x )
close -- row
(dflt_von,dflt_bis) <- io Control.Time.defaults
( von :: Time ) <- Control.Time.edit "von" $ Just
$ case mauf of Nothing -> dflt_von
Just auf -> A.von auf
( bis ::Time ) <- Control.Time.edit "bis" $ Just
$ case mauf of Nothing -> dflt_bis
Just auf -> A.bis auf
moth <-
click_choice_with_default 0 "importiere Konfiguration"
$ ("(previous/default)", mauf) : do
oth <- others
return ( toString $ A.name oth , Just oth )
let ( mproto, type_changed ) = case moth of
Just oth -> ( moth, False )
Nothing -> ( mauf, type_click )
-- nimm default-config, falls type change
-- FIXME: ist das sinnvoll bei import?
signed_conf <-
task_config_editor "Konfiguration"
mk mproto
-- check configuration (is implied)
close -- table
br
let sig = signature signed_conf
( task, CString conf ) = contents signed_conf
return $ A.Aufgabe
{ A.anr = ANr 0 -- error "Super.anr" -- intentionally
, A.vnr = vnr
, A.name = name
, A.server = fromCGI server
, A.typ = fromCGI task
, A.config = fromCGI conf
, A.signature = fromCGI sig
, A.remark = remark
, A.highscore = fromMaybe Keine mhilo
, A.status = fromMaybe Demo mstatus
, A.von = von
, A.bis = bis
, A.timeStatus = Control.Types.Early -- ist egal
}
-- | matrikelnummer zum aufgabenlösen:
-- tutor bekommt eine gewürfelt (und kann neu würfeln)
-- student bekommt genau seine eigene
get_stud tutor stud =
if tutor
then do
hr
m0 <- io $ randomRIO (0, 999999 :: Int)
-- neu würfeln nur bei änderungen oberhalb von hier
plain "eine gewürfelte Matrikelnummer:"
mat <- with ( show m0 ) $ textfield ( show m0 )
-- falls tutor, dann geht es hier nur um die matrikelnr
return $ stud { S.mnr = fromCGI mat
, S.snr = error "gibt es nicht"
}
else do
return stud
-- | bestimme aufgaben-typ (maker)
-- für tutor: wählbar
-- für student: fixiert (ohne dialog)
find_mk fallback_server tutor mauf = do
let pre_mk = fmap (toString . A.typ) mauf
server = case mauf of
Nothing -> fallback_server
Just auf -> toString $ A.server auf
if tutor
then do
hr
h3 "Parameter dieser Aufgabe:"
open btable -- will be closed in edit_aufgabe (tutor branch)
open row ; plain "Server"
mserver <- textfield server
mod <- submit "reload"
close -- row
if isNothing mauf || mod then do
-- blank
let serv = case mserver of
Just s -> s
Nothing -> server
tmk <- io $ get_task_tree serv
it <- tree_choice pre_mk
$ tt_to_tree serv tmk
return ( it, True ) -- FIXME
else do
open row
plain "Task Type"
Just pre <- return $ pre_mk
plain pre
close -- row
return ( make server pre , False )
else do
Just pre <- return $ pre_mk
return ( make server pre , False )
|
marcellussiegburg/autotool
|
db/src/Operate/Tutor.hs
|
gpl-2.0
| 6,412 | 81 | 26 | 2,492 | 1,544 | 828 | 716 | 144 | 8 |
module HandlerUtils where
import Control.Monad.Reader
import qualified Data.ByteString.Char8 as B
import Data.List
import RoomsAndClients
import CoreTypes
import Actions
thisClient :: Reader (ClientIndex, IRnC) ClientInfo
thisClient = do
(ci, rnc) <- ask
return $ rnc `client` ci
thisRoom :: Reader (ClientIndex, IRnC) RoomInfo
thisRoom = do
(ci, rnc) <- ask
let ri = clientRoom rnc ci
return $ rnc `room` ri
clientNick :: Reader (ClientIndex, IRnC) B.ByteString
clientNick = liftM nick thisClient
roomOthersChans :: Reader (ClientIndex, IRnC) [ClientChan]
roomOthersChans = do
(ci, rnc) <- ask
let ri = clientRoom rnc ci
return $ map (sendChan . client rnc) $ filter (/= ci) (roomClients rnc ri)
roomSameClanChans :: Reader (ClientIndex, IRnC) [ClientChan]
roomSameClanChans = do
(ci, rnc) <- ask
let ri = clientRoom rnc ci
let otherRoomClients = map (client rnc) . filter (/= ci) $ roomClients rnc ri
let cl = rnc `client` ci
let sameClanClients = Prelude.filter (\c -> clientClan c == clientClan cl) otherRoomClients
return $ map sendChan sameClanClients
roomClientsChans :: Reader (ClientIndex, IRnC) [ClientChan]
roomClientsChans = do
(ci, rnc) <- ask
let ri = clientRoom rnc ci
return $ map (sendChan . client rnc) (roomClients rnc ri)
thisClientChans :: Reader (ClientIndex, IRnC) [ClientChan]
thisClientChans = do
(ci, rnc) <- ask
return [sendChan (rnc `client` ci)]
answerClient :: [B.ByteString] -> Reader (ClientIndex, IRnC) [Action]
answerClient msg = liftM ((: []) . flip AnswerClients msg) thisClientChans
allRoomInfos :: Reader (a, IRnC) [RoomInfo]
allRoomInfos = liftM ((\irnc -> map (room irnc) $ allRooms irnc) . snd) ask
clientByNick :: B.ByteString -> Reader (ClientIndex, IRnC) (Maybe ClientIndex)
clientByNick n = do
(_, rnc) <- ask
let allClientIDs = allClients rnc
return $ find (\clId -> n == nick (client rnc clId)) allClientIDs
|
jeffchao/hedgewars-accessible
|
gameServer/HandlerUtils.hs
|
gpl-2.0
| 1,956 | 0 | 14 | 381 | 765 | 402 | 363 | 49 | 1 |
module Regular where
import Text.Regex.PCRE
import qualified Data.IntMap.Strict as IntMap
import qualified Data.String.Utils as SU
import Data.List
toBeEscaped = "\\/[]().{}?*+|"
escape :: String -> String
escape s = foldl (\b a -> SU.replace [a] ("\\" ++ [a]) b) s toBeEscaped
data RE = LineStart |
Word |
ConstWord String |
Number |
ConstChar Char |
Parenthesis |
Brackets |
HostName deriving (Eq, Ord)
reToRegExp :: RE -> String
reToRegExp LineStart = "^"
reToRegExp Number = "\\d+"
reToRegExp Word = "[a-zA-Z]+"
reToRegExp (ConstWord word) = escape word
reToRegExp (ConstChar c) = escape [c]
reToRegExp Parenthesis = "\\([^)]*\\)"
reToRegExp Brackets = "\\[[^)]*\\]"
reToRegExp HostName = "([\\w-_]+\\.)+([\\w-_]+)"
costFuncRE :: RE -> Int
costFuncRE LineStart = 0
costFuncRE Number = 5
costFuncRE Word = 5
costFuncRE (ConstWord _) = 1
costFuncRE (ConstChar _) = 1
costFuncRE Parenthesis = 1
costFuncRE Brackets = 1
costFuncRE HostName = 1
instance Show RE where
show = show . reToRegExp
reMatches :: RE -> String -> Bool
reMatches re s = s =~ (reToRegExp re)
reMatchesS :: RE -> String -> String
reMatchesS re s = s =~ (reToRegExp re)
findMatchingREs :: String -> [RE]
findMatchingREs s =
let constWord = [(ConstWord s)]
withWord = if (reMatches Word s) then (Word:constWord) else constWord
withNum = if (reMatches Number s) then (Number:withWord) else withWord
in withNum
type REChain = [RE]
toRegExp :: REChain -> String
--toRegExp = concat . (intersperse "(\\s*)") . (map reToRegExp)
toRegExp (LineStart:rest) = (reToRegExp LineStart) ++ (toRegExp rest)
toRegExp rest = unwords . (map reToRegExp) $ rest
costFuncREChain :: REChain -> Int
costFuncREChain = sum . (map costFuncRE)
chainMatches :: REChain -> String -> Bool
chainMatches reChain line = line =~ (toRegExp reChain)
chainMatchesS :: REChain -> String -> String
chainMatchesS reChain line = line =~ (toRegExp reChain)
-- Does one of these REChain's match this line?
anyREMatches :: [REChain] -> String -> Bool
anyREMatches reChains line = any (\x -> chainMatches x line) reChains
-- Does this REChain match any of these lines?
anyLineMatches :: REChain -> [String] -> Bool
anyLineMatches reChain logLines = any (chainMatches reChain) logLines
data REMatchCache = REMatchCache { rmcChain :: REChain,
matchData :: IntMap.IntMap Int }
buildCache :: REChain -> [String] -> REMatchCache
buildCache re logLines =
REMatchCache re $ IntMap.fromList $ foldl collector [] $ zip [0..] logLines
where collector collected (index, line) = (index, if re == [LineStart] then 1 else (length (chainMatchesS re line))):collected
isWord :: String -> Bool
isWord x = x =~ "\\w*"
|
afroisalreadyinu/LogAnalyzer
|
daemon/Regular.hs
|
gpl-2.0
| 2,785 | 0 | 13 | 569 | 902 | 486 | 416 | 68 | 3 |
---------------------------------------------------------------------------
-- This file is part of grammata.
--
-- grammata 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.
--
-- grammata 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 grammata. If not, see <http://www.gnu.org/licenses/>.
---------------------------------------------------------------------------
---------------------------------------------------------------------------
-- | Module : Grammata.Machine.Storage
-- Description : Grammata Polyparadigmatic Storages
-- Maintainer : [email protected]
-- Stability : stable
-- Portability : portable
-- Copyright : (c) Sascha Rechenberger, 2014, 2015
-- License : GPL-3
---------------------------------------------------------------------------
module Grammata.Machine.Storage
(
-- * Submodules
module Grammata.Machine.Storage.Functional,
module Grammata.Machine.Storage.Imperative,
module Grammata.Machine.Storage.Logical,
-- * Classes
Initializable (..)
)
where
import Grammata.Machine.Storage.Functional
import Grammata.Machine.Storage.Imperative
import Grammata.Machine.Storage.Logical
-- | Generalization of storage initialization.
class Initializable mem where
new :: mem
instance Initializable (IStorage ident value) where
new = newIStorage
instance Initializable (FStorage value) where
new = newFStorage
instance Initializable (LStorage ident value) where
new = newLStorage
|
SRechenberger/grammata
|
src/Grammata/Machine/Storage.hs
|
gpl-3.0
| 1,964 | 0 | 7 | 317 | 164 | 111 | 53 | 17 | 0 |
-- | Creates paths based on file\'s hashes.
module Util.HashDir (hashDir, hashDir') where
import Prelude
import Data.List
import qualified Data.Text as T
import System.FilePath
-- | Splits the hash of the file in four parts and constucts a four levels
-- directory path.
hashDir :: T.Text -> FilePath
hashDir = foldl' (</>) "" . map T.unpack . hashDir'
-- | Splits the hash of the file in four parts.
hashDir' :: T.Text -> [T.Text]
hashDir' hash =
let (p1, hash') = T.splitAt 2 hash
(p2, hash'') = T.splitAt 2 hash'
(p3, p4) = T.splitAt 2 hash''
in [p1, p2, p3, p4]
|
RaphaelJ/getwebb.org
|
Util/HashDir.hs
|
gpl-3.0
| 594 | 0 | 10 | 129 | 174 | 99 | 75 | 13 | 1 |
{-GPLV3.0 or later copyright Timothy Hobbs <[email protected]>
Copyright 2012.
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 Graphics.UI.Gtk.Custom.JSInput where
{-
Generates a simple form which allows users to input JSON values of type Bool, Rational and String.
Saving of the form data is performed on "focus change".
This means that you provide jsInputNew with a special callback
and that callback gets run every time the user changes a value in the form.
You can then save the contents of the form,
or sync them to your application's own internal state.
-}
import Text.JSON
import Data.Ratio
import Graphics.UI.Gtk as GTK
import Data.IORef
import Control.Monad.IO.Class
{-main :: IO ()
main = do
GTK.initGUI -- is start
window <- GTK.windowNew
let
feilds =
[("String",JSString $ toJSString "")
,("Bool",JSBool False)
,("Rational",JSRational False (0%1))]
jsInput <- jsInputNew feilds
(\newValuesR->
case newValuesR of
Ok values -> putStrLn $ show values
Error err -> putStrLn err)
GTK.containerAdd window jsInput
GTK.onDestroy window GTK.mainQuit
GTK.widgetShowAll window
GTK.mainGUI
return ()-}
jsInputNew ::
[(String,JSValue)] ->
(Result [(String,JSValue)] -> IO())->
IO Widget
jsInputNew
feilds
onUpdate
= do
vb <- GTK.vBoxNew False 0
let
(JSObject initialObject) = makeObj feilds
valuesIORef <- newIORef feilds
let
addFeild (key,value) = do
element <- case value of
JSBool checked -> do
b <- GTK.checkButtonNewWithLabel key
set b [toggleButtonActive := checked
,toggleButtonMode := True]
b `on` GTK.toggled $ do
values <- readIORef valuesIORef
value <- get b toggleButtonActive
let
newValues =
map
(\(k,v)->
case k == key of
True -> (k,JSBool value)
False -> (k,v))
values
writeIORef valuesIORef newValues
onUpdate $ Ok newValues
GTK.boxPackStart vb b GTK.PackNatural 0
return $ castToWidget b
r@JSRational{} -> do
hb <- hBoxNew False 0
l <- labelNew $ Just key
GTK.boxPackStart hb l GTK.PackNatural 0
e <- GTK.entryNew
entrySetText e $ encode r
e `on` GTK.focusOutEvent $ liftIO $ do
values <- readIORef valuesIORef
text <- get e entryText
let
valueR' = decode text
valueR =
case valueR' of
Ok (rational@JSRational{}) -> Ok rational
Ok _ -> Error "Not a rational."
Error err -> Error err
newValuesR =
case valueR of
Ok val ->
Ok $ map
(\(k,v)->
case k == key of
True -> (k, val)
False -> (k,v))
values
Error err -> Error err
case newValuesR of
Ok newValues -> writeIORef valuesIORef newValues
_ -> return ()
onUpdate $ newValuesR
return False
GTK.boxPackStart hb e GTK.PackNatural 0
GTK.boxPackStart vb hb GTK.PackNatural 0
return $ castToWidget hb
JSString jsstring -> do
hb <- vBoxNew False 0
l <- labelNew $ Just key
GTK.boxPackStart hb l GTK.PackNatural 0
tb <- GTK.textBufferNew Nothing
GTK.textBufferSetText tb $ fromJSString jsstring
tv <- GTK.textViewNewWithBuffer tb
tv `on` GTK.focusOutEvent $ liftIO $ do
values <- readIORef valuesIORef
text <- get tb textBufferText
let
newValuesR =
Ok $ map
(\(k,v)->
case k == key of
True -> (k, JSString $ toJSString text)
False -> (k,v))
values
case newValuesR of
Ok newValues -> writeIORef valuesIORef newValues
_ -> return ()
onUpdate $ newValuesR
return False
GTK.boxPackStart hb tv GTK.PackGrow 0
GTK.boxPackStart vb hb GTK.PackGrow 0
return $ castToWidget hb
_ -> return $ error "Unsupported value type. We only support Bool Rational and String, sorry!"
return ()
mapM addFeild feilds
return $ castToWidget vb
|
timthelion/gtk-jsinput
|
Graphics/UI/Gtk/Custom/JSInput.hs
|
gpl-3.0
| 4,633 | 0 | 34 | 1,301 | 1,045 | 497 | 548 | 104 | 12 |
module Main ( main ) where
import Control.Concurrent
import Network.FastCGI
action :: CGI CGIResult
action = do
setHeader "Content-type" "text/plain"
tid <- liftIO myThreadId
output $ unlines
[ "I am a FastCGI process!"
, "Hear me roar!"
, ""
, show tid
]
main :: IO ()
main = runFastCGIConcurrent' forkIO 10 action
|
PuZZleDucK/PuZZleDucK.ORG
|
test-html/haskell/FastCGI.hs
|
gpl-3.0
| 371 | 0 | 10 | 108 | 97 | 50 | 47 | 14 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.Analytics.Management.AccountUserLinks.List
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Lists account-user links for a given account.
--
-- /See:/ <https://developers.google.com/analytics/ Google Analytics API Reference> for @analytics.management.accountUserLinks.list@.
module Network.Google.Resource.Analytics.Management.AccountUserLinks.List
(
-- * REST Resource
ManagementAccountUserLinksListResource
-- * Creating a Request
, managementAccountUserLinksList
, ManagementAccountUserLinksList
-- * Request Lenses
, maullAccountId
, maullStartIndex
, maullMaxResults
) where
import Network.Google.Analytics.Types
import Network.Google.Prelude
-- | A resource alias for @analytics.management.accountUserLinks.list@ method which the
-- 'ManagementAccountUserLinksList' request conforms to.
type ManagementAccountUserLinksListResource =
"analytics" :>
"v3" :>
"management" :>
"accounts" :>
Capture "accountId" Text :>
"entityUserLinks" :>
QueryParam "start-index" (Textual Int32) :>
QueryParam "max-results" (Textual Int32) :>
QueryParam "alt" AltJSON :>
Get '[JSON] EntityUserLinks
-- | Lists account-user links for a given account.
--
-- /See:/ 'managementAccountUserLinksList' smart constructor.
data ManagementAccountUserLinksList = ManagementAccountUserLinksList'
{ _maullAccountId :: !Text
, _maullStartIndex :: !(Maybe (Textual Int32))
, _maullMaxResults :: !(Maybe (Textual Int32))
} deriving (Eq,Show,Data,Typeable,Generic)
-- | Creates a value of 'ManagementAccountUserLinksList' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'maullAccountId'
--
-- * 'maullStartIndex'
--
-- * 'maullMaxResults'
managementAccountUserLinksList
:: Text -- ^ 'maullAccountId'
-> ManagementAccountUserLinksList
managementAccountUserLinksList pMaullAccountId_ =
ManagementAccountUserLinksList'
{ _maullAccountId = pMaullAccountId_
, _maullStartIndex = Nothing
, _maullMaxResults = Nothing
}
-- | Account ID to retrieve the user links for.
maullAccountId :: Lens' ManagementAccountUserLinksList Text
maullAccountId
= lens _maullAccountId
(\ s a -> s{_maullAccountId = a})
-- | An index of the first account-user link to retrieve. Use this parameter
-- as a pagination mechanism along with the max-results parameter.
maullStartIndex :: Lens' ManagementAccountUserLinksList (Maybe Int32)
maullStartIndex
= lens _maullStartIndex
(\ s a -> s{_maullStartIndex = a})
. mapping _Coerce
-- | The maximum number of account-user links to include in this response.
maullMaxResults :: Lens' ManagementAccountUserLinksList (Maybe Int32)
maullMaxResults
= lens _maullMaxResults
(\ s a -> s{_maullMaxResults = a})
. mapping _Coerce
instance GoogleRequest ManagementAccountUserLinksList
where
type Rs ManagementAccountUserLinksList =
EntityUserLinks
type Scopes ManagementAccountUserLinksList =
'["https://www.googleapis.com/auth/analytics.manage.users",
"https://www.googleapis.com/auth/analytics.manage.users.readonly"]
requestClient ManagementAccountUserLinksList'{..}
= go _maullAccountId _maullStartIndex
_maullMaxResults
(Just AltJSON)
analyticsService
where go
= buildClient
(Proxy ::
Proxy ManagementAccountUserLinksListResource)
mempty
|
rueshyna/gogol
|
gogol-analytics/gen/Network/Google/Resource/Analytics/Management/AccountUserLinks/List.hs
|
mpl-2.0
| 4,424 | 0 | 16 | 1,003 | 513 | 300 | 213 | 82 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.Compute.Networks.UpdatePeering
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Updates the specified network peering with the data included in the
-- request Only the following fields can be modified:
-- NetworkPeering.export_custom_routes, and
-- NetworkPeering.import_custom_routes
--
-- /See:/ <https://developers.google.com/compute/docs/reference/latest/ Compute Engine API Reference> for @compute.networks.updatePeering@.
module Network.Google.Resource.Compute.Networks.UpdatePeering
(
-- * REST Resource
NetworksUpdatePeeringResource
-- * Creating a Request
, networksUpdatePeering
, NetworksUpdatePeering
-- * Request Lenses
, nupRequestId
, nupProject
, nupNetwork
, nupPayload
) where
import Network.Google.Compute.Types
import Network.Google.Prelude
-- | A resource alias for @compute.networks.updatePeering@ method which the
-- 'NetworksUpdatePeering' request conforms to.
type NetworksUpdatePeeringResource =
"compute" :>
"v1" :>
"projects" :>
Capture "project" Text :>
"global" :>
"networks" :>
Capture "network" Text :>
"updatePeering" :>
QueryParam "requestId" Text :>
QueryParam "alt" AltJSON :>
ReqBody '[JSON] NetworksUpdatePeeringRequest :>
Patch '[JSON] Operation
-- | Updates the specified network peering with the data included in the
-- request Only the following fields can be modified:
-- NetworkPeering.export_custom_routes, and
-- NetworkPeering.import_custom_routes
--
-- /See:/ 'networksUpdatePeering' smart constructor.
data NetworksUpdatePeering =
NetworksUpdatePeering'
{ _nupRequestId :: !(Maybe Text)
, _nupProject :: !Text
, _nupNetwork :: !Text
, _nupPayload :: !NetworksUpdatePeeringRequest
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'NetworksUpdatePeering' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'nupRequestId'
--
-- * 'nupProject'
--
-- * 'nupNetwork'
--
-- * 'nupPayload'
networksUpdatePeering
:: Text -- ^ 'nupProject'
-> Text -- ^ 'nupNetwork'
-> NetworksUpdatePeeringRequest -- ^ 'nupPayload'
-> NetworksUpdatePeering
networksUpdatePeering pNupProject_ pNupNetwork_ pNupPayload_ =
NetworksUpdatePeering'
{ _nupRequestId = Nothing
, _nupProject = pNupProject_
, _nupNetwork = pNupNetwork_
, _nupPayload = pNupPayload_
}
-- | An optional request ID to identify requests. Specify a unique request ID
-- so that if you must retry your request, the server will know to ignore
-- the request if it has already been completed. For example, consider a
-- situation where you make an initial request and the request times out.
-- If you make the request again with the same request ID, the server can
-- check if original operation with the same request ID was received, and
-- if so, will ignore the second request. This prevents clients from
-- accidentally creating duplicate commitments. The request ID must be a
-- valid UUID with the exception that zero UUID is not supported
-- (00000000-0000-0000-0000-000000000000).
nupRequestId :: Lens' NetworksUpdatePeering (Maybe Text)
nupRequestId
= lens _nupRequestId (\ s a -> s{_nupRequestId = a})
-- | Project ID for this request.
nupProject :: Lens' NetworksUpdatePeering Text
nupProject
= lens _nupProject (\ s a -> s{_nupProject = a})
-- | Name of the network resource which the updated peering is belonging to.
nupNetwork :: Lens' NetworksUpdatePeering Text
nupNetwork
= lens _nupNetwork (\ s a -> s{_nupNetwork = a})
-- | Multipart request metadata.
nupPayload :: Lens' NetworksUpdatePeering NetworksUpdatePeeringRequest
nupPayload
= lens _nupPayload (\ s a -> s{_nupPayload = a})
instance GoogleRequest NetworksUpdatePeering where
type Rs NetworksUpdatePeering = Operation
type Scopes NetworksUpdatePeering =
'["https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/compute"]
requestClient NetworksUpdatePeering'{..}
= go _nupProject _nupNetwork _nupRequestId
(Just AltJSON)
_nupPayload
computeService
where go
= buildClient
(Proxy :: Proxy NetworksUpdatePeeringResource)
mempty
|
brendanhay/gogol
|
gogol-compute/gen/Network/Google/Resource/Compute/Networks/UpdatePeering.hs
|
mpl-2.0
| 5,221 | 0 | 18 | 1,160 | 567 | 341 | 226 | 88 | 1 |
-- "Dao/Examples/FastNumbers.hs" a program for converting numbers expressed in
-- english to numerical values.
--
-- Copyright (C) 2008-2015 Ramin Honary.
--
-- Dao 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.
--
-- Dao 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 (see the file called "LICENSE"). If not, see the URL:
-- <http://www.gnu.org/licenses/agpl.html>.
-- | This program demonstrates how to create a simple natural language parsing program. The
-- documentation for this module is written as a tutorial which you can read from beginning to end.
-- Each function starts a new section of the tutorial.
--
-- We will create Dao production 'Dao.Rule.Rule's that can read a number written as a sentence in
-- the English language, and convert this number sentence to an 'Prelude.Integer' value, even if the
-- user makes minor spelling errors. For completeness, the inverse operation is also provided
-- (converting a 'Prelude.Integer' to an English language sentence). To accomplish this, we make
-- use of the 'Dao.Examples.FuzzyStrings.FuzzyString' data type we defined in an earlier exercise.
--
-- Lets consider a strategy for how we can convert to and from English language number expressions
-- 'Prelude.Integer's. First we need a way to map words to number values. The "Data.Map" module
-- provided by the Haskell Platform's "containers" package will work well for this purpose.
--
-- In the English language, there are a few words to symbolize numbers:
--
-- * Simple counting words like "zero" through "nineteen" and words for multiples of ten like
-- "twenty", "thirty", "fourty", up through "ninety".
-- * Multipliers like "hundred", "thousand", "million", and "billion" and so on, which are applied
-- lower-valued words and summed to express arbitrary numbers.
--
-- Lets 'Data.Map.Map' both ways, lets 'Data.Map.Map' English words to 'Prelude.Integer' values, and
-- the inverse 'Data.Map.Map'ping 'Prelude.Integer's to English words. Then lets convert the
-- 'Data.Map.Map'pings from English words to 'Prelude.Integer's to 'Dao.Rule.Rule's, wrapping the
-- words in 'Dao.Examples.FuzzyStrings.FuzzyString's. Finally, we can program the grammar of the
-- production 'Dao.Rule.Rule's using ordinary monadic do notation, and the combinators provided in
-- "Control.Monad" and "Control.Applicative" and "Dao.Rule", as we would with any computer language
-- parser.
--
-- To run this program in GHCi, navigate to the top level of the "Dao-examples" package and launch
-- GHCi like so:
--
-- > ghci -i./src Dao.Examples.Numbers
--
-- Then run the "main" function in the "Dao.Examples.Numbers" module:
--
-- > main
--
-- This will enter into a Read-Eval-Print loop managed by Readline.
module Dao.Examples.Numbers
( -- * Preliminaries
testRule, NumberRule,
-- * Programming the Spelling of Numbers
singleDigitsMap, teensMap, doubleDigitsMap, zillionsMap,
-- * Converting 'Data.Map.Map's to Dao Production 'Dao.Rule.Rule's.
ruleFromMap, numberDigits,
-- * The Fundamental Combinators
singleDigits, teens, doubleDigits, zillions,
-- * Programming English Language Semantics
subHundred, _hundred, _and, hundreds, numberSentence,
-- * The Final Product
number, digitsToWords, testInteger, testRandom
)
where
import Dao
import qualified Dao.Tree as T
import Dao.Examples.FuzzyStrings
import Data.Either
import Data.Functor.Identity
import Data.Maybe
import Data.Monoid
import qualified Data.Map as M
import qualified Data.Text as Strict
import Control.Arrow
import Control.Applicative
import Control.Monad
--import System.Console.Readline
import System.Random
-- | The 'testRule' function can be used to run any of the 'NumberRule' functions defined in this
-- module. You can use it in @GHCi@ to test any one of the example parsers defined here to get a
-- feel of how it works.
testRule :: Rule Identity o -> String -> [Either ErrorObject o]
testRule rule = tokenize >=> runIdentity . queryAll rule () . fmap obj
----------------------------------------------------------------------------------------------------
-- | 'NumberRule' will be the type we use for all of our Dao production 'Dao.Rule.Rule's.
--
-- It is a good idea to define 'Dao.Rule.Rule's to be polymorphic over the monadic type.
-- Unfortunately, this means always writing three classes into the context of the function:
-- 'Data.Functor.Functor', 'Control.Applicative.Applicative', and 'Control.Monad.Monad'. If you want
-- to use 'Control.Monad.IO.Class.liftIO' in your 'Dao.Rule.Rule's, you also need to provide
-- 'Control.Monad.IO.Class.MonadIO' in the context.
--
-- We can reduce the amount of typing we need to do by enabling the GHC language extension
-- @RankNTypes@, and creating a data type like 'kNumberRule' where the context is specified.
type NumberRule m i = forall m . (Functor m, Applicative m, Monad m) => Rule m i
-- | The 'singleDigitsMap' is a 'Data.Map.Map'ing from an 'Prelude.Integer' to the correct (and some
-- incorrect) spellings of the English language word for that 'Prelude.Integer'.
--
-- @
-- singleDigitsMap = 'Data.Map.fromList' $
-- [ (0, "zero no"),
-- (1, "one a on won wun"),
-- (2, "two to too tu tuu"),
-- (3, "three free"),
-- (4, "four"),
-- (5, "five"),
-- (6, "six si ix"),
-- (7, "seven"),
-- (8, "eight ate"),
-- (9, "nine")
-- ]
-- @
singleDigitsMap :: M.Map Integer String
singleDigitsMap = M.fromList
[ (0, "zero no"),
(1, "one a on won wun"),
(2, "two to too tu tuu"),
(3, "three free"),
(4, "four"),
(5, "five"),
(6, "six si ix"),
(7, "seven"),
(8, "eight ate"),
(9, "nine")
]
-- | The 'teensMap' is for numbers between 10 and 19. In English, numbers betwen 10 and 19 have
-- their own special words, so we specify those words here.
--
-- @
-- teensMap = 'Data.Map.fromList' $
-- [ (10, "ten tn te"),
-- (11, "eleven"),
-- (12, "twelve"),
-- (13, "thirteen"),
-- (14, "fourteen"),
-- (15, "fifteen"),
-- (16, "sixteen"),
-- (17, "seventeen"),
-- (18, "eighteen"),
-- (19, "nineteen")
-- ]
-- @
teensMap :: M.Map Integer String
teensMap = M.fromList
[ (10, "ten tn te"),
(11, "eleven"),
(12, "twelve"),
(13, "thirteen"),
(14, "fourteen"),
(15, "fifteen"),
(16, "sixteen"),
(17, "seventeen"),
(18, "eighteen"),
(19, "nineteen")
]
-- | The 'doubleDigitsMap' provides a 'Data.Map.Map'ping for multiples of ten between 10 an 100,
-- which in the English language, all have their own special words, so we specify those words here.
--
-- @
-- doubleDigitsMap = M.fromList $
-- [ (20, "twenty"),
-- (30, "thirty"),
-- (40, "fourty"),
-- (50, "fifty"),
-- (60, "sixty"),
-- (70, "seventy"),
-- (80, "eighty"),
-- (90, "ninety")
-- ]
-- @
doubleDigitsMap :: M.Map Integer String
doubleDigitsMap = M.fromList
[ (20, "twenty"),
(30, "thirty"),
(40, "fourty"),
(50, "fifty"),
(60, "sixty"),
(70, "seventy"),
(80, "eighty"),
(90, "ninety")
]
-- | 'zillionsMap' is a 'Data.Map.Map'ping from 'Prelude.Integer' values to strings for the numbers
-- for exponents of a "thousand", i.e. every number ending in "...illion", for as many numbers that
-- I know of. To make it easier to write, I use 'Data.Functor.fmap' to append the string "illion" to
-- all of the words except for the word "thousand".
--
-- @
-- zillionsMap = M.fromList $ 'Prelude.zip' ('Prelude.iterate' (1000 *) 1000) $
-- ("thousand" :) $ 'Data.Functor.fmap' (++ "illion") $
-- [ "m", "b", "tr", "quadr", "quint", "sext", "sept", "oct", "non", "dec", "undec", "dodec",
-- "tredec", "quattuordec", "quinquadec", "sexdec", "septdec", "octdec", "novendec", "vigint"
-- ]
-- @
zillionsMap :: M.Map Integer String
zillionsMap = M.fromList $ zip (iterate (1000 *) 1000) $
("thousand" :) $ (++ "illion") <$>
[ "m", "b", "tr" , "quadr", "quint", "sext" , "sept", "oct", "non" , "dec", "undec", "dodec"
, "tredec", "quattuordec", "quinquadec" , "sexdec", "septdec", "octdec" , "novendec", "vigint"
]
-- | 'ruleFromMap' will convert the above 'Data.Map.Map's to Dao a production 'Dao.Rule.Rule'. First
-- we need to convert the 'Data.Map.Map's to a list of associations (pairs) using 'Dao.Map.assocs'.
--
-- The format of the 'Prelude.String' elements of the 'Data.Map.Map's above are simple, each is a
-- string of space-separated words providing alternative spellings for the 'Prelude.Integer' key it
-- is associated with.
--
-- Our 'Dao.Examples.FuzzyStrings.FuzzyString's are good at matching misspelled words, but some
-- alternative spellings of words, which sound similar but are spelled differently, may be
-- considered too different for the 'Dao.Examples.FuzzyStrings.FuzzyString' to match, for example
-- writing "tu" instead of "two". It would be convenient if our intelligent program could
-- understand that when a user writes "tu" they mean to say "two", but these two spellings are too
-- different for 'Dao.Examples.FuzzyStrings.FuzzyString's to be of use. So lets explicitly declare
-- that both spellings map to the same 'Prelude.Integer' value of @2@.
--
-- Then we can use 'Prelude.words' to break up each word into a list of alternative spellings. Then
-- we use 'Data.Functor.fmap' to convert each association to a 'Dao.Rule.Rule' monadic function that
-- returns an 'Prelude.Integer' value. Every alternative spelling is assigned to the same
-- 'Prelude.Integer' value.
--
-- Finally, we use 'Control.Monad.msum' to combine every generated 'Dao.Rule.Rule' into a single
-- 'Dao.Rule.Rule' that can behave as any one of the 'Dao.Rule.Rule's generated from each
-- association.
--
-- The most important part of this function is that we use the 'Dao.Rule.tree' function to create
-- our production 'Dao.Rule.Rule's. The 'Dao.Rule.tree' function takes three parameters:
--
-- 1. a 'Dao.Tree.RunTree' control parameter which specifies whether the 'Dao.Tree.Tree' inside of
-- the 'Dao.Rule.Rule' should be matched in 'Dao.Tree.DepthFirst' or 'Dao.Tree.BreadthFirst'
-- order. Since we always want the longest possible match to succeed, we choose
-- 'Dao.Tree.DepthFirst' order, although in this case it doesn't really matter as every branch of
-- our tree has only one word, and so every branch has a depth of 1.
-- 2. a list of tree branches. The branches of the tree are a list of branch segments, where each
-- segment acts as a pattern that can match an item in a input 'Dao.Rule.Query'. Each branch
-- segment may be of any data type that instantiates 'Dao.Object.ObjectData'. In this case we
-- want to convert each word to a 'Dao.Examples.FuzzyStrings.FuzzyString'.
-- 3. an action function to be evaluated when a portion of an input 'Dao.Rule.Query' that has matched
-- the current 'Dao.Tree.Tree' branch. This function must take the portion of the
-- 'Dao.Rule.Query' that matched the pattern provided in parameter (2), and convert this to a
-- useful value, for example the 'Prelude.Integer' value. In our case, we do not care about the
-- words in the input 'Dao.Rule.Query' that have matched, the action is only evaluated if the
-- input 'Dao.Rule.Query' matches the pattern so the fact that the function is evaluated means
-- the end users has input the number word we were expecting. So all we need to do is return the
-- associated 'Prelude.Integer' value. Thus we will use 'Prelude.const' to discard the input
-- parameters and 'Control.Monad.return' the 'Prelude.Integer' key from the 'Data.Map.Map'.
--
-- @
-- ruleFromMap = 'Control.Monad.msum' . 'Data.Functor.fmap' convertAssocToRule . 'Data.Map.assocs' where
-- convertAssocToRule (i, str) =
-- 'Dao.Rule.tree' 'Dao.Tree.DepthFirst'
-- ((\\str -> ['Dao.Examples.FuzzyStrings.fuzzyString' str]) 'Control.Applicative.<$>' 'Prelude.words' str)
-- ('Prelude.const' $ return i)
-- @
--
-- Notice in the code
--
-- @
-- ('Data.Functor.fmap (\\str -> ['Dao.Examples.FuzzyStrings.fuzzyString' str]) $ 'Prelude.words' str)
-- @
--
-- Each branch is an alternative spelling for a word, and contains just one
-- 'Dao.Examples.FuzzyStrings.FuzzyString' pattern. If we wanted to create branches with multiple
-- words, we could do something like this:
--
-- @
-- ('Data.Functor.fmap (\\str -> ['Data.Functor.fmap' 'Dao.Examples.FuzzyStrings.fuzzyString' $ 'Prelude.words' str]))
-- @
ruleFromMap :: M.Map Integer String -> NumberRule m Integer
ruleFromMap = msum . fmap convertAssocToRule . M.assocs where
convertAssocToRule (i, str) =
tree T.DepthFirst
((\str -> [fuzzyString str]) <$> words str)
(const $ return i)
-- | The 'numberDigits' 'Dao.Rule.Rule' will parse an ordinary number expressed as a string of
-- digits.
--
-- With the 'ruleFromMap' function we defined a way to create Dao production 'Dao.Rule.Rule's out of
-- strings. But our program will be parsing input typed by a human, so lets also consider the case
-- where a user has entered a numerical value expressed as a string of base-10 digits "0123456789".
--
-- Where the 'Dao.Rule.tree' function created rules from 'Dao.Examples.FuzzyStrings.FuzzyString'
-- 'Dao.Object.Object's, we can also create 'Dao.Rule.Rule's that match an 'Dao.Object.Object' of a
-- specific Haskell data type. This can be done with the 'Dao.Rule.infer' combinator for any Haskell
-- data type instantiating 'Data.Typeable.Typeable'. As a reminder, you can instantiate your own
-- custom data types into the 'Data.Typeable.Typeable' class by using the GHC language extension
-- @DeriveDataTypeable@ and including a @deriving 'Data.Typeable.Typeable'@ clause after the
-- definition of your Haskell @data@ type in your source code.
--
-- The 'Dao.Rule.infer' function will infer the data type on which you intend to pattern match by
-- using 'Data.Typeable.typeOf' on the 'Dao.Rule.Rule' function that you pass to it as an argument.
-- For example, if you pass a 'Dao.Rule.Rule' function of type:
--
-- @
-- (('Data.Functor.Functor' m, 'Control.Applicative.Applicative' m, 'Control.Monad.Monad' m) => 'Data.Text.Text' -> 'Dao.Rule.Rule' m ()
-- @
--
-- The 'Dao.Rule.infer' function will create an 'Dao.Object.Object' pattern that matches any
-- 'Data.Text.Text' 'Dao.Object.Object' in the input 'Dao.Rule.Query'. The 'Data.Typeable.TypeRep'
-- value is actually wrapped in a 'Dao.Object.Object' and stored into the 'Dao.Tree.Tree' of
-- patterns inside of the Dao production 'Dao.Rule.Rule'.
--
-- So lets create a Dao production 'Dao.Rule.Rule' that matches an 'Data.Text.Text'
-- 'Dao.Object.Object' in the input 'Dao.Rule.Query', then tries to parse this 'Data.Text.Text' as a
-- 'Prelude.Integer' value using the Haskell function 'Text.Read.reads'. If the parse is
-- successful, the 'Dao.Rule.Rule' should succeed and return the 'Prelude.Integer' value. If the
-- parse fails, the 'Dao.Rule.Rule' should fail with 'Control.Monad.mzero' or
-- 'Control.Applicative.empty'.
--
-- @
-- numberDigits = 'Dao.Rule.infer' $ \\str -> case 'Data.Text.unpack' str of
-- \'-\':str -> 'Prelude.negate' 'Control.Applicative.<$>' parse str
-- str -> parse str
-- where
-- parse str = case 'Text.Read.reads' 0 str of
-- [(i, "")] -> return i
-- _ -> 'Control.Monad.mzero'
-- @
numberDigits :: NumberRule m Integer
numberDigits = infer $ \str -> case Strict.unpack str of
'-':str -> negate <$> parse str
str -> parse str
where
parse str = case reads str of
[(i, "")] -> return i
_ -> mzero
-- | This 'Dao.Rule.Rule' is simply defined as: @'ruleFromMap' 'singleDigitsMap'@
singleDigits :: NumberRule m Integer
singleDigits = ruleFromMap singleDigitsMap
-- | This 'Dao.Rule.Rule' is simply defined as: @'ruleFromMap' 'teensMap'@
teens :: NumberRule m Integer
teens = ruleFromMap teensMap
-- | This 'Dao.Rule.Rule' is simply defined as: @'ruleFromMap' 'doubleDigitsMap'@
doubleDigits :: NumberRule m Integer
doubleDigits = ruleFromMap doubleDigitsMap
-- | This 'Dao.Rule.Rule' is simply defined as: @'ruleFromMap' 'zilionsMap'@
zillions :: NumberRule m Integer
zillions = ruleFromMap zillionsMap
-- | 'subHundred' combines the simpler combinators 'singleDigits', 'teens', and 'doubleDigits', to
-- create a parser that can parse English words for numbers less than one hundred. This will be our
-- first complex combinator. Here is the equation for it:
--
-- @
-- ('Prelude.+') 'Control.Applicative.<$>' 'doubleDigits' 'Control.Applicative.<*>' ('Prelude.maybe' 0 'Prelude.id' 'Control.Applicative.<$>' 'Control.Applicative.optional' 'singleDigits'),
-- @
--
-- Here we make use of the 'Control.Applicative.Applicative' operator @('Control.Applicative.<*>')@
-- to apply a 'doubleDigits' 'Prelude.Integer' value and an 'Control.Applicative.optional'
-- 'singleDigits' 'Prelude.Integer' value to the sum function @('Prelude.+')@.
-- 'Control.Applicative.Applicative' functions always evaluate in order from left to right, so our
-- 'Dao.Rule.Rule's will match in sequence. The sum function is pure and needs to be lifted to the
-- 'Dao.Rule.Rule' monad, which we can do with the 'Data.Functor.Functor' operator
-- @('Control.Applicative.<$>')@.
--
-- What this means is, if we see a 'doubleDigits' number like "twenty" or "fifty", and it is
-- optionally followed by a 'singleDigits' number like "four" or "nine", then add these numbers
-- together: "twenty four" evaluates to @20 + 4@, "fifty nine" evaluates to @50 + 9@. We can use the
-- 'Prelude.maybe' function to indicate that if the 'singleDigits' value was not specified, we
-- should just add zero: "eigthy" evaluates to @80 + 0@.
--
-- It is also valid to express 'singleDigits' or 'teens' alone. So lets specify two more
-- 'Control.Applicative.Alternative' expressions. Lets use 'Control.Monad.msum' to list out all the
-- alternative ways an English speaker might express a number less than one hundred. We could also
-- use the 'Control.Applicative.Alternative's operator @('Control.Applicative.<|>')@ to list each
-- alternative, but I prefer list syntax myself.
--
-- @
-- subHundred = 'Control.Monad.msum'
-- [ ('Prelude.+') 'Control.Applicative.<$>' 'doubleDigits' 'Control.Applicative.<*>' ('Data.Maybe.fromMaybe' 0 'Control.Applicative.<$>' 'Control.Applicative.optional' 'singleDigits'),
-- 'teens',
-- 'singleDigits'
-- ]
-- @
--
-- And that is all we need to do to match any expression less than 100. Well that was easy!
subHundred :: NumberRule m Integer
subHundred = msum
[ (+) <$> doubleDigits <*> (fromMaybe 0 <$> optional singleDigits),
teens,
singleDigits
]
-- | '_hundred' is a trivial combinator that only matches the word "hundred".
--
-- @
-- _hundred = 'Dao.Examples.FuzzyStrings.fuzzyText' "hundred" 'Control.Monad.>>' return 100
-- @
_hundred :: NumberRule m Integer
_hundred = fuzzyText "hundred" >> return 100
-- | '_and' is a trivial combinator for the word "and" which can appear in various places in the
-- grammar of an English language number expression. Lets also include multiple possible spellings
-- for it. Lets also make it a completely optional word by including a @return ()@ as the final
-- choice, i.e. if none of the spellings match, we return successfully anyway.
--
-- @
-- _and = 'Control.Monad.msum' $ 'Data.Functor.fmap' 'Dao.Examples.FuzzyStrings.fuzzyText' ('Prelude.words' "and und an nd n") 'Prelude.++' [return ()]
-- @
_and :: NumberRule m ()
_and = msum $ fmap fuzzyText (words "and und an nd n") ++ [return ()]
-- | The 'hundreds' function will match any numerical expression less than 1000.
--
-- The word "hundred" can be used alone or succeeding some 'singleDigits'. As we saw with the
-- 'subHundred' example, we can use 'Control.Applicative.Applicative' operators to construct
-- 'Dao.Rule.Rule's that match sequences, and we can use the 'Control.Applicative.Alternative'
-- operator and 'Control.Monad.msum' to describe alternative ways of expressing numbers. Lets
-- continue building on what we have done before.
--
-- First lets think of an example expression that we could parse. The words "nine hundred and eighty
-- seven":
--
-- * "nine" -- this can be matched by 'singleDigits', which would return the 'Prelude.Integer' @9@.
-- * "hundred and" -- this can be matched by sequencing '_hundred' and '_and'
-- * "eighty seven" -- this can be matched by 'subHundred', which would return the 'Prelude.Integer' @87@.
--
-- The semantics of the words "nine hundred and eighty seven" map to the equation @(9*100 + 87)@,
-- and we can generalize this to a function @(\\a b -> a*100 + b)@ for any 'singleDigits' @a@ and any
-- 'subHundred' value @b@.
--
-- We will also need to match the words "hundred and" in between matching of the 'singleDigits' and
-- 'subHundred's, which can be done with the '_hundred' 'Dao.Rule.Rule'. The 'Dao.Rule.Rule' for
-- '_and' was defined to be optional and returns a value of @()@, and we want it to occur after the
-- '_hundred' function. So lets modify our equation to accept the value returned by '_hundred':
-- @(\\a hundred b -> a*hundred + b)@.
--
-- It is now obvious how to define our 'Dao.Rule.Rule':
--
-- @
-- (\\a hundred b -> a*hundred + b) 'Control.Applicative.<$>' 'singleDigits' 'Control.Applicative.<*>' (_hundred 'Control.Applicative.<*' _and) 'Control.Applicative.<*>' 'subHundred'
-- @
--
-- An educated Haskell programmer will recall that the @('Control.Applicative.<*')@ operator
-- evaluates both functions in order, but returns only the value from the left, so we can parse the
-- word "and" but the expression will only evaluate to the result parsed by '_hundred'.
--
-- Speakers of English also say things like "nineteen hundred", so lets include a rule for this
-- possibility. The equation for this rule is simlpy to multiply the words for 19 and the word for
-- 100. So our equation is: @(19*100)@ which generalizes to @(\\a b -> a*b)@ which in Haskell can be
-- written simply as @(*)@. So our next rule is:
--
-- @
-- (*) 'Control.Applicative.<$>' 'singleDigits' 'Control.Applicative.<*>' '_hundred'
-- @
--
-- Lets also suppose the end user writes their number as a string of digits and also include the
-- 'numberDigits' 'Dao.Rule.Rule', but for the sake of consistency, lets limit this rule to only
-- numbers less than 1000. After all, the name of this function is 'hundreds' and we wouldn't want
-- to confuse the 'numberSentence' 'Dao.Rule.Rule' which uses this 'hundreds' 'Dao.Rule.Rule', and
-- expects 'hundreds' to always return a value less than 1000 -- we don't want to accept input like
-- "48275 hundred and one".
--
-- @
-- 'numberDigits' >>= \\i -> 'Control.Monad.guard' (i\<1000) >> return i
-- @
--
-- Finally, lets combine all of the 'Dao.Rule.Rule's we have written so far so that our 'hundreds'
-- rule can parse any number expression less than 1000. Again I use 'Control.Monad.msum' to combine
-- each 'Control.Applicative.Alternative' because I prefer list notation, but is equivalent to use
-- the 'Control.Applicative.Alternative' operator @('Control.Applicative.<|>')@.
--
-- @
-- hundreds = 'Dao.Rule.bestMatch' 1 $ 'Control.Monad.msum'
-- [ (\\a hundred b -> a*hundred + b) 'Control.Applicative.<$>' 'singleDigits' <*> ('_hundred' 'Control.Applicative.<*' '_and') 'Control.Applicative.<*>' 'subHundred',
-- (*) 'Control.Applicative.<$>' 'subHundred' 'Control.Applicative.<*>' '_hundred',
-- 'subHundred', '_hundred',
-- 'numberDigits' >>= \\i -> 'Control.Monad.guard' (i\<1000) >> return i
-- ]
-- @
--
-- The final thing to note here is the use of the 'Dao.Rule.bestMatch' function. When a
-- 'Dao.Rule.Rule' is matching against a 'Dao.Rule.Query' input, all possible branches are evaluated
-- in parallel (I mean /logically/ in parallel, not in separate threads). So for example, the input
-- 'Dao.Rule.Query' for "two hundred and thirteen" will have the rule 'subHundred' match in parallel
-- with the rule for @(\\a hundred b -> a*hundred + b)@. As evaluation continues, this will create
-- two parallel branches of evaluation, one 'subHundred' matches the word "two", and one where
-- 'singleDigits' matches the word "two". All future evaluation must try both branches, which can be
-- computationally expensive. Rules that create too many possibilities will grow exponentially in
-- complexity.
--
-- To mitigate this problem, the 'Dao.Rule.bestMatch' function is provided in the "Dao.Rule" module.
-- This function forces evaluation of it's given 'Dao.Rule.Rule' function, eliminating laziness, but
-- also eliminating all branches of evaluation except for the one which matched the most
-- 'Dao.Rule.Query' input. Said another way, 'Dao.Rule.bestMatch' forces evaluation to be
-- 'Dao.Tree.DepthFirst' and takes only the longest branch of evaluation, eliminating all other
-- possible branches before proceeding.
--
-- However 'Dao.Rule.bestMatch' does not eliminate thrown errors, or multiple results that all
-- matched equally well.
hundreds :: NumberRule m Integer
hundreds = bestMatch 1 $ msum
[ (\a hundred b -> a*hundred + b) <$> singleDigits <*> (_hundred <* _and) <*> subHundred,
(*) <$> subHundred <*> _hundred,
subHundred, _hundred,
numberDigits >>= \i -> guard (i<1000) >> return i
]
-- | 'numberSentence' will match any number expressed as an english language sentence.
--
-- Numbers are any sequence of a 'hundreds' expression followed by a 'zillions' expression. Of
-- course, convention dictates the speaker should order the sequence from highest to lowest
-- significance, but we do not need to care about the ordering, as long as there is no ambiguity.
--
-- The simplest way to do this function would be to do a simple recursion:
--
-- @
-- numberSentence n = do
-- h <- 'hundreds'
-- 'Control.Monad.msum'
-- [ (\\z n -> h\*z + n) 'Control.Applicative.<$>' 'zillions' 'Control.Applicative.<*>' ('numberSentence' 'Control.Applicative.<|>' return n),
-- return (h+n)
-- ]
-- @
--
-- But we would probably like to inform the user of ambiguity if they should accidentally say the
-- word "million" twice, they may after all have meant to say "billion" and we would like to be
-- sure. So we create a 'Data.Map.Map' that keeps track of which 'zillions' numbers have already
-- been said and use 'Control.Monad.Errorl.throwError' to inform the end users of the ambiguity.
-- Actually we can use 'Dao.Object.throwObject' to throw an 'Dao.Object.Object', so we can make use
-- of Dao's dynamic typing and not have to worry about the statically typed
-- 'Control.Monad.Error.Class.MonadError' type.
--
-- Lets also allow end-users to optionally precede their number with the word "negative" or "minus".
--
-- @
-- numberSentence = neg 'Control.Applicative.<*>' 'Dao.Logic.chooseOnly' 1 ('Dao.Rule.bestMatch' 1 $ loop 'Data.Monoid.mempty' 0) where
-- neg = 'Control.Monad.msum' $ 'Data.Functor.fmap' (`'Dao.Examples.FuzzyStrings.fuzzyRule'` ('Prelude.const' $ return 'Prelude.negate')) (words "minus negative neg") 'Prelude.++'
-- [return 'Prelude.id']
-- loop saidAlready n = do
-- h <- 'hundreds'
-- 'Control.Monad.msum' $
-- [( do z <- 'zillions' <* 'Control.Applicative.optional' _and
-- case 'Data.Map.lookup' z saidAlready of
-- 'Prelude.Nothing' -> let i = n\*h+z in loop ('Data.Map.insert' z () saidAlready) i 'Control.Applicative.<|>' return i
-- 'Prelude.Just' () -> 'Dao.Object.throwObject' $ 'Prelude.concat' $
-- [ "You said ", maybe "something-zillion" 'Prelude.show' $ 'Data.Map.lookup' z 'zillionsMap',
-- " more than once."
-- ]
-- ),
-- return (h+n)
-- ]
-- @
--
-- The final thing to note here is the use of 'Dao.Logic.chooseOnly'. Since 'Dao.Rule.bestMatch'
-- does not eliminate thrown errors or multiple matches that matched equally well, we want to
-- further narrow down our results to only one thrown error or only the best match. The
-- 'Dao.Logic.chooseOnly' function can do this. It is a 'Dao.Logic.MonadLogic' function, so it will
-- work not only on 'Dao.Rule.Rule's, but any monadic type instantiating 'Dao.Logic.MonadLogic'.
numberSentence :: NumberRule m Integer
numberSentence = neg <*> bestMatch 1 (loop mempty 0) where
neg = msum $ fmap (`fuzzyRule` (const $ return negate)) (words "minus negative neg") ++
[return id]
loop saidAlready n = do
h <- hundreds
msum
[do z <- zillions <* optional _and
case M.lookup z saidAlready of
Nothing -> let i = h*z+n in loop (M.insert z () saidAlready) i <|> return i
Just () -> throwObject $ concat
[ "You said ", maybe "something-zillion" show $ M.lookup z zillionsMap,
" more than once."
],
return (h+n)
]
----------------------------------------------------------------------------------------------------
-- | This function converts a 'Prelude.Integer' to a sequence of 'Data.Text.Text' words describing
-- the 'Prelude.Integer' as an English language sentence.
--
-- This is not an interesting or difficult problem at all and does not require the use of the "Dao"
-- library to implement it. But it is included here for good measure, after all what intelligent
-- program would not have this feature? Although it is limited to numbers less thant @10^66 - 1@
-- because the 'zillionsMap' only has enough words to describe numbers up to that point.
digitsToWords :: Integer -> [Strict.Text]
digitsToWords i = toText <$> if i==0 then ["zero"] else isNeg $ convert 1 $ breakup $ abs i where
isNeg = if i<0 then ("negative" :) else id
breakup i = if i==0 then [] else uncurry (\a b -> b : breakup a) $ divMod i 1000
convert z ix = case ix of
[] -> []
0:ix -> convert (1000 * (z::Integer)) ix
i:ix -> do
let (hundreds, dd) = divMod i 100
let (tens, ones) = divMod dd 10
let lookup i m = if i==0 then Just [] else take 1 . words <$> M.lookup i m
mplus (convert (1000*z) ix) $ fromMaybe ["MY BRAIN HURTS!!!"] $ do
hundreds <- lookup hundreds singleDigitsMap
hundreds <- Just $ if null hundreds then [] else hundreds ++
if dd==0 then ["hundred"] else words "hundred and"
tens <- msum
[ if dd==0 then Just [] else Nothing
, lookup dd teensMap
, (++) <$> lookup (10*tens) doubleDigitsMap <*> lookup ones singleDigitsMap
]
illion <- if z==1 then Just [] else lookup z zillionsMap
Just $ hundreds ++ tens ++ illion
----------------------------------------------------------------------------------------------------
-- | This is the one 'Dao.Rule.Rule' to rule them all: the 'number' rule. This 'Dao.Rule.Rule'
-- combines the 'numberSentence' 'Dao.Rule.Rule' and the 'numberDigits' rule, so an end user can
-- enter a string of digits or a sentence of words expressing a number, and this 'Dao.Rule.Rule'
-- will match the input 'Dao.Rule.Query' and do the right thing.
--
-- @
-- number = 'Dao.Rule.bestMatch' 1 $
-- ('Dao.Object.obj' . 'Data.Text.unwords' . 'digitsToWords' 'Control.Applicative.<$>' 'numberDigits') 'Control.Applicative.<|>' ('Dao.Object.obj' 'Control.Applicative.<$>' 'numberSentence')
-- @
number :: NumberRule m Object
number = bestMatch 1 $
(obj . Strict.unwords . digitsToWords <$> numberDigits) <|> (obj <$> numberSentence)
-- | This function will enter into a Read-Eval-Print Loop (REPL) controlled by "readline". You can
-- enter any number and it will be 'Dao.Examples.FuzzyStrings.tokenize'd, each token will be
-- converted to a list of 'Dao.Object.Object's, and this list of 'Dao.Object.Object's (also known as
-- a 'Dao.Rule.Query') will be fed into the 'number' production 'Dao.Rule.Rule'. Exit REPL with
-- Control-D, or whatever you have configured for your exit key in the "readline" configuration.
--
-- For your convenience, here is the full source of this module, cut-and-pasted right into this
-- documentation. Specifying all production 'Dao.Rule.Rule's only requres only 112 lines of code.
--
-- @
-- module "Dao.Examples.Numbers" where
--
-- import "Dao.Examples.FuzzyStrings"
--
-- import "Dao"
-- import qualified "Dao.Tree" as T
--
-- import "Data.Either"
-- import "Data.Functor.Identity"
-- import "Data.Monoid"
-- import qualified "Data.Map" as M
-- import qualified "Data.Text" as Strict
--
-- import "Control.Arrow"
-- import "Control.Applicative"
-- import "Control.Monad"
-- import "Control.Monad.Except"
--
-- import "System.Console.Readline"
--
-- 'testRule' :: 'Dao.Rule.Rule' 'Control.Monad.Identity.Identity' o -> 'Prelude.String' -> ['Prelude.Either' 'Dao.Object.ErrorObject' o]
-- 'testRule' rule = 'Dao.Examples.FuzzyString.tokenize' 'Control.Monad.>=>' 'Control.Monad.Identity.runIdentity' . 'Dao.Rule.queryAll' rule . 'Data.Functor.fmap' 'Dao.Object.obj'
--
-- type 'NumberRule' m i = forall m . ('Data.Functor.Functor' m, 'Control.Applicative.Applicative' m, 'Control.Monad.Monad' m) => 'Dao.Rule.Rule' m i
--
-- 'singleDigitsMap' :: M.'Data.Map.Map' 'Prelude.Integer' 'Prelude.String'
-- 'singleDigitsMap' = M.'Data.Map.fromList' $
-- [ (0, "zero no"),
-- (1, "one a on won wun"),
-- (2, "two to too tu tuu"),
-- (3, "three free"),
-- (4, "four"),
-- (5, "five"),
-- (6, "six si ix"),
-- (7, "seven"),
-- (8, "eight ate"),
-- (9, "nine")
-- ]
--
-- 'teensMap' :: M.'Data.Map.Map' 'Prelude.Integer' 'Prelude.String'
-- 'teensMap' = M.'Data.Map.fromList' $
-- [ (10, "ten tn te"),
-- (11, "eleven"),
-- (12, "twelve"),
-- (13, "thirteen"),
-- (14, "fourteen"),
-- (15, "fifteen"),
-- (16, "sixteen"),
-- (17, "seventeen"),
-- (18, "eighteen"),
-- (19, "nineteen")
-- ]
--
-- 'doubleDigitsMap' :: M.'Data.Map.Map' 'Prelude.Integer' 'Prelude.String'
-- 'doubleDigitsMap' = M.'Data.Map.fromList' $
-- [ (20, "twenty"),
-- (30, "thirty"),
-- (40, "fourty"),
-- (50, "fifty"),
-- (60, "sixty"),
-- (70, "seventy"),
-- (80, "eighty"),
-- (90, "ninety")
-- ]
--
-- 'zillionsMap' :: M.'Data.Map.Map' 'Prelude.Integer' 'Prelude.String'
-- 'zillionsMap' = M.'Data.Map.fromList' $ 'Prelude.zip' ('Prelude.iterate' (1000 *) 1000) $
-- ("thousand" :) $ 'Data.Functor.fmap' ('Prelude.++' "illion") $
-- [ "m", "b", "tr" , "quadr", "quint", "sext" , "sept", "oct", "non" , "dec", "undec", "dodec"
-- , "tredec", "quattuordec", "quinquadec" , "sexdec", "septdec", "octdec" , "novendec", "vigint"
-- ]
--
-- 'ruleFromMap' :: M.'Data.Map.Map' 'Prelude.Integer' 'Prelude.String' -> NumberRule m 'Prelude.Integer'
-- 'ruleFromMap' = 'Control.Monad.msum' . 'Data.Functor.fmap' convertAssocToRule . M.'Data.Map.assocs' where
-- convertAssocToRule (i, str) =
-- 'Dao.Rule.tree' T.'Dao.Tree.DepthFirst'
-- ((\\str -> ['Dao.Examples.FuzzyStrings.fuzzyString' str]) 'Control.Applicative.<$>' 'Prelude.words' str)
-- ('Prelude.const' $ 'Control.Monad.return' i)
--
-- 'numberDigits' :: 'NumberRule' m 'Prelude.Integer'
-- 'numberDigits' = 'Dao.Rule.infer' $ \\str -> case 'Data.Text.unpack' str of
-- \'-\':str -> 'Prelude.negate' 'Control.Applicative.<$>' parse str
-- str -> parse str
-- where
-- parse str = case 'Text.Read.reads' 0 str of
-- [(i, "")] -> return i
-- _ -> 'Control.Monad.mzero'
--
-- 'singleDigits' :: 'NumberRule' m 'Prelude.Integer'
-- 'singleDigits' = 'Prelude.ruleFromMap' 'Prelude.singleDigitsMap'
--
-- 'teens' :: 'Prelude.NumberRule' m 'Prelude.Integer'
-- 'teens' = 'Prelude.ruleFromMap' 'teensMap'
--
-- 'doubleDigits' :: 'NumberRule' m 'Prelude.Integer'
-- 'doubleDigits' = 'ruleFromMap' 'Prelude.doubleDigitsMap'
--
-- 'zillions' :: 'NumberRule' m 'Prelude.Integer'
-- 'zillions' = 'ruleFromMap' 'zillionsMap'
--
-- 'subHundred' :: 'NumberRule' m 'Prelude.Integer'
-- 'subHundred' = 'Control.Monad.msum'
-- [ (+) 'Control.Applicative.<$>' 'doubleDigits' 'Control.Applicative.<*>' ('Data.Maybe.fromMaybe' 0 'Control.Applicative.<$>' 'Control.Applicative.optional' 'singleDigits'),
-- 'teens', 'singleDigits'
-- ]
--
-- '_hundred' :: 'NumberRule' m 'Prelude.Integer'
-- '_hundred' = 'fuzzyText' "hundred" 'Control.Monad.>>' 'Control.Monad.return' 100
--
-- '_and' :: 'NumberRule' m ()
-- '_and' = 'Control.Monad.msum' $ 'Data.Functor.fmap' 'Dao.Examples.FuzzyStrings.fuzzyText' ('Prelude.words' "and und an nd n") 'Prelude.++' ['Control.Monad.return' ()]
--
-- 'hundreds' :: 'NumberRule' m 'Prelude.Integer'
-- 'hundreds' = 'Dao.Rule.bestMatch' 1 $ 'Control.Monad.msum'
-- [ (\\a hundred b -> a*hundred + b) 'Control.Applicative.<$>' 'singleDigits' 'Control.Applicative.<*>' ('_hundred' 'Control.Applicative.<*' '_and') <*> 'subHundred',
-- (*) 'Control.Applicative.<$>' 'subHundred' 'Control.Applicative.<*>' '_hundred',
-- 'subHundred', '_hundred',
-- 'numberDigits' 'Control.Monad.>>=' \\i -> 'Control.Monad.guard' (i\<1000) 'Control.Monad.>>' 'Control.Monad.return' i
-- ]
--
-- 'numberSentence' :: 'NumberRule' m 'Prelude.Integer'
-- 'numberSentence' = neg 'Control.Applicative.<*>' 'Dao.Logic.chooseOnly' 1 ('Dao.Rule.bestMatch' 1 $ loop 'Data.Monoid.mempty' 0) where
-- neg = 'Control.Monad.msum' $ 'Data.Functor.fmap' (`'Dao.Examples.FuzzyStrings.fuzzyRule'` ('Prelude.const' $ return 'Prelude.negate')) (words "minus negative neg") 'Prelude.++'
-- [return 'Prelude.id']
-- loop saidAlready n = do
-- h <- 'hundreds'
-- 'Control.Monad.msum'
-- [do z <- 'zillions' 'Control.Applicative.<*' 'Control.Applicative.optional' '_and'
-- case M.'Data.Map.lookup' z saidAlready of
-- 'Prelude.Nothing' -> loop (M.'Data.Map.insert' z () saidAlready) (h\*z + n)
-- 'Prelude.Just' () -> 'Dao.Object.throwObject' $ 'Prelude.concat'
-- [ "You said ", 'Prelude.maybe' "something-zillion" 'Prelude.show' $ M.'Data.Map.lookup' z 'zillionsMap',
-- " more than once."
-- ],
-- 'Control.Monad.return' (h+n)
-- ]
--
-- ----------------------------------------------------------------------------------------------------
--
-- 'digitsToWords' :: 'Prelude.Integer' -> [Strict.'Data.Text.Text']
-- 'digitsToWords' i = toText 'Control.Applicative.<$>' if i==0 then ["zero"] else isNeg $ convert 1 $ breakup $ 'Prelude.abs' i where
-- isNeg = if i\<0 then ("negative" :) else 'Prelude.id'
-- breakup i = if i==0 then [] else 'Prelude.uncurry' (\\a b -> b : breakup a) $ 'Prelude.divMod' i 1000
-- convert z ix = case ix of
-- [] -> []
-- 0:ix -> convert (1000 * (z::'Prelude.Integer')) ix
-- i:ix -> do
-- let (hundreds, dd) = 'Prelude.divMod' i 100
-- let (tens, ones) = 'Prelude.divMod' dd 10
-- let lookup i m = if i==0 then 'Prelude.Just' [] else take 1 . 'Prelude.words' 'Control.Applicative.<$>' M.'Data.Map.lookup' i m
-- 'Control.Monad.mplus' (convert (1000\*z) ix) $ 'Prelude.fromMaybe' ["MY BRAIN HURTS!!!"] $
-- hundreds <- lookup hundreds 'singleDigitsMap'
-- hundreds <- 'Prelude.Just' $ if 'Prelude.null' hundreds then [] else hundreds 'Prelude.++'
-- if dd==0 then ["hundred"] else words "hundred and"
-- tens <- 'Control.Monad.msum'
-- [ if dd==0 then 'Prelude.Just' [] else 'Prelude.Nothing',
-- lookup dd 'teensMap',
-- ('Prelude.++') 'Control.Applicative.<$>' lookup (10*tens) 'doubleDigitsMap' 'Control.Applicative.<*>' lookup ones 'singleDigitsMap'
-- ]
-- illion <- if z==1 then 'Prelude.Just' [] else lookup z 'zillionsMap'
-- 'Prelude.Just' $ hundreds 'Prelude.++' tens 'Prelude.++' illion
--
-- 'number' :: 'NumberRule' m 'Object'
-- 'number' = 'Dao.Rule.bestMatch' 1 $
-- ('Dao.Object.obj' . Strict.'Data.Text.unwords' . 'digitsToWords' <$> 'numberDigits') 'Control.Applicative.<|>' ('Dao.Rule.obj' 'Control.Applicative.<$>' 'numberSentence')
--
-- ----------------------------------------------------------------------------------------------------
--
-- main :: IO ()
-- main = do
-- 'System.Console.Readline.initialize' -- initialize Readline
-- 'System.Console.Readline.setCompletionEntryFunction' $ 'Prelude.Just' tabCompletion -- 'tabCompletion' is defined below.
-- 'Data.Function.fix' $ \loop -> do
-- q <- 'System.Console.Readline.readline' "number> "
-- case q of
-- 'Prelude.Nothing' -> 'Control.Monad.return' ()
-- 'Prelude.Just q -> do
-- 'System.Console.Readline.addHistory' q
-- q <- 'Control.Monad.return' $ 'Prelude.fmap' 'Dao.Object.obj' 'Control.Applicative.<$>' 'Dao.Examples.FuzzyStrings.tokenize' q
-- 'Control.Monad.unless' ('Prelude.null' q) $ do
-- 'Control.Monad.forM_' ('Prelude.zip' q $ 'Prelude.fmap' ('Data.Functor.runIdentity' . 'Dao.Rule.queryAll' 'Dao.Examples.Numbers.number' ()) q)
-- (\ (q, result) -> case 'Data.Either.partitionEithers' result of
-- ([] , i:_) -> 'System.IO.print' i
-- ([] , [] ) -> 'System.IO.putStrLn' $ "Does not appear to be a number: "'Prelude.++''Prelude.show' ('Prelude.head' q)
-- (err:_, [] ) -> 'System.IO.putStrLn' $ "Got an error: "'Prelude.++''Prelude.show' err
-- (err:_, i:_) -> 'System.IO.putStrLn' $ "Got an error: "'Prelude.++''Prelude.show' err'Prelude.++'"\nDid you mean "'Prelude.++''Prelude.show' i'Prelude.++'"?"
-- )
-- loop
--
-- -- | Tab completion for Readline.
-- tabCompletion :: String -> IO [String]
-- tabCompletion input = do
-- let -- First, we need a function to convert an 'Dao.Object.Object' to 'Dao.Text.StrictText'.
-- obj2text = ('Dao.Predicate.pTrueToJust' . ('Dao.Object.fromObj' 'Control.Monad.>=>' 'Dao.Object.fromSimple') :: 'Dao.Object.Object' -> 'Prelude.Maybe' 'Dao.Text.StrictText')
-- --
-- -- Now, tokenize the input string.
-- tokens <- 'Control.Monad.return' $ 'Prelude.fmap' 'Dao.Object.obj' <$> 'Dao.Examples.FuzzyStrings.tokenize' input
-- --
-- -- Lets begin by tokenizing the input string.
-- tokens <- 'Control.Applicative.pure' $ 'Prelude.fmap' 'Dao.Object.obj' <$> 'Dao.Examples.FuzzyStrings.tokenize' input
-- tokens <- 'Control.Applicative.pure' $ if 'Prelude.null' tokens then [] else 'Prelude.head' tokens
-- --
-- -- The 'Dao.Rule.guessPartial' function is designed especially for
-- -- this kind of tab completion work. We will tokenize the string
-- -- input from Readline to create a 'Dao.Rule.Query', and perform a
-- -- 'Dao.Rule.partialQuery' over the 'number' rule.
-- (completions, _) <- 'Dao.Rule.guessPartial' ('Dao.Rule.partialQuery' 99 'Dao.Examples.Numbers.number' ()) ('Dao.Object.obj' <$> tokens)
-- (\lastToken completionList -> case lastToken >>= obj2text of
-- Nothing -> -- if the last token isn't 'Dao.Text.StrictText'
-- 'Control.Monad.return' completionList -- then don't bother filtering anything.
-- Just lastToken -> do
-- let -- Lets use monadic notation to create a filter,
-- -- so we are using the list monad here.
-- 'Dao.Rule.filterCompletions' completion = if null completion then [] else do
-- --
-- -- Get the first element of this completion candidate.
-- headCompletion <- 'Data.Maybe.maybeToList' $ obj2text $ 'Prelude.head' completion
-- --
-- -- If the last token entered by the user is a prefix of this particular
-- -- completion candidate, we 'Control.Monad.return' this completion.
-- 'Control.Monad.guard' $ lastToken `'Data.Text.isPrefixOf'` headCompletion
-- [completion]
-- --
-- -- Now lets apply our filter and 'Control.Monad.return' the result.
-- 'Control.Monad.return' $ completionList 'Control.Monad.>>=' filterCompletions
-- )
-- -- Now lets convert each completion back into a 'Prelude.String',
-- -- and limit the list of completions to 99 items.
-- 'Control.Monad.return' $ 'Prelude.take' 99 $
-- 'Data.Text.unpack' . 'Data.Text.unwords' . ('Prelude.concatMap' $ 'Data.Maybe.maybeToList' . obj2text) <$> completions
-- @
-- | This will take an 'Prelude.Integer', feed it into 'number' to produce a sentence, then feed the
-- sentence back into 'number' to produce the integer. If the result returned is the same as the
-- value of the input, returns 'Prelude.True', otherwise returns 'Prelude.False'. Also prints a
-- message to standard output.
testInteger :: Integer -> IO Bool
testInteger i = putStrLn msg >> return ok where
toStr o = case fromObj o of
PFalse -> [Left [obj $ "Could not convert "++show o++" to integer"]]
PError e -> [Left e]
PTrue o -> testRule number (Strict.unpack o) >>= (return . Left ||| toInt o)
toInt o i = case fromObj i of
PFalse -> [Left [obj $ "Could not convert "++show i++" to string"]]
PError e -> [Left e]
PTrue i -> [Right (i, o)]
(ok, msg) = case testRule number (show i) >>= (return . Left ||| toStr) of
[Right o] | i == fst o -> (True , show i++": PTrue -> "++show o)
(Right o : x) | i == fst o -> let (errs, oks) = length *** length $ partitionEithers x in
( True
, concat
[ show i, ": ", show o, " WARNING "
, show errs, " errors and ", show oks, " other valid results ignored"
]
)
result -> (False, show i++": FAIL -> "++show result)
-- | This will test all numbers from 0 to 1400, and then a thousand random numbers to make sure
-- converting from integers to sentences and back to integers yield the number. Halts after three
-- failures.
testRandom :: IO ()
testRandom = (++) <$> pure [0..1400] <*> replicateM 1000 randomIO >>= loop 3 where
loop counter ix = case ix of
[] -> return ()
i:ix -> testInteger i >>= \pass ->
unless (not pass && (counter::Int) <= 1) $ loop ((if pass then id else subtract 1) counter) ix
|
RaminHAL9001/Dao-examples
|
src/Dao/Examples/Numbers.hs
|
agpl-3.0
| 46,760 | 0 | 22 | 8,824 | 3,251 | 2,066 | 1,185 | -1 | -1 |
module Ape.Transform.CommonSubExpr (commonSubExpr, emptyExprMap) where
import Ape.Expr
import Ape.Env
import qualified Data.Map.Strict as M
import Ape.Transform.NormalizeExpr
import Data.List
type ExprMap = M.Map (CExpr Info) String
emptyExprMap :: ExprMap
emptyExprMap = M.empty
class CommonSubExpr a where
commonSubExpr :: ExprMap -> Env Variable -> a Info -> a Info
-- Make all variables in the environment point their final renamed form
normalizeEnv :: Env Variable -> Env Variable
normalizeEnv e = if next == e
then e
else normalizeEnv next
where next = mapEnv (\v -> if isInEnv e v then lookupEnv e v else v) e
instance CommonSubExpr Value where
commonSubExpr _ e v@(Var i w) = if isInEnv e w then Var i $ lookupEnv e w else v
commonSubExpr m e (Tuple i v) = Tuple i $ map (commonSubExpr m e) v
commonSubExpr m e (Lambda i v t b) = Lambda i v t (commonSubExpr m e b)
commonSubExpr _ _ v = v
instance CommonSubExpr CExpr where
commonSubExpr m e c = case M.lookup c m of
Just v -> Atomic $ Val $ Var (info c) v
_ -> case c of
If i b t f -> If i (commonSubExpr m e b) (commonSubExpr m e t) (commonSubExpr m e f)
App i xs -> App i $ map (commonSubExpr m e) xs
Atomic a -> Atomic (commonSubExpr m e a)
instance CommonSubExpr AExpr where
commonSubExpr m e (Val v) = normalizeExpr $ Val $ commonSubExpr m e v
commonSubExpr m e (PrimOp i op xs) = normalizeExpr $ PrimOp i op $ map (commonSubExpr m e) xs
instance CommonSubExpr Expr where
commonSubExpr m e (Let i v b) = case v' of
[] -> commonSubExpr m' e'' b
_ -> Let i v' $ commonSubExpr m' e'' b
where
handleSingleBinding (expr2var, var2var, bindings) bind@(var, _, expr) = case expr of
-- If the binding is under the form let a = b, we just remap a to b
Atomic (Val (Var _ var')) -> (expr2var, insertEnv var2var var var', bindings)
-- Otherwise, we need to check if the expression already exists somewhere else in the program
_ -> case M.lookup expr expr2var of
Just var' -> (expr2var, insertEnv var2var var var', bindings)
Nothing -> (M.insert expr var expr2var, var2var, bind:bindings)
handleBindings (expr2var, var2var, bindings) = (expr2var', var2var', reverse bindings')
where (expr2var', var2var', bindings') = foldl' handleSingleBinding (expr2var, var2var, []) bindings
transformBindings prev@(expr2var, var2var, bindings) = if prev == result
then result
else transformBindings result
where
bindings' = map (\(w, t, c) -> (w, t, commonSubExpr (M.delete c expr2var) var2var c)) bindings
result = handleBindings (m, var2var, bindings')
-- Iterate until fixpoint is reached
(m', e', v') = transformBindings $ handleBindings (m, e, v)
e'' = normalizeEnv e'
commonSubExpr m e (Complex c) = Complex $ commonSubExpr m e c
|
madmann91/Ape
|
src/Ape/Transform/CommonSubExpr.hs
|
lgpl-3.0
| 3,097 | 0 | 17 | 889 | 1,063 | 552 | 511 | 50 | 3 |
module EnumFromTo where
enumFromTo' :: (Enum a, Eq a) => a -> a -> [a]
enumFromTo' from to = go from to []
where go from to li
| from == to = li ++ [to]
| otherwise = go (succ from) to (li ++ [from])
|
thewoolleyman/haskellbook
|
09/05/maor/enumfromto.hs
|
unlicense
| 226 | 0 | 11 | 72 | 117 | 60 | 57 | 6 | 1 |
{-# OPTIONS -fglasgow-exts #-}
-----------------------------------------------------------------------------
{-| Module : Object.hs
Copyright : (c) David Harley 2010
Project : qtHaskell
Version : 1.1.4
Modified : 2010-09-02 17:02:34
Warning : this file is machine generated - do not modify.
--}
-----------------------------------------------------------------------------
module Qtc.Classes.Object (
Object(..), objectNull, objectIsNull, objectCast, objectFromPtr, objectFromPtr_nf, withObjectPtr, ptrFromObject, objectListFromPtrList, objectListFromPtrList_nf
) where
import Control.Exception
import System.IO.Unsafe( unsafePerformIO )
import Foreign.C
import Foreign.Ptr
import Foreign.ForeignPtr
import Foreign.Storable
import Foreign.Marshal.Alloc
import Foreign.Marshal.Array
data Object a = Object ! (ForeignPtr a)
instance Eq (Object a) where
fobj1 == fobj2
= unsafePerformIO $
withObjectPtr fobj1 $ \p1 ->
withObjectPtr fobj2 $ \p2 ->
return (p1 == p2)
instance Ord (Object a) where
compare fobj1 fobj2
= unsafePerformIO $
withObjectPtr fobj1 $ \p1 ->
withObjectPtr fobj2 $ \p2 ->
return (compare p1 p2)
instance Show (Object a) where
show fobj
= unsafePerformIO $
withObjectPtr fobj $ \p ->
return (show p)
objectNull :: Object a
objectNull
= Object $ unsafePerformIO (newForeignPtr_ nullPtr)
objectIsNull :: Object a -> Bool
objectIsNull fobj
= unsafePerformIO $
withObjectPtr fobj $ \p -> return (p == nullPtr)
objectCast :: Object a -> Object b
objectCast (Object fp) = Object (castForeignPtr fp)
withObjectPtr :: Object a -> (Ptr a -> IO b) -> IO b
withObjectPtr (Object fp) f = withForeignPtr fp f
objectFromPtr :: FunPtr (Ptr a -> IO ()) -> Ptr a -> IO (Object a)
objectFromPtr f p
= do
nfp <- newForeignPtr f p
return $ Object nfp
objectFromPtr_nf :: Ptr a -> IO (Object a)
objectFromPtr_nf p
= do
nfp <- newForeignPtr_ p
return $ Object nfp
ptrFromObject :: Object a -> Ptr a
ptrFromObject (Object fp) = unsafeForeignPtrToPtr fp
objectListFromPtrList :: FunPtr (Ptr a -> IO ()) -> [Ptr a] -> IO [Object a]
objectListFromPtrList f pl = objectListFromPtrList_r f [] pl
objectListFromPtrList_r :: FunPtr (Ptr a -> IO ()) -> [Object a] -> [Ptr a] -> IO [Object a]
objectListFromPtrList_r _ fol [] = return fol
objectListFromPtrList_r f fol (x:xs)
= do
nfp <- newForeignPtr f x
objectListFromPtrList_r f (fol ++ [Object nfp]) xs
objectListFromPtrList_nf :: [Ptr a] -> IO [Object a]
objectListFromPtrList_nf pl = objectListFromPtrList_nf_r [] pl
objectListFromPtrList_nf_r :: [Object a] -> [Ptr a] -> IO [Object a]
objectListFromPtrList_nf_r fol [] = return fol
objectListFromPtrList_nf_r fol (x:xs)
= do
nfp <- newForeignPtr_ x
objectListFromPtrList_nf_r (fol ++ [Object nfp]) xs
|
uduki/hsQt
|
Qtc/Classes/Object.hs
|
bsd-2-clause
| 2,870 | 76 | 11 | 564 | 890 | 466 | 424 | 70 | 1 |
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TupleSections #-}
module Mars.Command.Ls (Ls (..), LsResult (..), ansiColor) where
import Data.Aeson
import qualified Data.HashMap.Strict as Map
import Data.Ix
import Data.Maybe
import Data.String
import Data.String.Conv
import Data.Text (Text)
import qualified Data.Text as Text
import Data.Text.IO (putStrLn)
import Data.Typeable
import qualified Data.Vector as Vector
import GHC.Generics
import Mars.Command
import Mars.Query (Query (..))
import Mars.Renderable
import Mars.Types
import Test.QuickCheck
import Prelude hiding (putStrLn)
newtype Ls = Ls Query
deriving (Generic, Show, Eq, Typeable)
newtype LsResult = DirectoryEntries [DirectoryEntry]
deriving (Generic, Show, Eq, Typeable)
instance Command Ls LsResult where
evalCommand s (Ls DefaultLocation) = DirectoryEntries . list (document s) $ path s
evalCommand s (Ls q) = DirectoryEntries . list (document s) $ path s <> q
instance Action LsResult where
execCommand state (DirectoryEntries o) = do
putStrLn . format $ o
return state
where
format :: [DirectoryEntry] -> Text
format l =
Text.intercalate "\n"
. zipWith
ansiColor
(colorMap <$> l)
$ (\(DirectoryEntry (ItemName name) _) -> name) <$> l
instance Renderable Ls where
render (Ls a) = "ls " <> render a
list :: Value -> Query -> [DirectoryEntry]
list doc query =
concatMap directoryEntries . queryDoc query $ doc
directoryEntries :: Value -> [DirectoryEntry]
directoryEntries (Object o) =
let toDirectoryEntry :: (Text, Value) -> DirectoryEntry
toDirectoryEntry (name, v) =
DirectoryEntry
(ItemName . toS $ name)
(toItemType v)
in toDirectoryEntry
<$> catMaybes
( spreadMaybe
<$> spread (o Map.!?) (Map.keys o)
)
directoryEntries (Array o) =
let toDirectoryEntry :: (Int, Value) -> DirectoryEntry
toDirectoryEntry (name, v) =
DirectoryEntry
(ItemName . toS . show $ name)
(toItemType v)
in toDirectoryEntry
<$> catMaybes
( spreadMaybe
<$> spread (o Vector.!?) ((\x -> range (0, length x)) o)
)
directoryEntries (String _) = []
directoryEntries (Number _) = []
directoryEntries (Bool _) = []
directoryEntries Null = []
colorMap :: DirectoryEntry -> ANSIColour
colorMap (DirectoryEntry _ MarsObject) = Blue
colorMap (DirectoryEntry _ MarsList) = Blue
colorMap (DirectoryEntry _ MarsString) = Green
colorMap (DirectoryEntry _ MarsNumber) = Green
colorMap (DirectoryEntry _ MarsBool) = Green
colorMap (DirectoryEntry _ MarsNull) = Green
ansiColor :: ANSIColour -> Text -> Text
ansiColor Grey = ansiWrap "30"
ansiColor Red = ansiWrap "31"
ansiColor Green = ansiWrap "32"
ansiColor Yellow = ansiWrap "33"
ansiColor Blue = ansiWrap "34"
ansiColor Magenta = ansiWrap "35"
ansiColor Cyan = ansiWrap "36"
ansiColor White = ansiWrap "37"
ansiWrap :: (Monoid m, Data.String.IsString m) => m -> m -> m
ansiWrap colorID text = "\ESC[" <> colorID <> "m" <> text <> "\ESC[0m"
spread :: (a -> b) -> [a] -> [(a, b)]
spread f a = zip a (f <$> a)
extractSpread :: Functor f => (a, f b) -> f (a, b)
extractSpread (i, l) = (i,) <$> l
spreadMaybe :: (a, Maybe b) -> Maybe (a, b)
spreadMaybe = extractSpread
toItemType :: Value -> ItemType
toItemType (Object _) = MarsObject
toItemType (Array _) = MarsList
toItemType (String _) = MarsString
toItemType (Number _) = MarsNumber
toItemType (Bool _) = MarsBool
toItemType Null = MarsNull
instance Arbitrary Ls where
arbitrary = Ls <$> arbitrary
|
lorcanmcdonald/mars
|
src/Mars/Command/Ls.hs
|
bsd-3-clause
| 3,676 | 0 | 18 | 782 | 1,290 | 685 | 605 | 104 | 1 |
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TupleSections #-}
module River.X64.Color (
colorByRegister
, RegisterError(..)
) where
import Control.Monad.Trans.State.Strict (StateT, runStateT, get, put)
import Data.Function (on)
import qualified Data.List as List
import Data.Map (Map)
import qualified Data.Map as Map
import River.Core.Color (ColorStrategy(..))
import River.Core.Syntax
import River.Fresh
import River.Map
import River.X64.Primitive
import River.X64.Syntax (Register64(..))
data RegisterError n =
RegistersExhausted !n
deriving (Eq, Ord, Show)
colorByRegister :: Ord n => ColorStrategy (RegisterError n) Register64 k Prim n a
colorByRegister =
ColorStrategy {
unusedColor =
\n used ->
case Map.toList (registers `mapDifferenceSet` used) of
[] ->
Left $ RegistersExhausted n
regs ->
pure . fst $ List.minimumBy (compare `on` snd) regs
, precolored =
precoloredOfProgram
}
precoloredOfProgram ::
Ord n =>
FreshName n =>
Program k Prim n a ->
Fresh (Map n Register64, Program k Prim n a)
precoloredOfProgram = \case
Program a tm0 -> do
(tm, rs) <- runStateT (precoloredOfTerm tm0) Map.empty
pure (rs, Program a tm)
putsert :: (Ord k, Monad m) => k -> v -> StateT (Map k v) m ()
putsert k v = do
kvs <- get
put $ Map.insert k v kvs
precoloredOfTerm ::
Ord n =>
FreshName n =>
Term k Prim n a ->
StateT (Map n Register64) Fresh (Term k Prim n a)
precoloredOfTerm = \case
-- TODO ensure in RAX
Return at tl ->
pure $
Return at tl
If at k (Variable ai i) t0 e0 -> do
t <- precoloredOfTerm t0
e <- precoloredOfTerm e0
i_ah <- freshen i
i_flags <- freshen i
putsert i_ah RAX
putsert i_flags RFLAGS
pure $
Let at [i_ah] (Copy at [Variable ai i]) $
Let at [i_flags] (Copy at [Variable ai i_ah]) $ -- implicit sahf instruction
If at k (Variable ai i_flags) t e
If at k i t0 e0 ->
If at k i
<$> precoloredOfTerm t0
<*> precoloredOfTerm e0
LetRec at bs tm -> do
LetRec at
<$> precoloredOfBindings bs
<*> precoloredOfTerm tm
Let at [lo, hi] (Prim ap Imul [Variable ax x, y]) tm0 -> do
tm <- precoloredOfTerm tm0
x_rax <- freshen x
lo_rax <- freshen lo
hi_rdx <- freshen hi
putsert x_rax RAX
putsert lo_rax RAX
putsert hi_rdx RDX
pure $
Let ap [x_rax] (Copy ap [Variable ax x]) $
Let at [lo_rax, hi_rdx] (Prim ap Imul [Variable ax x_rax, y]) $
Let at [lo] (Copy at [Variable at lo_rax]) $
Let at [hi] (Copy at [Variable at hi_rdx]) $
tm
Let at [dv, md] (Prim ap Idiv [Variable al lo, Variable ah hi, x]) tm0 -> do
tm <- precoloredOfTerm tm0
lo_rax <- freshen lo
hi_rdx <- freshen hi
dv_rax <- freshen dv
md_rdx <- freshen md
putsert lo_rax RAX
putsert hi_rdx RDX
putsert dv_rax RAX
putsert md_rdx RDX
pure $
Let ap [lo_rax] (Copy ap [Variable al lo]) $
Let ap [hi_rdx] (Copy ap [Variable ah hi]) $
Let at [dv_rax, md_rdx] (Prim ap Idiv [Variable al lo_rax, Variable ah hi_rdx, x]) $
Let at [dv] (Copy at [Variable at dv_rax]) $
Let at [md] (Copy at [Variable at md_rdx]) $
tm
Let at [hi] (Prim ap Cqto [Variable al lo]) tm0 -> do
tm <- precoloredOfTerm tm0
lo_rax <- freshen lo
hi_rdx <- freshen hi
putsert lo_rax RAX
putsert hi_rdx RDX
pure $
Let ap [lo_rax] (Copy ap [Variable al lo]) $
Let at [hi_rdx] (Prim ap Cqto [Variable al lo_rax]) $
Let at [hi] (Copy at [Variable at hi_rdx]) $
tm
Let at [r] (Prim ap Test [x, y]) tm0 -> do
tm <- precoloredOfTerm tm0
r_flags <- freshen r
r_ah <- freshen r
putsert r_flags RFLAGS
putsert r_ah RAX
pure $
Let at [r_flags] (Prim ap Test [x, y]) $
Let at [r_ah] (Copy at [Variable at r_flags]) $ -- implicit lahf instruction
Let at [r] (Copy at [Variable at r_ah]) $
tm
Let at [r] (Prim ap Cmp [x, y]) tm0 -> do
tm <- precoloredOfTerm tm0
r_flags <- freshen r
r_ah <- freshen r
putsert r_flags RFLAGS
putsert r_ah RAX
pure $
Let at [r_flags] (Prim ap Cmp [x, y]) $
Let at [r_ah] (Copy at [Variable at r_flags]) $ -- implicit lahf instruction
Let at [r] (Copy at [Variable at r_ah]) $
tm
Let at [b] (Prim ap (Set cc) [Variable ar r]) tm0 -> do
tm <- precoloredOfTerm tm0
r_ah <- freshen r
r_flags <- freshen r
putsert r_ah RAX
putsert r_flags RFLAGS
pure $
Let at [r_ah] (Copy at [Variable ar r]) $
Let at [r_flags] (Copy at [Variable ar r_ah]) $ -- implicit sahf instruction
Let at [b] (Prim ap (Set cc) [Variable ar r_flags]) $
tm
Let at ns tl tm ->
Let at ns tl
<$> precoloredOfTerm tm
precoloredOfBindings ::
Ord n =>
FreshName n =>
Bindings k Prim n a ->
StateT (Map n Register64) Fresh (Bindings k Prim n a)
precoloredOfBindings = \case
Bindings a nbs0 -> do
let
(ns, bs0) =
unzip nbs0
bs <- traverse precoloredOfBinding bs0
pure $
Bindings a (zip ns bs)
precoloredOfBinding ::
Ord n =>
FreshName n =>
Binding k Prim n a ->
StateT (Map n Register64) Fresh (Binding k Prim n a)
precoloredOfBinding = \case
Lambda a ns tm -> do
Lambda a ns
<$> precoloredOfTerm tm
registers :: Map Register64 Int
registers =
Map.fromList $ flip zip [1..]
--
-- Caller saved registers
--
-- We can overwrite these at will.
--
[ RAX
, RCX
, RDX
, RSI
, RDI
, R8
, R9
, R10
--
-- Spill register
--
-- We will use this to spill and restore from the stack.
--
-- , R11
--
--
-- Stack pointer
--
-- , RSP
--
--
-- Callee saved registers
--
-- If we use these, they must be saved to the stack and restored before
-- returning.
--
, R12
, R13
, R14
, R15
, RBX
-- , RBP
]
|
jystic/river
|
src/River/X64/Color.hs
|
bsd-3-clause
| 6,266 | 0 | 20 | 1,988 | 2,421 | 1,204 | 1,217 | 192 | 11 |
{-|
Module : Idris.Output
Description : Utilities to display Idris' internals and other informtation to the user.
Copyright :
License : BSD3
Maintainer : The Idris Community.
-}
{-# OPTIONS_GHC -fwarn-incomplete-patterns #-}
module Idris.Output where
import Idris.Core.TT
import Idris.Core.Evaluate (isDConName, isTConName, isFnName, normaliseAll)
import Idris.AbsSyntax
import Idris.Colours (hStartColourise, hEndColourise)
import Idris.Delaborate
import Idris.Docstrings
import Idris.IdeMode
import Util.Pretty
import Util.ScreenSize (getScreenWidth)
import Util.System (isATTY)
import Control.Monad.Trans.Except (ExceptT (ExceptT), runExceptT)
import System.Console.Haskeline.MonadException
(MonadException (controlIO), RunIO (RunIO))
import System.IO (stdout, Handle, hPutStrLn, hPutStr)
import System.FilePath (replaceExtension)
import Prelude hiding ((<$>))
import Data.Char (isAlpha)
import Data.List (nub, intersperse)
import Data.Maybe (fromMaybe)
instance MonadException m => MonadException (ExceptT Err m) where
controlIO f = ExceptT $ controlIO $ \(RunIO run) -> let
run' = RunIO (fmap ExceptT . run . runExceptT)
in fmap runExceptT $ f run'
pshow :: IState -> Err -> String
pshow ist err = displayDecorated (consoleDecorate ist) .
renderPretty 1.0 80 .
fmap (fancifyAnnots ist True) $ pprintErr ist err
iWarn :: FC -> Doc OutputAnnotation -> Idris ()
iWarn fc err =
do i <- getIState
case idris_outputmode i of
RawOutput h ->
do err' <- iRender . fmap (fancifyAnnots i True) $
case fc of
FC fn _ _ | fn /= "" -> text (show fc) <> colon <//> err
_ -> err
hWriteDoc h i err'
IdeMode n h ->
do err' <- iRender . fmap (fancifyAnnots i True) $ err
let (str, spans) = displaySpans err'
runIO . hPutStrLn h $
convSExp "warning" (fc_fname fc, fc_start fc, fc_end fc, str, spans) n
iRender :: Doc a -> Idris (SimpleDoc a)
iRender d = do w <- getWidth
ist <- getIState
let ideMode = case idris_outputmode ist of
IdeMode _ _ -> True
_ -> False
tty <- runIO isATTY
case w of
InfinitelyWide -> return $ renderPretty 1.0 1000000000 d
ColsWide n -> return $
if n < 1
then renderPretty 1.0 1000000000 d
else renderPretty 0.8 n d
AutomaticWidth | ideMode || not tty -> return $ renderPretty 1.0 80 d
| otherwise -> do width <- runIO getScreenWidth
return $ renderPretty 0.8 width d
hWriteDoc :: Handle -> IState -> SimpleDoc OutputAnnotation -> Idris ()
hWriteDoc h ist rendered =
do runIO $ displayDecoratedA
(hPutStr h)
(maybe (return ()) (hStartColourise h))
(maybe (return ()) (hEndColourise h))
(fmap (annotationColour ist) rendered)
runIO $ hPutStr h "\n" -- newline translation on the output
-- stream should take care of this for
-- Windows
-- | Write a pretty-printed term to the console with semantic coloring
consoleDisplayAnnotated :: Handle -> Doc OutputAnnotation -> Idris ()
consoleDisplayAnnotated h output =
do ist <- getIState
rendered <- iRender output
hWriteDoc h ist rendered
iPrintTermWithType :: Doc OutputAnnotation -> Doc OutputAnnotation -> Idris ()
iPrintTermWithType tm ty = iRenderResult (tm <+> colon <+> align ty)
-- | Pretty-print a collection of overloadings to REPL or IDEMode - corresponds to :t name
iPrintFunTypes :: [(Name, Bool)] -> Name -> [(Name, Doc OutputAnnotation)] -> Idris ()
iPrintFunTypes bnd n [] = iPrintError $ "No such variable " ++ show n
iPrintFunTypes bnd n overloads = do ist <- getIState
let ppo = ppOptionIst ist
let infixes = idris_infixes ist
let output = vsep (map (uncurry (ppOverload ppo infixes)) overloads)
iRenderResult output
where fullName ppo n | length overloads > 1 = prettyName True True bnd n
| otherwise = prettyName True (ppopt_impl ppo) bnd n
ppOverload ppo infixes n tm =
fullName ppo n <+> colon <+> align tm
iRenderOutput :: Doc OutputAnnotation -> Idris ()
iRenderOutput doc =
do i <- getIState
case idris_outputmode i of
RawOutput h -> do out <- iRender doc
hWriteDoc h i out
IdeMode n h ->
do (str, spans) <- fmap displaySpans . iRender . fmap (fancifyAnnots i True) $ doc
let out = [toSExp str, toSExp spans]
runIO . hPutStrLn h $ convSExp "write-decorated" out n
iRenderResult :: Doc OutputAnnotation -> Idris ()
iRenderResult d = do ist <- getIState
case idris_outputmode ist of
RawOutput h -> consoleDisplayAnnotated h d
IdeMode n h -> ideModeReturnAnnotated n h d
ideModeReturnWithStatus :: String -> Integer -> Handle -> Doc OutputAnnotation -> Idris ()
ideModeReturnWithStatus status n h out = do
ist <- getIState
(str, spans) <- fmap displaySpans .
iRender .
fmap (fancifyAnnots ist True) $
out
let good = [SymbolAtom status, toSExp str, toSExp spans]
runIO . hPutStrLn h $ convSExp "return" good n
-- | Write pretty-printed output to IDEMode with semantic annotations
ideModeReturnAnnotated :: Integer -> Handle -> Doc OutputAnnotation -> Idris ()
ideModeReturnAnnotated = ideModeReturnWithStatus "ok"
-- | Show an error with semantic highlighting
iRenderError :: Doc OutputAnnotation -> Idris ()
iRenderError e = do ist <- getIState
case idris_outputmode ist of
RawOutput h -> consoleDisplayAnnotated h e
IdeMode n h -> ideModeReturnWithStatus "error" n h e
iPrintWithStatus :: String -> String -> Idris ()
iPrintWithStatus status s = do
i <- getIState
case idris_outputmode i of
RawOutput h -> case s of
"" -> return ()
s -> runIO $ hPutStrLn h s
IdeMode n h ->
let good = SexpList [SymbolAtom status, toSExp s] in
runIO $ hPutStrLn h $ convSExp "return" good n
iPrintResult :: String -> Idris ()
iPrintResult = iPrintWithStatus "ok"
iPrintError :: String -> Idris ()
iPrintError = iPrintWithStatus "error"
iputStrLn :: String -> Idris ()
iputStrLn s = do i <- getIState
case idris_outputmode i of
RawOutput h -> runIO $ hPutStrLn h s
IdeMode n h -> runIO . hPutStrLn h $ convSExp "write-string" s n
idemodePutSExp :: SExpable a => String -> a -> Idris ()
idemodePutSExp cmd info = do i <- getIState
case idris_outputmode i of
IdeMode n h ->
runIO . hPutStrLn h $
convSExp cmd info n
_ -> return ()
-- TODO: send structured output similar to the metavariable list
iputGoal :: SimpleDoc OutputAnnotation -> Idris ()
iputGoal g = do i <- getIState
case idris_outputmode i of
RawOutput h -> hWriteDoc h i g
IdeMode n h ->
let (str, spans) = displaySpans . fmap (fancifyAnnots i True) $ g
goal = [toSExp str, toSExp spans]
in runIO . hPutStrLn h $ convSExp "write-goal" goal n
-- | Warn about totality problems without failing to compile
warnTotality :: Idris ()
warnTotality = do ist <- getIState
mapM_ (warn ist) (nub (idris_totcheckfail ist))
where warn ist (fc, e) = iWarn fc (pprintErr ist (Msg e))
printUndefinedNames :: [Name] -> Doc OutputAnnotation
printUndefinedNames ns = text "Undefined " <> names <> text "."
where names = encloseSep empty empty (char ',') $ map ppName ns
ppName = prettyName True True []
prettyDocumentedIst :: IState
-> (Name, PTerm, Maybe (Docstring DocTerm))
-> Doc OutputAnnotation
prettyDocumentedIst ist (name, ty, docs) =
prettyName True True [] name <+> colon <+> align (prettyIst ist ty) <$>
fromMaybe empty (fmap (\d -> renderDocstring (renderDocTerm ppTm norm) d <> line) docs)
where ppTm = pprintDelab ist
norm = normaliseAll (tt_ctxt ist) []
sendParserHighlighting :: Idris ()
sendParserHighlighting =
do ist <- getIState
let hs = map unwrap . nub . map wrap $ idris_parserHighlights ist
sendHighlighting hs
ist <- getIState
putIState ist {idris_parserHighlights = []}
where wrap (fc, a) = (FC' fc, a)
unwrap (fc', a) = (unwrapFC fc', a)
sendHighlighting :: [(FC, OutputAnnotation)] -> Idris ()
sendHighlighting highlights =
do ist <- getIState
case idris_outputmode ist of
RawOutput _ -> updateIState $
\ist -> ist { idris_highlightedRegions =
highlights ++ idris_highlightedRegions ist }
IdeMode n h ->
let fancier = [ toSExp (fc, fancifyAnnots ist False annot)
| (fc, annot) <- highlights, fullFC fc
]
in case fancier of
[] -> return ()
_ -> runIO . hPutStrLn h $
convSExp "output"
(SymbolAtom "ok",
(SymbolAtom "highlight-source", fancier)) n
where fullFC (FC _ _ _) = True
fullFC _ = False
-- | Write the highlighting information to a file, for use in external tools
-- or in editors that don't support the IDE protocol
writeHighlights :: FilePath -> Idris ()
writeHighlights f =
do ist <- getIState
let hs = reverse $ idris_highlightedRegions ist
let hfile = replaceExtension f "idh"
let annots = toSExp [ (fc, fancifyAnnots ist False annot)
| (fc@(FC _ _ _), annot) <- hs
]
runIO $ writeFile hfile $ sExpToString annots
clearHighlights :: Idris ()
clearHighlights = updateIState $ \ist -> ist { idris_highlightedRegions = [] }
renderExternal :: OutputFmt -> Int -> Doc OutputAnnotation -> Idris String
renderExternal fmt width doc
| width < 1 = throwError . Msg $ "There must be at least one column for the pretty-printer."
| otherwise =
do ist <- getIState
return . wrap fmt .
displayDecorated (decorate fmt) .
renderPretty 1.0 width .
fmap (fancifyAnnots ist True) $
doc
where
decorate _ (AnnFC _) = id
decorate HTMLOutput (AnnName _ (Just TypeOutput) d _) =
tag "idris-type" d
decorate HTMLOutput (AnnName _ (Just FunOutput) d _) =
tag "idris-function" d
decorate HTMLOutput (AnnName _ (Just DataOutput) d _) =
tag "idris-data" d
decorate HTMLOutput (AnnName _ (Just MetavarOutput) d _) =
tag "idris-metavar" d
decorate HTMLOutput (AnnName _ (Just PostulateOutput) d _) =
tag "idris-postulate" d
decorate HTMLOutput (AnnName _ _ _ _) = id
decorate HTMLOutput (AnnBoundName _ True) = tag "idris-bound idris-implicit" Nothing
decorate HTMLOutput (AnnBoundName _ False) = tag "idris-bound" Nothing
decorate HTMLOutput (AnnConst c) =
tag (if constIsType c then "idris-type" else "idris-data")
(Just $ constDocs c)
decorate HTMLOutput (AnnData _ _) = tag "idris-data" Nothing
decorate HTMLOutput (AnnType _ _) = tag "idris-type" Nothing
decorate HTMLOutput AnnKeyword = tag "idris-keyword" Nothing
decorate HTMLOutput (AnnTextFmt fmt) =
case fmt of
BoldText -> mkTag "strong"
ItalicText -> mkTag "em"
UnderlineText -> tag "idris-underlined" Nothing
where mkTag t x = "<"++t++">"++x++"</"++t++">"
decorate HTMLOutput (AnnTerm _ _) = id
decorate HTMLOutput (AnnSearchResult _) = id
decorate HTMLOutput (AnnErr _) = id
decorate HTMLOutput (AnnNamespace _ _) = id
decorate HTMLOutput (AnnLink url) =
\txt -> "<a href=\"" ++ url ++ "\">" ++ txt ++ "</a>"
decorate HTMLOutput AnnQuasiquote = id
decorate HTMLOutput AnnAntiquote = id
decorate LaTeXOutput (AnnName _ (Just TypeOutput) _ _) =
latex "IdrisType"
decorate LaTeXOutput (AnnName _ (Just FunOutput) _ _) =
latex "IdrisFunction"
decorate LaTeXOutput (AnnName _ (Just DataOutput) _ _) =
latex "IdrisData"
decorate LaTeXOutput (AnnName _ (Just MetavarOutput) _ _) =
latex "IdrisMetavar"
decorate LaTeXOutput (AnnName _ (Just PostulateOutput) _ _) =
latex "IdrisPostulate"
decorate LaTeXOutput (AnnName _ _ _ _) = id
decorate LaTeXOutput (AnnBoundName _ True) = latex "IdrisImplicit"
decorate LaTeXOutput (AnnBoundName _ False) = latex "IdrisBound"
decorate LaTeXOutput (AnnConst c) =
latex $ if constIsType c then "IdrisType" else "IdrisData"
decorate LaTeXOutput (AnnData _ _) = latex "IdrisData"
decorate LaTeXOutput (AnnType _ _) = latex "IdrisType"
decorate LaTeXOutput AnnKeyword = latex "IdrisKeyword"
decorate LaTeXOutput (AnnTextFmt fmt) =
case fmt of
BoldText -> latex "textbf"
ItalicText -> latex "emph"
UnderlineText -> latex "underline"
decorate LaTeXOutput (AnnTerm _ _) = id
decorate LaTeXOutput (AnnSearchResult _) = id
decorate LaTeXOutput (AnnErr _) = id
decorate LaTeXOutput (AnnNamespace _ _) = id
decorate LaTeXOutput (AnnLink url) = (++ "(\\url{" ++ url ++ "})")
decorate LaTeXOutput AnnQuasiquote = id
decorate LaTeXOutput AnnAntiquote = id
tag cls docs str = "<span class=\""++cls++"\""++title++">" ++ str ++ "</span>"
where title = maybe "" (\d->" title=\"" ++ d ++ "\"") docs
latex cmd str = "\\"++cmd++"{"++str++"}"
wrap HTMLOutput str =
"<!doctype html><html><head><style>" ++ css ++ "</style></head>" ++
"<body><!-- START CODE --><pre>" ++ str ++ "</pre><!-- END CODE --></body></html>"
where css = concat . intersperse "\n" $
[".idris-data { color: red; } ",
".idris-type { color: blue; }",
".idris-function {color: green; }",
".idris-keyword { font-weight: bold; }",
".idris-bound { color: purple; }",
".idris-implicit { font-style: italic; }",
".idris-underlined { text-decoration: underline; }"]
wrap LaTeXOutput str =
concat . intersperse "\n" $
["\\documentclass{article}",
"\\usepackage{fancyvrb}",
"\\usepackage[usenames]{xcolor}"] ++
map (\(cmd, color) ->
"\\newcommand{\\"++ cmd ++
"}[1]{\\textcolor{"++ color ++"}{#1}}")
[("IdrisData", "red"), ("IdrisType", "blue"),
("IdrisBound", "magenta"), ("IdrisFunction", "green")] ++
["\\newcommand{\\IdrisKeyword}[1]{{\\underline{#1}}}",
"\\newcommand{\\IdrisImplicit}[1]{{\\itshape \\IdrisBound{#1}}}",
"\n",
"\\begin{document}",
"% START CODE",
"\\begin{Verbatim}[commandchars=\\\\\\{\\}]",
str,
"\\end{Verbatim}",
"% END CODE",
"\\end{document}"]
|
enolan/Idris-dev
|
src/Idris/Output.hs
|
bsd-3-clause
| 15,694 | 0 | 22 | 4,857 | 4,586 | 2,256 | 2,330 | 312 | 48 |
{-# OPTIONS_GHC -Wall #-}
module Cis194.Hw.LogAnalysis where
-- in ghci, you may need to specify an additional include path:
-- Prelude> :set -isrc
import Cis194.Hw.Log
-- $setup
-- >>> let foo = LogMessage Warning 10 "foo"
-- >>> let baz = LogMessage Warning 5 "baz"
-- >>> let bif = LogMessage Warning 15 "bif"
-- >>> let zor = LogMessage (Error 2) 562 "zor"
parseMessage :: String -> LogMessage
parseMessage s = case s of
[] -> Unknown "not good"
'E':_ -> do
let _:y:z:zs = (words s)
er = (read y)::Int
ts = (read z)::Int
str= unwords zs
LogMessage (Error er) ts str
'I':_ -> do
let _:z:zs = (words s)
ts = (read z)::Int
str= unwords zs
LogMessage Info ts str
'W':_ -> do
let _:z:zs = (words s)
ts = (read z)::Int
str= unwords zs
LogMessage Warning ts str
_ -> Unknown s
parse :: String -> [LogMessage]
parse s = case s of
"" -> []
xs -> let dems = lines xs
in map parseMessage dems
-- | 1. test for getter: ts
-- >>> let foo = LogMessage Warning 10 "foo"
-- >>> tst foo
-- 10
tst :: LogMessage -> Int
tst (LogMessage _ t _) = t
tst _ = 0
-- | find LogMessage type
-- >>> let zor = LogMessage (Error 2) 562 "zor"
-- >>> logMessage zor
-- Error 2
-- logMessage :: LogMessage -> MessageType
-- logMessage (LogMessage l _ _) = l
-- logMessage _ = Info
-- | insert for LogMessages
-- >>> insert (Unknown "foo") Leaf
-- Leaf
-- >>> let a = Leaf
-- >>> let b = LogMessage Warning 5 "baz"
-- >>> insert b a
-- Node Leaf b Leaf
-- | insert maintains the sort order of messages in the tree
-- >>> let foo = LogMessage Warning 10 "foo"
-- >>> let baz = LogMessage Warning 5 "baz"
-- >>> let bif = LogMessage Warning 15 "bif"
-- >>> let zor = LogMessage (Error 2) 562 "zor"
-- >>> let a = Node Leaf foo Leaf
-- >>> insert baz a
-- Node (Node Leaf baz Leaf) foo Leaf
-- >>> insert bif b
-- Node (Node Leaf baz Leaf) foo1 (Node Leaf bif Leaf)
insert :: LogMessage -> MessageTree -> MessageTree
insert (Unknown _) Leaf = Leaf
insert lm Leaf = Node Leaf lm Leaf
insert lm (Node l m r) | (tst lm) >= (tst m) = Node l m (insert lm r)
| otherwise = Node (insert lm l) m r
-- | Build: builds a MessageTree from a list of LogMessages
----- >>> let foo = LogMessage Warning 10 "foo"
---- >>> let baz = LogMessage Warning 5 "baz"
---- >>> let bif = LogMessage Warning 15 "bif"
-- >>> let ans = Node (Node Leaf (LogMessage Warning 5 "baz") Leaf) (LogMessage Warning 10 "foo") (Node Leaf (LogMessage Warning 15 "bif") Leaf)
-- >>> build [foo, baz, bif]
-- ans
----- Node (Node Leaf (LogMessage Warning 5 "baz") Leaf) (LogMessage Warning 10 "foo") (Node Leaf (LogMessage Warning 15 "bif") Leaf)
build :: [LogMessage] -> MessageTree
build = foldl (flip insert) Leaf
inOrder :: MessageTree -> [LogMessage]
inOrder Leaf = []
inOrder (Node l m r) = inOrder l ++ [m] ++ inOrder r
-- | build then order:
buildThenOrder :: [LogMessage] -> [LogMessage]
buildThenOrder = inOrder . build
-- | function isError
isError :: MessageType -> Bool
isError x = case x of
(Error _) -> True
Warning -> False
Info -> False
-- | message type from log massage
messType :: LogMessage -> MessageType
messType (LogMessage mt _ _) = mt
messType _ = Info
-- | gets the message
mess :: LogMessage -> String
mess (LogMessage _ _ str) = str
mess _ = ""
-- | is this an error LogMessage?
isLogMessageError :: LogMessage -> Bool
isLogMessageError = isError . messType
-- | does this error message exceed 50?
exceedsThreshold50 :: MessageType -> Bool
exceedsThreshold50 (Error x)
| x >= 50 = True
| otherwise = False
exceedsThreshold50 Info = False
exceedsThreshold50 Warning = False
thresholdFor50 :: LogMessage -> Bool
thresholdFor50 = exceedsThreshold50 . messType
-- let yy = filter isLogMessageError (buildThenOrder messages)
-- whatWentWrong takes an unsorted list of LogMessages, and returns a list of the
-- messages corresponding to any errors with a severity of 50 or greater,
-- sorted by timestamp.
whatWentWrong :: [LogMessage] -> [String]
whatWentWrong xs = map mess $ filter thresholdFor50 $ filter isLogMessageError $ buildThenOrder xs
|
halarnold2000/cis194
|
src/Cis194/Hw/LogAnalysis.hs
|
bsd-3-clause
| 4,449 | 0 | 15 | 1,203 | 914 | 487 | 427 | 66 | 5 |
module Problem13
( numbers100
, sum100numbers
, columnarAddition
) where
import Data.List as L
import Lib (digits, number)
numbers100 :: [Integer]
numbers100 = [ 37107287533902102798797998220837590246510135740250
, 46376937677490009712648124896970078050417018260538
, 74324986199524741059474233309513058123726617309629
, 91942213363574161572522430563301811072406154908250
, 23067588207539346171171980310421047513778063246676
, 89261670696623633820136378418383684178734361726757
, 28112879812849979408065481931592621691275889832738
, 44274228917432520321923589422876796487670272189318
, 47451445736001306439091167216856844588711603153276
, 70386486105843025439939619828917593665686757934951
, 62176457141856560629502157223196586755079324193331
, 64906352462741904929101432445813822663347944758178
, 92575867718337217661963751590579239728245598838407
, 58203565325359399008402633568948830189458628227828
, 80181199384826282014278194139940567587151170094390
, 35398664372827112653829987240784473053190104293586
, 86515506006295864861532075273371959191420517255829
, 71693888707715466499115593487603532921714970056938
, 54370070576826684624621495650076471787294438377604
, 53282654108756828443191190634694037855217779295145
, 36123272525000296071075082563815656710885258350721
, 45876576172410976447339110607218265236877223636045
, 17423706905851860660448207621209813287860733969412
, 81142660418086830619328460811191061556940512689692
, 51934325451728388641918047049293215058642563049483
, 62467221648435076201727918039944693004732956340691
, 15732444386908125794514089057706229429197107928209
, 55037687525678773091862540744969844508330393682126
, 18336384825330154686196124348767681297534375946515
, 80386287592878490201521685554828717201219257766954
, 78182833757993103614740356856449095527097864797581
, 16726320100436897842553539920931837441497806860984
, 48403098129077791799088218795327364475675590848030
, 87086987551392711854517078544161852424320693150332
, 59959406895756536782107074926966537676326235447210
, 69793950679652694742597709739166693763042633987085
, 41052684708299085211399427365734116182760315001271
, 65378607361501080857009149939512557028198746004375
, 35829035317434717326932123578154982629742552737307
, 94953759765105305946966067683156574377167401875275
, 88902802571733229619176668713819931811048770190271
, 25267680276078003013678680992525463401061632866526
, 36270218540497705585629946580636237993140746255962
, 24074486908231174977792365466257246923322810917141
, 91430288197103288597806669760892938638285025333403
, 34413065578016127815921815005561868836468420090470
, 23053081172816430487623791969842487255036638784583
, 11487696932154902810424020138335124462181441773470
, 63783299490636259666498587618221225225512486764533
, 67720186971698544312419572409913959008952310058822
, 95548255300263520781532296796249481641953868218774
, 76085327132285723110424803456124867697064507995236
, 37774242535411291684276865538926205024910326572967
, 23701913275725675285653248258265463092207058596522
, 29798860272258331913126375147341994889534765745501
, 18495701454879288984856827726077713721403798879715
, 38298203783031473527721580348144513491373226651381
, 34829543829199918180278916522431027392251122869539
, 40957953066405232632538044100059654939159879593635
, 29746152185502371307642255121183693803580388584903
, 41698116222072977186158236678424689157993532961922
, 62467957194401269043877107275048102390895523597457
, 23189706772547915061505504953922979530901129967519
, 86188088225875314529584099251203829009407770775672
, 11306739708304724483816533873502340845647058077308
, 82959174767140363198008187129011875491310547126581
, 97623331044818386269515456334926366572897563400500
, 42846280183517070527831839425882145521227251250327
, 55121603546981200581762165212827652751691296897789
, 32238195734329339946437501907836945765883352399886
, 75506164965184775180738168837861091527357929701337
, 62177842752192623401942399639168044983993173312731
, 32924185707147349566916674687634660915035914677504
, 99518671430235219628894890102423325116913619626622
, 73267460800591547471830798392868535206946944540724
, 76841822524674417161514036427982273348055556214818
, 97142617910342598647204516893989422179826088076852
, 87783646182799346313767754307809363333018982642090
, 10848802521674670883215120185883543223812876952786
, 71329612474782464538636993009049310363619763878039
, 62184073572399794223406235393808339651327408011116
, 66627891981488087797941876876144230030984490851411
, 60661826293682836764744779239180335110989069790714
, 85786944089552990653640447425576083659976645795096
, 66024396409905389607120198219976047599490197230297
, 64913982680032973156037120041377903785566085089252
, 16730939319872750275468906903707539413042652315011
, 94809377245048795150954100921645863754710598436791
, 78639167021187492431995700641917969777599028300699
, 15368713711936614952811305876380278410754449733078
, 40789923115535562561142322423255033685442488917353
, 44889911501440648020369068063960672322193204149535
, 41503128880339536053299340368006977710650566631954
, 81234880673210146739058568557934581403627822703280
, 82616570773948327592232845941706525094512325230608
, 22918802058777319719839450180888072429661980811197
, 77158542502016545090413245809786882778948721859617
, 72107838435069186155435662884062257473692284509516
, 20849603980134001723930671666823555245252804609722
, 53503534226472524250874054075591789781264330331690 ]
sum100numbers = columnarAddition numbers100
columnarAddition :: [Integer] -> Integer
columnarAddition numbers =
let numbersAsDigits = map digits numbers
columns = L.transpose $ map L.reverse numbersAsDigits
(sumDigits, carryOver) = foldl sumColumns ([], 0) columns
in number $ digits carryOver ++ sumDigits
where sumColumns :: ([Integer], Integer) -> [Integer] -> ([Integer], Integer)
sumColumns (sumDigits,carryOver) nextDigits =
let nextSum = (sum nextDigits) + carryOver
nextDigit = nextSum `mod` 10
nextCarryOver = nextSum `div` 10
in (nextDigit:sumDigits, nextCarryOver)
|
candidtim/euler
|
src/Problem13.hs
|
bsd-3-clause
| 7,418 | 0 | 13 | 1,678 | 551 | 342 | 209 | 120 | 1 |
{-# LANGUAGE RebindableSyntax #-}
-- Copyright : (C) 2009 Corey O'Connor
-- License : BSD-style (see the file LICENSE)
{-# LANGUAGE MagicHash #-}
module Bind.Marshal.Verify.Dynamic where
import Bind.Marshal.Prelude
import Bind.Marshal.Action.Base
import Bind.Marshal.Action.Dynamic
import Bind.Marshal.Action.Monad
import Control.Applicative
import Data.IORef
import GHC.Exts
import GHC.Prim
import System.IO
import Verify
data NopDelegate = NopDelegate
instance BufferDelegate NopDelegate where
gen_region 0 NopDelegate
= returnM $! BDIter 0 0 NopDelegate nullAddr# nullAddr#
gen_region _size NopDelegate
= fail "NopDelegate can only generate 0 sized buffers"
finalize_region bd_iter
| bytes_final bd_iter == 0 = returnM (buffer_delegate bd_iter)
| otherwise = fail "NopDelegate can only finalize 0 sized buffers"
data LoggingDelegate sub_delegate where
LoggingDelegate :: BufferDelegate sub_delegate
=> [ProducerLogEntry]
-> sub_delegate
-> LoggingDelegate sub_delegate
data ProducerLogEntry
= GenBuffer Size Size -- Requested miminum size. Max bytes avail of generated buffer.
| FinalizeBuffer Size -- Actual finalize size.
deriving ( Show, Eq )
logging_buffer_delegate :: BufferDelegate bd => bd -> IO (LoggingDelegate bd)
logging_buffer_delegate sub_delegate = returnM $! LoggingDelegate [] sub_delegate
dump_request_log :: LoggingDelegate sub_delegate -> IO ()
dump_request_log (LoggingDelegate log _sub) = do
mapM_ (\s -> log_out $ show s) log :: IO ()
instance BufferDelegate sub_delegate => BufferDelegate (LoggingDelegate sub_delegate) where
gen_region size (LoggingDelegate log sub_p) = do
bd_iter <- gen_region size sub_p
let sub_p' = buffer_delegate bd_iter
let log' = log ++ [GenBuffer size (max_bytes_avail bd_iter) ]
returnM $! bd_iter { buffer_delegate = LoggingDelegate log' sub_p' }
:: IO (BDIter (LoggingDelegate sub_delegate))
finalize_region bd_iter@(BDIter _ _ bd s p) = do
let !(LoggingDelegate log sub_p) = bd
log' = log ++ [FinalizeBuffer (I# (minusAddr# p s))]
sub_p' <- finalize_region (bd_iter {buffer_delegate = sub_p})
returnM $! LoggingDelegate log' sub_p' :: IO (LoggingDelegate sub_delegate)
verify_logged_requests :: LoggingDelegate sub_delegate -> [ProducerLogEntry] -> IO ()
verify_logged_requests p@(LoggingDelegate actual _sub_p) expected = do
if actual == expected
then returnM ()
else do
fail $ "expected is:\n" ++ show expected :: IO ()
|
coreyoconnor/bind-marshal
|
src/Bind/Marshal/Verify/Dynamic.hs
|
bsd-3-clause
| 2,661 | 0 | 17 | 592 | 663 | 338 | 325 | -1 | -1 |
-- | Simulates the @isUnicodeIdentifierPart@ Java method. <http://docs.oracle.com/javase/6/docs/api/java/lang/Character.html#isUnicodeIdentifierPart%28int%29>
module Language.Java.Character.IsUnicodeIdentifierPart
(
IsUnicodeIdentifierPart(..)
) where
import Data.Char
import Data.Word
import Data.Set.Diet(Diet)
import qualified Data.Set.Diet as S
-- | Instances simulate Java characters and provide a decision on simulating @isUnicodeIdentifierPart@.
class Enum c => IsUnicodeIdentifierPart c where
isUnicodeIdentifierPart ::
c
-> Bool
isNotUnicodeIdentifierPart ::
c
-> Bool
isNotUnicodeIdentifierPart =
not . isUnicodeIdentifierPart
instance IsUnicodeIdentifierPart Char where
isUnicodeIdentifierPart c =
ord c `S.member` isUnicodeIdentifierPartSet
instance IsUnicodeIdentifierPart Int where
isUnicodeIdentifierPart c =
c `S.member` isUnicodeIdentifierPartSet
instance IsUnicodeIdentifierPart Integer where
isUnicodeIdentifierPart c =
c `S.member` isUnicodeIdentifierPartSet
instance IsUnicodeIdentifierPart Word8 where
isUnicodeIdentifierPart c =
c `S.member` isUnicodeIdentifierPartSet
instance IsUnicodeIdentifierPart Word16 where
isUnicodeIdentifierPart c =
c `S.member` isUnicodeIdentifierPartSet
instance IsUnicodeIdentifierPart Word32 where
isUnicodeIdentifierPart c =
c `S.member` isUnicodeIdentifierPartSet
instance IsUnicodeIdentifierPart Word64 where
isUnicodeIdentifierPart c =
c `S.member` isUnicodeIdentifierPartSet
isUnicodeIdentifierPartSet ::
(Num a, Enum a, Ord a) =>
Diet a
isUnicodeIdentifierPartSet =
let r = [
[0..8]
, [14..27]
, [48..57]
, [65..90]
, [95]
, [97..122]
, [127..159]
, [170]
, [173]
, [181]
, [186]
, [192..214]
, [216..246]
, [248..566]
, [592..705]
, [710..721]
, [736..740]
, [750]
, [768..855]
, [861..879]
, [890]
, [902]
, [904..906]
, [908]
, [910..929]
, [931..974]
, [976..1013]
, [1015..1019]
, [1024..1153]
, [1155..1158]
, [1162..1230]
, [1232..1269]
, [1272..1273]
, [1280..1295]
, [1329..1366]
, [1369]
, [1377..1415]
, [1425..1441]
, [1443..1465]
, [1467..1469]
, [1471]
, [1473..1474]
, [1476]
, [1488..1514]
, [1520..1522]
, [1536..1539]
, [1552..1557]
, [1569..1594]
, [1600..1624]
, [1632..1641]
, [1646..1747]
, [1749..1757]
, [1759..1768]
, [1770..1788]
, [1791]
, [1807..1866]
, [1869..1871]
, [1920..1969]
, [2305..2361]
, [2364..2381]
, [2384..2388]
, [2392..2403]
, [2406..2415]
, [2433..2435]
, [2437..2444]
, [2447..2448]
, [2451..2472]
, [2474..2480]
, [2482]
, [2486..2489]
, [2492..2500]
, [2503..2504]
, [2507..2509]
, [2519]
, [2524..2525]
, [2527..2531]
, [2534..2545]
, [2561..2563]
, [2565..2570]
, [2575..2576]
, [2579..2600]
, [2602..2608]
, [2610..2611]
, [2613..2614]
, [2616..2617]
, [2620]
, [2622..2626]
, [2631..2632]
, [2635..2637]
, [2649..2652]
, [2654]
, [2662..2676]
, [2689..2691]
, [2693..2701]
, [2703..2705]
, [2707..2728]
, [2730..2736]
, [2738..2739]
, [2741..2745]
, [2748..2757]
, [2759..2761]
, [2763..2765]
, [2768]
, [2784..2787]
, [2790..2799]
, [2817..2819]
, [2821..2828]
, [2831..2832]
, [2835..2856]
, [2858..2864]
, [2866..2867]
, [2869..2873]
, [2876..2883]
, [2887..2888]
, [2891..2893]
, [2902..2903]
, [2908..2909]
, [2911..2913]
, [2918..2927]
, [2929]
, [2946..2947]
, [2949..2954]
, [2958..2960]
, [2962..2965]
, [2969..2970]
, [2972]
, [2974..2975]
, [2979..2980]
, [2984..2986]
, [2990..2997]
, [2999..3001]
, [3006..3010]
, [3014..3016]
, [3018..3021]
, [3031]
, [3047..3055]
, [3073..3075]
, [3077..3084]
, [3086..3088]
, [3090..3112]
, [3114..3123]
, [3125..3129]
, [3134..3140]
, [3142..3144]
, [3146..3149]
, [3157..3158]
, [3168..3169]
, [3174..3183]
, [3202..3203]
, [3205..3212]
, [3214..3216]
, [3218..3240]
, [3242..3251]
, [3253..3257]
, [3260..3268]
, [3270..3272]
, [3274..3277]
, [3285..3286]
, [3294]
, [3296..3297]
, [3302..3311]
, [3330..3331]
, [3333..3340]
, [3342..3344]
, [3346..3368]
, [3370..3385]
, [3390..3395]
, [3398..3400]
, [3402..3405]
, [3415]
, [3424..3425]
, [3430..3439]
, [3458..3459]
, [3461..3478]
, [3482..3505]
, [3507..3515]
, [3517]
, [3520..3526]
, [3530]
, [3535..3540]
, [3542]
, [3544..3551]
, [3570..3571]
, [3585..3642]
, [3648..3662]
, [3664..3673]
, [3713..3714]
, [3716]
, [3719..3720]
, [3722]
, [3725]
, [3732..3735]
, [3737..3743]
, [3745..3747]
, [3749]
, [3751]
, [3754..3755]
, [3757..3769]
, [3771..3773]
, [3776..3780]
, [3782]
, [3784..3789]
, [3792..3801]
, [3804..3805]
, [3840]
, [3864..3865]
, [3872..3881]
, [3893]
, [3895]
, [3897]
, [3902..3911]
, [3913..3946]
, [3953..3972]
, [3974..3979]
, [3984..3991]
, [3993..4028]
, [4038]
, [4096..4129]
, [4131..4135]
, [4137..4138]
, [4140..4146]
, [4150..4153]
, [4160..4169]
, [4176..4185]
, [4256..4293]
, [4304..4344]
, [4352..4441]
, [4447..4514]
, [4520..4601]
, [4608..4614]
, [4616..4678]
, [4680]
, [4682..4685]
, [4688..4694]
, [4696]
, [4698..4701]
, [4704..4742]
, [4744]
, [4746..4749]
, [4752..4782]
, [4784]
, [4786..4789]
, [4792..4798]
, [4800]
, [4802..4805]
, [4808..4814]
, [4816..4822]
, [4824..4846]
, [4848..4878]
, [4880]
, [4882..4885]
, [4888..4894]
, [4896..4934]
, [4936..4954]
, [4969..4977]
, [5024..5108]
, [5121..5740]
, [5743..5750]
, [5761..5786]
, [5792..5866]
, [5870..5872]
, [5888..5900]
, [5902..5908]
, [5920..5940]
, [5952..5971]
, [5984..5996]
, [5998..6000]
, [6002..6003]
, [6016..6099]
, [6103]
, [6108..6109]
, [6112..6121]
, [6155..6157]
, [6160..6169]
, [6176..6263]
, [6272..6313]
, [6400..6428]
, [6432..6443]
, [6448..6459]
, [6470..6509]
, [6512..6516]
, [7424..7531]
, [7680..7835]
, [7840..7929]
, [7936..7957]
, [7960..7965]
, [7968..8005]
, [8008..8013]
, [8016..8023]
, [8025]
, [8027]
, [8029]
, [8031..8061]
, [8064..8116]
, [8118..8124]
, [8126]
, [8130..8132]
, [8134..8140]
, [8144..8147]
, [8150..8155]
, [8160..8172]
, [8178..8180]
, [8182..8188]
, [8204..8207]
, [8234..8238]
, [8255..8256]
, [8276]
, [8288..8291]
, [8298..8303]
, [8305]
, [8319]
, [8400..8412]
, [8417]
, [8421..8426]
, [8450]
, [8455]
, [8458..8467]
, [8469]
, [8473..8477]
, [8484]
, [8486]
, [8488]
, [8490..8493]
, [8495..8497]
, [8499..8505]
, [8509..8511]
, [8517..8521]
, [8544..8579]
, [12293..12295]
, [12321..12335]
, [12337..12341]
, [12344..12348]
, [12353..12438]
, [12441..12442]
, [12445..12447]
, [12449..12543]
, [12549..12588]
, [12593..12686]
, [12704..12727]
, [12784..12799]
, [13312..19893]
, [19968..40869]
, [40960..42124]
, [44032..55203]
, [63744..64045]
, [64048..64106]
, [64256..64262]
, [64275..64279]
, [64285..64296]
, [64298..64310]
, [64312..64316]
, [64318]
, [64320..64321]
, [64323..64324]
, [64326..64433]
, [64467..64829]
, [64848..64911]
, [64914..64967]
, [65008..65019]
, [65024..65039]
, [65056..65059]
, [65075..65076]
, [65101..65103]
, [65136..65140]
, [65142..65276]
, [65279]
, [65296..65305]
, [65313..65338]
, [65343]
, [65345..65370]
, [65381..65470]
, [65474..65479]
, [65482..65487]
, [65490..65495]
, [65498..65500]
, [65529..65531]
, [65536..65547]
, [65549..65574]
, [65576..65594]
, [65596..65597]
, [65599..65613]
, [65616..65629]
, [65664..65786]
, [66304..66334]
, [66352..66378]
, [66432..66461]
, [66560..66717]
, [66720..66729]
, [67584..67589]
, [67592]
, [67594..67637]
, [67639..67640]
, [67644]
, [67647]
, [119141..119145]
, [119149..119170]
, [119173..119179]
, [119210..119213]
, [119808..119892]
, [119894..119964]
, [119966..119967]
, [119970]
, [119973..119974]
, [119977..119980]
, [119982..119993]
, [119995]
, [119997..120003]
, [120005..120069]
, [120071..120074]
, [120077..120084]
, [120086..120092]
, [120094..120121]
, [120123..120126]
, [120128..120132]
, [120134]
, [120138..120144]
, [120146..120483]
, [120488..120512]
, [120514..120538]
, [120540..120570]
, [120572..120596]
, [120598..120628]
, [120630..120654]
, [120656..120686]
, [120688..120712]
, [120714..120744]
, [120746..120770]
, [120772..120777]
, [120782..120831]
, [131072..173782]
, [194560..195101]
]
in S.fromList . concat $ r
|
tonymorris/java-character
|
src/Language/Java/Character/IsUnicodeIdentifierPart.hs
|
bsd-3-clause
| 12,247 | 0 | 10 | 5,425 | 3,632 | 2,264 | 1,368 | 474 | 1 |
{-# LANGUAGE TemplateHaskell #-}
module NintetyNine.Problem16 where
import Test.Hspec
import Test.QuickCheck
import Test.QuickCheck.All
import Data.List
-- dropEvery "abcdefghik" 3 "abdeghk"
dropEvery :: [a] -> Int -> [a]
dropEvery xs n
| length xs < n = xs
| otherwise = take (n - 1) xs ++ dropEvery (drop n xs) n
dropEvery2 :: [a] -> Int -> [a]
dropEvery2 [] _ = []
dropEvery2 xs n = take (n - 1) xs ++ dropEvery2 (drop n xs) n
-- using flip, zip, map, first , snd, cycle
dropEvery3 :: [a] -> Int -> [a]
dropEvery3 =
-- dropEvery x : drop + repeat for every n
-- have a list and delete every element at position multiple of n
-- how to delete an element from a list or create a new list without that element
-- foldl untill find index = n * x
-- scanl where it concatenates every x except if it has index m
-- with splitAt
-- dropEvery :: [a] -> Int -> [a]
-- dropEvery xs n = y ++ (dropEvery ys)
-- where (y:ys) = (splitAt n xs)
-- dropEvery2 :: [a] -> Int -> [a]
-- dropEvery2 xs n = let (y::ys) = (splitAt n xs)
-- in y ++ (dropEvery2 ys)
-- Test
-- hspec
dropEverySpec :: Spec
dropEverySpec = do
describe "Drop every N'th element from a list." $ do
it "Drop every N'th element from a list." $ do
dropEvery "abcdefghik" 3 `shouldBe` "abdeghk"
describe "[With dropEvery2] Drop every N'th element from a list." $ do
it "Drop every N'th element from a list." $ do
dropEvery2 "abcdefghik" 3 `shouldBe` "abdeghk"
-- QuickCheck
return []
main = $quickCheckAll
|
chemouna/99Haskell
|
src/Problem16.hs
|
bsd-3-clause
| 1,547 | 0 | 14 | 367 | 311 | 166 | 145 | -1 | -1 |
#!/usr/bin/runhaskell
module Main where
import Distribution.Simple
main :: IO ()
main = defaultMain
|
colinhect/hsnoise
|
Setup.hs
|
bsd-3-clause
| 104 | 0 | 6 | 17 | 25 | 15 | 10 | 4 | 1 |
------------------------------------------------------------
-- |
-- Module : Data.NeuralNetwork.Backend.BLASHS
-- Description : A backend for neural network on top of 'blas-hs'
-- Copyright : (c) 2016 Jiasen Wu
-- License : BSD-style (see the file LICENSE)
-- Maintainer : Jiasen Wu <[email protected]>
-- Stability : experimental
-- Portability : portable
--
--
-- This module supplies a backend for the neural-network-base
-- package. This backend is implemented on top of the blas-hs
-- package and optimised with SIMD.
------------------------------------------------------------
{-# LANGUAGE UndecidableInstances #-}
module Data.NeuralNetwork.Backend.BLASHS (
-- module Data.NeuralNetwork.Backend.BLASHS.Layers,
module Data.NeuralNetwork.Backend.BLASHS.Utils,
module Data.NeuralNetwork.Backend.BLASHS.LSTM,
module Data.NeuralNetwork.Backend.BLASHS.SIMD,
ByBLASHS(..), byBLASHSf, byBLASHSd
) where
import Data.NeuralNetwork
import Data.NeuralNetwork.Stack
import Data.NeuralNetwork.Common
import Data.NeuralNetwork.Backend.BLASHS.Layers
import Data.NeuralNetwork.Backend.BLASHS.LSTM
import Data.NeuralNetwork.Backend.BLASHS.Utils
import Data.NeuralNetwork.Backend.BLASHS.Eval
import Data.NeuralNetwork.Backend.BLASHS.SIMD
import Control.Monad.Except (ExceptT, throwError)
import Control.Monad.State
import Data.Constraint (Dict(..))
import Blas.Generic.Unsafe (Numeric)
-- | Compilation of the specification of a neural network is carried out in
-- the 'Err' monad, and the possible errors are characterized by 'ErrCode'.
type Err = ExceptT ErrCode IO
-- | The backend data type
data ByBLASHS p = ByBLASHS
byBLASHSf :: ByBLASHS Float
byBLASHSf = ByBLASHS
byBLASHSd :: ByBLASHS Double
byBLASHSd = ByBLASHS
type AbbrSpecToCom p s = SpecToCom (ByBLASHS p) s
type AbbrSpecToEvl p s o = SpecToEvl (ByBLASHS p) (AbbrSpecToCom p s) o
-- | Neural network specified to start with 1D / 2D input
instance (InputLayer i, RealType p,
BodyTrans Err (ByBLASHS p) s,
EvalTrans Err (ByBLASHS p) (AbbrSpecToCom p s) o,
BackendCst Err (AbbrSpecToCom p s) (AbbrSpecToEvl p s o))
=> Backend (ByBLASHS p) (i,s,o) where
type Env (ByBLASHS p) = Err
type ComponentFromSpec (ByBLASHS p) (i,s,o) = AbbrSpecToCom p s
type EvaluatorFromSpec (ByBLASHS p) (i,s,o) = AbbrSpecToEvl p s o
compile b (i,s,o) = do c <- btrans b (isize i) s
e <- etrans b c o
return $ (c, e)
witness _ _ = Dict
instance RunInEnv IO Err where
run = liftIO
instance (Numeric p, RealType p, SIMDable p) => BodyTrans Err (ByBLASHS p) SpecFullConnect where
-- 'SpecFullConnect' is translated to a two-layer component
-- a full-connect, followed by a relu activation (1D, single channel)
type SpecToCom (ByBLASHS p) SpecFullConnect = Stack (RunLayer p F) (RunLayer p (T SinglVec)) CE
btrans _ (D1 s) (FullConnect n) = do u <- lift $ newFLayer s n
return $ Stack u (Activation (relu, relu'))
btrans _ _ _ = throwError ErrMismatch
instance (Numeric p, RealType p, SIMDable p) => BodyTrans Err (ByBLASHS p) SpecConvolution where
-- 'SpecConvolution' is translated to a two-layer component
-- a convolution, following by a relu activation (2D, multiple channels)
type SpecToCom (ByBLASHS p) SpecConvolution = Stack (RunLayer p C) (RunLayer p (T MultiMat)) CE
btrans _ (D2 k s t) (Convolution n f p) = do u <- lift $ newCLayer k n f p
return $ Stack u (Activation (relu, relu'))
btrans _ _ _ = throwError ErrMismatch
instance (Numeric p, RealType p, SIMDable p) => BodyTrans Err (ByBLASHS p) SpecMaxPooling where
-- 'MaxPooling' is translated to a max-pooling component.
type SpecToCom (ByBLASHS p) SpecMaxPooling = RunLayer p P
btrans _ (D2 _ _ _) (MaxPooling n) = return (MaxP n)
btrans _ _ _ = throwError ErrMismatch
instance (Numeric p, RealType p, SIMDable p) => BodyTrans Err (ByBLASHS p) SpecReshape2DAs1D where
-- 'SpecReshape2DAs1D' is translated to a reshaping component.
type SpecToCom (ByBLASHS p) SpecReshape2DAs1D = Reshape2DAs1D p
btrans _ (D2 _ _ _) _ = return as1D
btrans _ _ _ = throwError ErrMismatch
instance (Numeric p, RealType p, SIMDable p) => BodyTrans Err (ByBLASHS p) SpecLSTM where
-- 'SpecLSTM' is translated to a LSTM component.
type SpecToCom (ByBLASHS p) SpecLSTM = Stack (LSTM p) (RunLayer p (T SinglVec)) (LiftRun (Run (LSTM p)) (Run (RunLayer p (T SinglVec))))
btrans _ (D1 s) (LSTM n) = do u <- lift $ newLSTM s n
return $ Stack u (Activation (relu, relu'))
btrans _ _ _ = throwError ErrMismatch
instance (BodyTrans Err (ByBLASHS p) a) => BodyTrans Err (ByBLASHS p) (SpecFlow a) where
--
type SpecToCom (ByBLASHS p) (SpecFlow a) = Stream (SpecToCom (ByBLASHS p) a)
btrans b (SV s) (Flow a) = do u <- btrans b s a
return $ Stream u
btrans _ _ _ = throwError ErrMismatch
instance Component c => EvalTrans Err (ByBLASHS p) c SpecEvaluator where
type SpecToEvl (ByBLASHS p) c SpecEvaluator = Eval (Run c) p
etrans _ _ = return . Eval
|
pierric/neural-network
|
Backend-blashs/Data/NeuralNetwork/Backend/BLASHS.hs
|
bsd-3-clause
| 5,167 | 0 | 14 | 1,079 | 1,526 | 814 | 712 | -1 | -1 |
--
-- Benchmark code: sample request using http-condiuit
--
-- Copyright © 2012-2013 Operational Dynamics Consulting, 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 a BSD licence.
--
{-# LANGUAGE OverloadedStrings #-}
module ConduitSample (sampleViaHttpConduit) where
import Control.Monad.Trans (liftIO)
import qualified Data.ByteString.Char8 as S
import qualified Data.ByteString.Lazy.Char8 as L
import Data.CaseInsensitive (CI, original)
import Data.Conduit
import Data.Conduit.Binary (sinkHandle, sourceLbs)
import Network.HTTP.Conduit
import Network.HTTP.Types
import System.IO (IOMode (..), hClose, openFile)
main :: IO ()
main = do
withManager $ liftIO . sampleViaHttpConduit
sampleViaHttpConduit :: Manager -> IO ()
sampleViaHttpConduit manager = do
runResourceT $ do
req <- parseUrl "http://localhost/"
let req2 = req {
checkStatus = \_ _ _ -> Nothing,
requestHeaders = [(hAccept, "text/html")],
responseTimeout = Nothing
}
res <- http req2 manager
let sta = responseStatus res
ver = responseVersion res
hdr = responseHeaders res
handle <- liftIO $ openFile "/tmp/http-conduit.out" WriteMode
let src = do
sourceLbs (joinStatus sta ver)
sourceLbs (join hdr)
src $$ sinkHandle handle
responseBody res $$+- sinkHandle handle
liftIO $ hClose handle
joinStatus :: Status -> HttpVersion -> L.ByteString
joinStatus sta ver =
L.concat $ map L.pack
[ show ver, " "
, show $ statusCode sta, " "
, S.unpack $ statusMessage sta
, "\n"
]
--
-- Process headers into a single string
--
join :: ResponseHeaders -> L.ByteString
join m =
foldr combineHeaders "" m
combineHeaders :: (CI S.ByteString, S.ByteString) -> L.ByteString -> L.ByteString
combineHeaders (k,v) acc =
L.append acc $ L.fromChunks [key, ": ", value, "\n"]
where
key = original k
value = v
|
afcowie/pipes-http
|
tests/ConduitSample.hs
|
bsd-3-clause
| 2,161 | 0 | 17 | 545 | 540 | 293 | 247 | 48 | 1 |
{-# LANGUAGE DeriveDataTypeable, OverloadedStrings #-}
module Tests.Test.HUnitPlus.Execution where
import Control.Exception(Exception, throwIO)
import Data.List
import Data.HashMap.Strict(HashMap)
import Data.Maybe
import Data.Typeable
import Distribution.TestSuite
import Test.HUnitPlus.Base
import Test.HUnitPlus.Execution
import Test.HUnitPlus.Filter
import Test.HUnitPlus.Reporting
import qualified Data.HashSet as HashSet
import qualified Data.HashMap.Strict as HashMap
import qualified Data.Text as Strict
data ReportEvent =
EndEvent Counts
| StartSuiteEvent State
| EndSuiteEvent State
| StartCaseEvent State
| EndCaseEvent State
| SkipEvent State
| ProgressEvent Strict.Text State
| FailureEvent Strict.Text State
| ErrorEvent Strict.Text State
| SystemErrEvent Strict.Text State
| SystemOutEvent Strict.Text State
deriving (Eq, Show)
fullLoggingReporter :: Reporter [ReportEvent]
fullLoggingReporter = defaultReporter {
reporterStart = return [],
reporterEnd =
\_ ss events -> return $ (EndEvent ss :events),
reporterStartSuite =
\ss events -> return $ (StartSuiteEvent ss : events),
reporterEndSuite =
\_ ss events -> return $ (EndSuiteEvent ss : events),
reporterStartCase =
\ss events -> return $ (StartCaseEvent ss : events),
reporterEndCase =
\_ ss events -> return $ (EndCaseEvent ss : events),
reporterSkipCase =
\ss events -> return $ (SkipEvent ss : events),
reporterCaseProgress =
\msg ss events -> return $ (ProgressEvent msg ss : events),
reporterFailure =
\msg ss events -> return $ (FailureEvent msg ss : events),
reporterError =
\msg ss events -> return $ (ErrorEvent msg ss : events),
reporterSystemErr =
\msg ss events -> return $ (SystemErrEvent msg ss : events),
reporterSystemOut =
\msg ss events -> return $ (SystemOutEvent msg ss : events)
}
makeTagName False False = "no_tag"
makeTagName True False = "tag1"
makeTagName False True = "tag2"
makeTagName True True = "tag12"
makeTagSet (False, False) = HashSet.empty
makeTagSet (True, False) = HashSet.singleton "tag1"
makeTagSet (False, True) = HashSet.singleton "tag2"
makeTagSet (True, True) = HashSet.fromList ["tag1", "tag2"]
data TestException = TestException
deriving (Show, Typeable)
instance Exception TestException
data Behavior = Normal Result | Exception
makeResName (Normal Pass) = "pass"
makeResName (Normal (Fail _)) = "fail"
makeResName (Normal (Error _)) = "error"
makeResName Exception = "exception"
makeAssert (Normal Pass) = assertSuccess
makeAssert (Normal (Fail msg)) = assertFailure (Strict.pack msg)
makeAssert (Normal (Error msg)) = abortError (Strict.pack msg)
makeAssert Exception = throwIO TestException
updateCounts (Normal Pass) c @ Counts { cAsserts = asserts } =
c { cAsserts = asserts + 1, cCaseAsserts = 1 }
updateCounts (Normal (Fail _)) c @ Counts { cFailures = fails,
cAsserts = asserts } =
c { cFailures = fails + 1, cAsserts = asserts + 1, cCaseAsserts = 1 }
updateCounts (Normal (Error _)) c @ Counts { cErrors = errors } =
c { cErrors = errors + 1, cCaseAsserts = 0 }
updateCounts Exception c @ Counts { cErrors = errors } =
c { cErrors = errors + 1, cCaseAsserts = 0 }
makeName :: (Bool, Bool, Behavior) -> Strict.Text
makeName (tag1, tag2, res) =
Strict.concat [makeTagName tag1 tag2, "_", makeResName res]
makeTest :: String -> (Bool, Bool, Behavior) -> Test
makeTest prefix tdata @ (tag1, tag2, res) =
let
inittags = if tag1 then ["tag1"] else []
tags = if tag2 then "tag2" : inittags else inittags
testname = prefix ++ (Strict.unpack (makeName tdata))
in
testNameTags testname tags (makeAssert res)
{-
testInstance = TestInstance { name = testname, tags = tags,
setOption = (\_ _ -> Right testInstance),
options = [], run = runTest }
in
Test testInstance
-}
makeTestData :: String -> ([Test], [ReportEvent], State) ->
Either (Bool, Bool, Behavior) (Bool, Bool, Behavior) ->
([Test], [ReportEvent], State)
makeTestData prefix
(tests, events,
ss @ State { stName = oldname,
stCounts = counts @ Counts { cCases = cases,
cTried = tried } })
(Right tdata @ (tag1, tag2, res)) =
let
startedCounts = counts { cCases = cases + 1, cTried = tried + 1 }
finishedCounts = updateCounts res startedCounts
ssWithName = ss { stName = Strict.concat [Strict.pack prefix, makeName tdata] }
ssStarted = ssWithName { stCounts = startedCounts }
ssFinished = ssWithName { stCounts = finishedCounts }
-- Remember, the order is reversed for these, because we reverse
-- the events list in the end.
newevents =
case res of
Normal Pass ->
EndCaseEvent ssFinished : StartCaseEvent ssStarted : events
Normal (Fail msg) ->
EndCaseEvent ssFinished : FailureEvent (Strict.pack msg) ssStarted :
StartCaseEvent ssStarted : events
Normal (Error msg) ->
EndCaseEvent ssFinished : ErrorEvent (Strict.pack msg) ssStarted :
StartCaseEvent ssStarted : events
Exception ->
EndCaseEvent ssFinished :
ErrorEvent "Uncaught exception in test: TestException" ssStarted :
StartCaseEvent ssStarted : events
in
(makeTest prefix tdata : tests, newevents,
ssFinished { stName = oldname })
makeTestData prefix
(tests, events, ss @ State { stCounts =
c @ Counts { cSkipped = skipped,
cCases = cases },
stName = oldname })
(Left tdata) =
let
newcounts = c { cCases = cases + 1, cSkipped = skipped + 1 }
newstate = ss { stCounts = newcounts,
stName = Strict.concat [Strict.pack prefix, makeName tdata] }
in
(makeTest prefix tdata : tests, SkipEvent newstate : events,
newstate { stName = oldname })
resultVals :: [Behavior]
resultVals = [Normal Pass, Normal (Fail "Fail Message"),
Normal (Error "Error Message"), Exception]
tagVals :: [Bool]
tagVals = [True, False]
testData :: [(Bool, Bool, Behavior)]
testData = foldl (\accum tag1 ->
foldl (\accum tag2 ->
foldl (\accum res -> (tag1, tag2, res) : accum)
accum resultVals)
accum tagVals)
[] tagVals
tag1Filter tdata @ (True, _, _) = Right tdata
tag1Filter tdata = Left tdata
tag2Filter tdata @ (_, True, _) = Right tdata
tag2Filter tdata = Left tdata
tag12Filter tdata @ (True, _, _) = Right tdata
tag12Filter tdata @ (_, True, _) = Right tdata
tag12Filter tdata = Left tdata
data ModFilter = All | WithTags (Bool, Bool) | None deriving Show
getTests :: ModFilter -> [Either (Bool, Bool, Behavior) (Bool, Bool, Behavior)]
getTests All = map Right testData
getTests (WithTags (True, False)) = map tag1Filter testData
getTests (WithTags (False, True)) = map tag2Filter testData
getTests (WithTags (True, True)) = map tag12Filter testData
getTests None = map Left testData
-- Generate a list of all mod filters we can use for a sub-module, and
-- the selectors we need for them
getSuperSet :: (Selector -> Selector) -> ModFilter ->
[(ModFilter, Selector, Bool)]
-- If we're already running all tests, there's nothing else we can do
getSuperSet wrapinner All =
[(All, wrapinner (allSelector { selectorTags = Nothing }), False)]
-- If we're running tests with both tags, we can do that, or we can
-- run all tests in the submodule.
getSuperSet wrapinner (WithTags (True, True)) =
[(WithTags (True, True),
wrapinner (allSelector { selectorTags = Nothing }), False),
(All, wrapinner allSelector, True)]
-- If we're running tests with one of the tags, we can do that, or we
-- can run with both tags, or we can run all tests.
getSuperSet wrapinner (WithTags (False, True)) =
[(WithTags (False, True),
wrapinner (allSelector { selectorTags = Nothing }), False),
(WithTags (True, True),
wrapinner (allSelector { selectorTags =
Just $! HashSet.fromList ["tag1", "tag2" ] }),
True),
(All, wrapinner allSelector, True) ]
getSuperSet wrapinner (WithTags (True, False)) =
[(WithTags (True, False),
wrapinner (allSelector { selectorTags = Nothing }), False),
(WithTags (True, True),
wrapinner (allSelector { selectorTags =
Just $! HashSet.fromList ["tag1", "tag2" ] }),
True),
(All, wrapinner allSelector, True) ]
-- If we're not running any tests, we can do anything
getSuperSet wrapinner None =
[(None, wrapinner (allSelector { selectorTags = Nothing }), False),
(WithTags (True, False),
wrapinner (allSelector { selectorTags = Just $! HashSet.singleton "tag1" }),
True),
(WithTags (False, True),
wrapinner (allSelector { selectorTags = Just $! HashSet.singleton "tag2" }),
True),
(WithTags (True, True),
wrapinner (allSelector { selectorTags =
Just $! HashSet.fromList ["tag1", "tag2" ] }),
True),
(All, wrapinner allSelector, True) ]
-- Make the tests for a group, with a starting modfilter
makeLeafGroup :: String -> (Selector -> Selector) -> ModFilter ->
([Test], [ReportEvent], State, [Selector]) ->
[([Test], [ReportEvent], State, [Selector])]
makeLeafGroup gname wrapinner mfilter initialTests =
let
mapfun :: ([Test], [ReportEvent], State, [Selector]) ->
(ModFilter, Selector, Bool) ->
([Test], [ReportEvent], State, [Selector])
mapfun (tests, events, ss @ State { stPath = oldpath }, selectors)
(mfilter, selector, valid) =
let
ssWithPath = ss { stPath = Label (Strict.pack gname) : oldpath }
(grouptests, events', ss') =
foldl (makeTestData (gname ++ "_"))
([], events, ssWithPath)
(getTests mfilter)
tests' = Group { groupName = gname, groupTests = reverse grouptests,
concurrently = True } : tests
in
if valid
then (tests', events', ss' { stPath = oldpath }, selector : selectors)
else (tests', events', ss' { stPath = oldpath }, selectors)
in
map (mapfun initialTests) (getSuperSet wrapinner mfilter)
makeOuterGroup :: ModFilter -> ([Test], [ReportEvent], State, [Selector]) ->
[([Test], [ReportEvent], State, [Selector])]
makeOuterGroup mfilter initialTests =
let
wrapOuterPath inner =
Selector { selectorInners = HashMap.singleton "Outer" inner,
selectorTags = Nothing }
mapfun :: ([Test], [ReportEvent], State, [Selector]) ->
(ModFilter, Selector, Bool) ->
[([Test], [ReportEvent], State, [Selector])]
mapfun (tests, events, ss @ State { stPath = oldpath }, selectors)
(mfilter, selector, valid) =
let
ssWithPath = ss { stPath = Label "Outer" : oldpath }
mapfun :: ([Test], [ReportEvent], State, [Selector]) ->
([Test], [ReportEvent], State, [Selector])
mapfun (innergroup : tests, events, ss, selectors) =
let
(grouptests, events', ss') = foldl (makeTestData "Outer_")
([innergroup], events, ss)
(getTests mfilter)
tests' = Group { groupName = "Outer",
groupTests = reverse grouptests,
concurrently = True } : tests
in
if valid
then (tests', events', ss' { stPath = oldpath },
selector : selectors)
else (tests', events', ss' { stPath = oldpath }, selectors)
wrapInnerPath inner =
Selector {
selectorInners =
HashMap.singleton "Outer" Selector {
selectorInners =
HashMap.singleton "Inner" inner,
selectorTags = Nothing
},
selectorTags = Nothing
}
withInner :: [([Test], [ReportEvent], State, [Selector])]
withInner = makeLeafGroup "Inner" wrapInnerPath mfilter
(tests, events, ssWithPath, selectors)
in
map mapfun withInner
in
concatMap (mapfun initialTests) (getSuperSet wrapOuterPath mfilter)
modfilters = [ All, WithTags (True, False), WithTags (False, True),
WithTags (True, True), None ]
genFilter :: Strict.Text
-> [(TestSuite, [ReportEvent],
HashMap Strict.Text (HashMap OptionMap Selector), Counts)]
genFilter sname =
let
-- Take a root ModFilter and an initial (suite list, event list,
-- selectors). We generate a stock suite, derive a selector from
-- the root ModFilter, and produce a list of possible (suite list,
-- event list, selectors)'s, one for each possibility.
suiteTestInst :: ModFilter
-> [(TestSuite, [ReportEvent],
HashMap Strict.Text (HashMap OptionMap Selector),
Counts)]
suiteTestInst mfilter =
let
-- Initial state for a filter
initState = State { stCounts = zeroCounts, stName = sname,
stPath = [], stOptions = HashMap.empty,
stOptionDescs = [] }
-- The selectors for the root set
rootSelectors :: [Selector]
rootSelectors =
case mfilter of
All -> [allSelector]
WithTags tags ->
[allSelector { selectorTags = Just $! makeTagSet tags }]
None -> []
-- Result after executing the root tests.
(rootTests, rootEvents, rootState) =
foldl (makeTestData "") ([], [StartSuiteEvent initState], initState)
(getTests mfilter)
wrapOtherPath inner =
Selector { selectorInners = HashMap.singleton "Other" inner,
selectorTags = Nothing }
-- Results after executing tests in the Other module
withOther :: [([Test], [ReportEvent], State, [Selector])]
withOther = makeLeafGroup "Other" wrapOtherPath mfilter
(rootTests, rootEvents,
rootState, rootSelectors)
finalData = concatMap (makeOuterGroup mfilter) withOther
-- Wrap up a test list, end state, and selector list into a
-- test suite and a filter. Also add the EndSuite event to
-- the events list.
buildSuite :: ([Test], [ReportEvent], State, [Selector]) ->
(TestSuite, [ReportEvent],
HashMap Strict.Text (HashMap OptionMap Selector),
Counts)
buildSuite (tests, _, _, []) =
let
suite =
TestSuite { suiteName = sname, suiteTests = reverse tests,
suiteConcurrently = True, suiteOptions = [] }
in
(suite, [], HashMap.empty, zeroCounts)
buildSuite (tests, events, state @ State { stCounts = counts },
selectors) =
let
-- Build the test suite out of the name and test list, add
-- it to the list of suites.
suite =
TestSuite { suiteName = sname, suiteTests = reverse tests,
suiteConcurrently = True, suiteOptions = [] }
-- Add an end suite event
eventsWithEnd = EndSuiteEvent state : events
-- Add an entry for this suite to the selector map
selectormap :: HashMap Strict.Text (HashMap OptionMap Selector)
selectormap =
case selectors of
[one] ->
let
optmap = HashMap.singleton HashMap.empty one
in
HashMap.singleton sname optmap
_ ->
let
combined = foldl1 combineSelectors selectors
optmap = HashMap.singleton HashMap.empty combined
in
HashMap.singleton sname optmap
in
(suite, reverse eventsWithEnd, selectormap, counts)
in
map buildSuite finalData
in
-- Create test data for this suite with all possible modfilters,
-- and add it to the existing list of test instances.
concatMap suiteTestInst modfilters
suite1Data :: [(TestSuite, [ReportEvent],
HashMap Strict.Text (HashMap OptionMap Selector), Counts)]
suite1Data = genFilter "Suite1"
suite2Data :: [(TestSuite, [ReportEvent],
HashMap Strict.Text (HashMap OptionMap Selector), Counts)]
suite2Data = genFilter "Suite2"
combineSuites :: (TestSuite, [ReportEvent],
HashMap Strict.Text (HashMap OptionMap Selector), Counts) ->
(TestSuite, [ReportEvent],
HashMap Strict.Text (HashMap OptionMap Selector), Counts) ->
([TestSuite], [ReportEvent],
HashMap Strict.Text (HashMap OptionMap Selector))
combineSuites (suite1, events1, selectormap1, Counts { cAsserts = asserts1,
cCases = cases1,
cErrors = errors1,
cFailures = failures1,
cSkipped = skipped1,
cTried = tried1 })
(suite2, events2, selectormap2, counts2) =
let
bumpCounts (EndEvent c @ Counts { cAsserts = asserts2,
cCases = cases2,
cErrors = errors2,
cFailures = failures2,
cSkipped = skipped2,
cTried = tried2 }) =
EndEvent c { cAsserts = asserts1 + asserts2,
cErrors = errors1 + errors2,
cCases = cases1 + cases2,
cFailures = failures1 + failures2,
cSkipped = skipped1 + skipped2,
cTried = tried1 + tried2 }
bumpCounts (StartSuiteEvent s @ State { stCounts =
c @ Counts { cAsserts = asserts2,
cCases = cases2,
cErrors = errors2,
cFailures = failures2,
cSkipped = skipped2,
cTried = tried2 } }) =
StartSuiteEvent s { stCounts = c { cAsserts = asserts1 + asserts2,
cErrors = errors1 + errors2,
cCases = cases1 + cases2,
cFailures = failures1 + failures2,
cSkipped = skipped1 + skipped2,
cTried = tried1 + tried2 } }
bumpCounts (EndSuiteEvent s @ State { stCounts =
c @ Counts { cAsserts = asserts2,
cCases = cases2,
cErrors = errors2,
cFailures = failures2,
cSkipped = skipped2,
cTried = tried2 } }) =
EndSuiteEvent s { stCounts = c { cAsserts = asserts1 + asserts2,
cErrors = errors1 + errors2,
cCases = cases1 + cases2,
cFailures = failures1 + failures2,
cSkipped = skipped1 + skipped2,
cTried = tried1 + tried2 } }
bumpCounts (StartCaseEvent s @ State { stCounts =
c @ Counts { cAsserts = asserts2,
cCases = cases2,
cErrors = errors2,
cFailures = failures2,
cSkipped = skipped2,
cTried = tried2 } }) =
StartCaseEvent s { stCounts = c { cAsserts = asserts1 + asserts2,
cErrors = errors1 + errors2,
cCases = cases1 + cases2,
cFailures = failures1 + failures2,
cSkipped = skipped1 + skipped2,
cTried = tried1 + tried2 } }
bumpCounts (EndCaseEvent s @ State { stCounts =
c @ Counts { cAsserts = asserts2,
cCases = cases2,
cErrors = errors2,
cFailures = failures2,
cSkipped = skipped2,
cTried = tried2 } }) =
EndCaseEvent s { stCounts = c { cAsserts = asserts1 + asserts2,
cErrors = errors1 + errors2,
cCases = cases1 + cases2,
cFailures = failures1 + failures2,
cSkipped = skipped1 + skipped2,
cTried = tried1 + tried2 } }
bumpCounts (SkipEvent s @ State { stCounts =
c @ Counts { cAsserts = asserts2,
cCases = cases2,
cErrors = errors2,
cFailures = failures2,
cSkipped = skipped2,
cTried = tried2 } }) =
SkipEvent s { stCounts = c { cAsserts = asserts1 + asserts2,
cErrors = errors1 + errors2,
cCases = cases1 + cases2,
cFailures = failures1 + failures2,
cSkipped = skipped1 + skipped2,
cTried = tried1 + tried2 } }
bumpCounts (ProgressEvent msg s @ State { stCounts =
c @ Counts { cAsserts = asserts2,
cCases = cases2,
cErrors = errors2,
cFailures = failures2,
cSkipped = skipped2,
cTried = tried2 } }) =
ProgressEvent msg s { stCounts = c { cAsserts = asserts1 + asserts2,
cErrors = errors1 + errors2,
cCases = cases1 + cases2,
cFailures = failures1 + failures2,
cSkipped = skipped1 + skipped2,
cTried = tried1 + tried2 } }
bumpCounts (FailureEvent msg s @ State { stCounts =
c @ Counts { cAsserts = asserts2,
cCases = cases2,
cErrors = errors2,
cFailures = failures2,
cSkipped = skipped2,
cTried = tried2 } }) =
FailureEvent msg s { stCounts = c { cAsserts = asserts1 + asserts2,
cErrors = errors1 + errors2,
cCases = cases1 + cases2,
cFailures = failures1 + failures2,
cSkipped = skipped1 + skipped2,
cTried = tried1 + tried2 } }
bumpCounts (ErrorEvent msg s @ State { stCounts =
c @ Counts { cAsserts = asserts2,
cCases = cases2,
cErrors = errors2,
cFailures = failures2,
cSkipped = skipped2,
cTried = tried2 } }) =
ErrorEvent msg s { stCounts = c { cAsserts = asserts1 + asserts2,
cErrors = errors1 + errors2,
cCases = cases1 + cases2,
cFailures = failures1 + failures2,
cSkipped = skipped1 + skipped2,
cTried = tried1 + tried2 } }
bumpCounts (SystemErrEvent msg s @ State { stCounts =
c @ Counts { cAsserts = asserts2,
cCases = cases2,
cErrors = errors2,
cFailures = failures2,
cSkipped = skipped2,
cTried = tried2 } }) =
SystemErrEvent msg s { stCounts = c { cAsserts = asserts1 + asserts2,
cErrors = errors1 + errors2,
cCases = cases1 + cases2,
cFailures = failures1 + failures2,
cSkipped = skipped1 + skipped2,
cTried = tried1 + tried2 } }
bumpCounts (SystemOutEvent msg s @ State { stCounts =
c @ Counts { cAsserts = asserts2,
cCases = cases2,
cErrors = errors2,
cFailures = failures2,
cSkipped = skipped2,
cTried = tried2 } }) =
SystemOutEvent msg s { stCounts = c { cAsserts = asserts1 + asserts2,
cErrors = errors1 + errors2,
cCases = cases1 + cases2,
cFailures = failures1 + failures2,
cSkipped = skipped1 + skipped2,
cTried = tried1 + tried2 } }
suites = [suite1, suite2]
events = events1 ++ map bumpCounts events2 ++
[bumpCounts (EndEvent counts2 { cCaseAsserts = 0 })]
selectormap = HashMap.union selectormap1 selectormap2
in
(suites, events, selectormap)
suiteData :: [([TestSuite], [ReportEvent],
HashMap Strict.Text (HashMap OptionMap Selector))]
suiteData = foldl (\accum suite1 ->
foldl (\accum suite2 ->
(combineSuites suite1 suite2) : accum)
accum suite2Data)
[] suite1Data
makeExecutionTest :: ([TestSuite], [ReportEvent],
HashMap Strict.Text (HashMap OptionMap Selector)) ->
(Int, [Test]) -> (Int, [Test])
makeExecutionTest (suites, expected, selectors) (index, tests) =
let
format events = intercalate "\n" (map show events)
selectorStrs =
intercalate "\n" (map (\(suite, selector) -> "[" ++ Strict.unpack suite ++
"]" ++ show selector)
(HashMap.toList selectors))
compstate State { stName = name1, stPath = path1, stCounts = counts1,
stOptionDescs = descs1 }
State { stName = name2, stPath = path2, stCounts = counts2,
stOptionDescs = descs2 } =
name1 == name2 && path1 == path2 && counts1 == counts2 && descs1 == descs2
comp (EndEvent counts1) (EndEvent counts2) = counts1 == counts2
comp (StartSuiteEvent st1) (StartSuiteEvent st2) = compstate st1 st2
comp (EndSuiteEvent st1) (EndSuiteEvent st2) = compstate st1 st2
comp (StartCaseEvent st1) (StartCaseEvent st2) = compstate st1 st2
comp (EndCaseEvent st1) (EndCaseEvent st2) = compstate st1 st2
comp (SkipEvent st1) (SkipEvent st2) = compstate st1 st2
comp (ProgressEvent msg1 st1) (ProgressEvent msg2 st2) =
msg1 == msg2 && compstate st1 st2
comp (FailureEvent msg1 st1) (FailureEvent msg2 st2) =
msg1 == msg2 && compstate st1 st2
comp (ErrorEvent msg1 st1) (ErrorEvent msg2 st2) =
msg1 == msg2 && compstate st1 st2
comp (SystemErrEvent msg1 st1) (SystemErrEvent msg2 st2) =
msg1 == msg2 && compstate st1 st2
comp (SystemOutEvent msg1 st1) (SystemOutEvent msg2 st2) =
msg1 == msg2 && compstate st1 st2
comp _ _ = False
check (e : expecteds) (a : actuals)
| comp e a = check expecteds actuals
| otherwise =
return (Finished (Fail ("Selectors\n" ++ selectorStrs ++
"\nExpected\n************************\n" ++
show e ++
"\nbut got\n************************\n" ++
show a)))
check [] [] = return (Finished Pass)
check expected [] =
return (Finished (Fail ("Missing output:\n" ++ format expected)))
check [] actual =
return (Finished (Fail ("Extra output:\n" ++ format actual)))
runTest =
do
(_, actual) <- performTestSuites fullLoggingReporter selectors suites
check expected (reverse actual)
testInstance = TestInstance { name = "execution_test_" ++ show index,
tags = [], options = [], run = runTest,
setOption = (\_ _ -> Right testInstance) }
in
(index + 1, Test testInstance : tests)
tests :: Test
tests = testGroup "Execution" (snd (foldr makeExecutionTest (0, []) suiteData))
|
emc2/HUnit-Plus
|
test/Tests/Test/HUnitPlus/Execution.hs
|
bsd-3-clause
| 31,830 | 31 | 25 | 13,502 | 7,642 | 4,285 | 3,357 | 556 | 15 |
-- |
-- Module :
-- License : BSD-Style
-- Maintainer : Nicolas DI PRIMA <[email protected]>
-- Stability : experimental
-- Portability : unknown
--
{-# LANGUAGE OverloadedStrings #-}
module Main (main) where
import Control.Monad (when)
import Data.List (intercalate)
import Network.SMTP
import System.Environment
main :: IO ()
main = do
args <- getArgs
case args of
[] -> usage (Just "need at least sender and recipient email address")
["help"] -> usage Nothing
"verify":fromStr:rcptStr:[] -> mainVerify fromStr rcptStr >>= putStrLn . prettyPrintResult " "
_ -> usage (Just $ "unrecognized options: " ++ intercalate " " args)
mainVerify :: String -> String -> IO (Result ())
mainVerify fromStr rcptStr = executeSMTP $ do
mxs <- lookupMXs (domainpart rcpt)
case mxs of
[] -> fail "no MX server for the given recipient"
(mx:_) -> do
con <- openSMTPConnection (mxAddress mx) 25 (domainpart from)
mailFrom con from
bool <- rcptTo con rcpt
when (not bool) $ fail $ "cannot send email to " ++ rcptStr
closeSMTPConnection con
where
from :: EmailAddress
from = either error id $ emailAddrFromString fromStr
rcpt :: EmailAddress
rcpt = either error id $ emailAddrFromString rcptStr
usage :: Maybe String
-> IO ()
usage mMsg = printUsage $ intercalate "\n"
[ maybe "SMTP Client Command Line interface" ((++) "Error: ") mMsg
, ""
, "available options:"
, " help: show this help message"
]
where
printUsage :: String -> IO ()
printUsage = case mMsg of
Nothing -> putStrLn
Just _ -> error
|
NicolasDP/hs-smtp
|
cli/Main.hs
|
bsd-3-clause
| 1,713 | 0 | 18 | 478 | 474 | 238 | 236 | 40 | 4 |
{-# LANGUAGE MultiParamTypeClasses #-}
module Lambda.Convertor.Expr where
import DeepControl.Applicative
import DeepControl.Monad hiding (forM, mapM)
import Lambda.DataType (Lambda)
import Lambda.DataType.Expr
import Lambda.Action
import Lambda.Convertor.PatternMatch
import Util.Pseudo
import Prelude hiding (forM, mapM)
import Data.Monoid
import Data.Foldable
import Data.Traversable
instance PseudoFunctor Expr where
pdfmap f (LAM p x msp) = LAM p (f x) msp
pdfmap f (LAMM p x msp) = LAMM p (f x) msp
pdfmap f (FIX x msp) = FIX (f x) msp
pdfmap f (APP x1 x2 msp) = APP (f x1) (f x2) msp
pdfmap f (APPSeq xs msp) = APPSeq (f |$> xs) msp
-- gadget
pdfmap f (SYN g msp) = SYN (fmap f g) msp
pdfmap f (SEN g msp) = SEN (fmap f g) msp
pdfmap f (QUT g msp) = QUT (fmap f g) msp
pdfmap f (LIST g msp) = LIST (fmap f g) msp
pdfmap f (TPL g msp) = TPL (fmap f g) msp
pdfmap f (TAG g msp) = TAG (fmap f g) msp
--
pdfmap f (THUNK t) = THUNK (f t)
pdfmap _ x = x
instance PseudoFoldable Expr where
pdfoldMap f (LAM p x _) = f x
pdfoldMap f (LAMM p x _) = f x
pdfoldMap f (FIX x _) = f x
pdfoldMap f (APP x1 x2 _) = f x1 <> f x2
pdfoldMap f (APPSeq xs _) = fold $ f |$> xs
-- gadget
pdfoldMap f (SYN g _) = foldMap f g
pdfoldMap f (SEN g _) = foldMap f g
pdfoldMap f (QUT g _) = foldMap f g
pdfoldMap f (LIST g _) = foldMap f g
pdfoldMap f (TPL g _) = foldMap f g
pdfoldMap f (TAG g _) = foldMap f g
--
pdfoldMap f (THUNK t) = f t
pdfoldMap f x = f x
instance PseudoTraversable Lambda Expr where
pdmapM f (LAM p x msp) = localMSPBy msp $ LAM p |$> localLAMPush p (f x) |* msp
pdmapM f (LAMM p x msp) = localMSPBy msp $ LAMM p |$> localLAMPush p (f x) |* msp
pdmapM f (FIX x msp) = localMSPBy msp $ FIX |$> f x |* msp
pdmapM f (APP x1 x2 msp) = localMSPBy msp $ APP |$> f x1 |*> f x2 |* msp
pdmapM f (APPSeq xs msp) = localMSPBy msp $ APPSeq |$> mapM f xs |* msp
-- gadget
pdmapM f (SYN g msp) = localMSPBy msp $ SYN |$> mapM f g |* msp
pdmapM f (SEN g msp) = localMSPBy msp $ SEN |$> mapM f g |* msp
pdmapM f (QUT g msp) = localMSPBy msp $ QUT |$> mapM f g |* msp
pdmapM f (LIST g msp) = localMSPBy msp $ LIST |$> mapM f g |* msp
pdmapM f (TPL g msp) = localMSPBy msp $ TPL |$> mapM f g |* msp
pdmapM f (TAG g msp) = localMSPBy msp $ TAG |$> mapM f g |* msp
--
pdmapM f (THUNK t) = THUNK |$> f t
pdmapM _ x = (*:) x
|
ocean0yohsuke/Simply-Typed-Lambda
|
src/Lambda/Convertor/Expr.hs
|
bsd-3-clause
| 2,635 | 0 | 10 | 839 | 1,279 | 630 | 649 | 55 | 0 |
module Parser.ParseModule
(parseModule)
where
import Parser.Parse
import Parser.Syntax
import Parser.ParseSpace
import Parser.ParseDec
import Parser.ParseIdent
parseImportSome :: Parse Char ImportTermination
parseImportSome = fmap ImportSome $ ksingleOrParenthesized parseLocalIdent
parseImportAll :: Parse Char ImportTermination
parseImportAll = lit '*' >> return ImportAll
parseImportTermination :: Parse Char ImportTermination
parseImportTermination = parseEither parseImportSome parseImportAll
parseImportPath :: Parse Char ImportPath
parseImportPath = greedy $ do
initPath <- many $ do
name <- parseLocalIdent
optional kspace
lits "::"
optional kspace
return name
term <- parseImportTermination
return $ ImportPath initPath term
parseImport :: Parse Char ImportPath
parseImport = greedy $ do
lits "import"
kspace
path <- parseImportPath
ksemicolon
return path
parseModule :: Parse Char Module
parseModule = greedy $ do
optional kspace
toImport <- many $ do -- not named "imports" because ST2 highlights that weirdly...
path <- parseImport
optional kspace
return path
decs <- many $ do
dec <- parseDec
optional kspace
return dec
return $ Module toImport decs
|
Kiwi-Labs/kwirc
|
kwick/parser/ParseModule.hs
|
mit
| 1,205 | 2 | 12 | 193 | 330 | 152 | 178 | 42 | 1 |
{-# LANGUAGE DeriveGeneric #-}
module Course where
import qualified Data.Text as T
import Data.Aeson
import GHC.Generics
data Course = Course !T.Text deriving (Show, Generic)
instance FromJSON Course
|
ksaveljev/udemy-downloader
|
Course.hs
|
mit
| 204 | 0 | 8 | 31 | 53 | 31 | 22 | 9 | 0 |
{-# language TypeSynonymInstances, FlexibleInstances, MultiParamTypeClasses #-}
module Binpack.Interface where
import Binpack.Instance
import Binpack.Example
import qualified Binpack.Param as P
import Binpack.Quiz
import Binpack.Approximation
import Binpack.InstanceTH ()
import Autolib.FiniteMap
import Autolib.Set
import Challenger.Partial
import Autolib.ToDoc
import Autolib.Reporter
import Autolib.Util.Zufall
import Inter.Types
import Inter.Quiz
import Data.List ( sort )
import LCS.Code ( is_embedded_in )
instance OrderScore Binpack where
scoringOrder _ = Increasing
instance Partial Binpack Instance Assignment where
describe _ i = toDoc i
initial _ i = eltsFM $ addListToFM_C (++) emptyFM $ zip
( concat $ repeat [ 1 .. bins i ] )
( map return $ weights i )
partial _ i b = do
when ( length b > bins i ) $ reject $ vcat
[ text "zu viele Behälter benutzt"
]
sequence_ $ do
bin <- b
return $ do
let t = sum bin
inform $ vcat
[ text "Behälter"
, nest 4 $ vcat
[ text "Gegenstände:" <+> toDoc bin
, text "Summe:" <+> toDoc t
]
]
when ( t > capacity i ) $ reject $ text "zu groß"
total _ i b = do
let todo = sort $ weights i
done = sort $ concat b
when ( todo /= done ) $ reject $ vcat
[ text "nicht alle oder nicht die richtigen Gewichte verpackt:"
, text "gegeben waren :" <+> toDoc todo
, text "Sie benutzen :" <+> toDoc done
]
instance Verify Binpack Instance where
verify _ i = do
let small = filter (<= 0) $ weights i
when ( not $ null small ) $ reject $ vcat
[ text "Gewichte nicht positiv:"
, toDoc small
]
let large = filter ( > capacity i ) $ weights i
when ( not $ null large ) $ reject $ vcat
[ text "Gewichte größer als Kapazität:"
, toDoc large
]
let totalweight = sum $ weights i
totalcap = fromIntegral ( bins i ) * capacity i
inform $ vcat
[ text "Gesamtgewicht " <+> toDoc totalweight
, text "Gesamtkapazität" <+> toDoc totalcap
]
when ( totalweight > totalcap ) $ reject $ text "paßt nicht"
used_bins :: Assignment -> Int
used_bins b = length b
instance Measure Binpack Instance Assignment where
measure _ i b = fromIntegral $ used_bins b
make_fixed :: Make
make_fixed = direct Binpack Binpack.Example.e1
instance Generator Binpack P.Param Instance where
generator p conf key = generate_with_distance 1 conf
generate_with_distance d conf =
do ws <- pick conf
return $ Instance { capacity = P.capacity conf
, bins = P.bins conf
, weights = ws
}
`repeat_until` \ i -> first_fit_decreasing_size i >= d + bins i
instance Project Binpack Instance Instance where
project p i = i
make_quiz :: Make
make_quiz = quiz Binpack P.example
|
florianpilz/autotool
|
src/Binpack/Interface.hs
|
gpl-2.0
| 3,351 | 0 | 21 | 1,248 | 931 | 459 | 472 | 79 | 1 |
{- |
Module : ./CASL/ToSExpr.hs
Description : translate CASL to S-Expressions
Copyright : (c) C. Maeder, DFKI 2008
License : GPLv2 or higher, see LICENSE.txt
Maintainer : [email protected]
Stability : provisional
Portability : portable
translation of CASL to S-Expressions
-}
module CASL.ToSExpr where
import CASL.Fold
import CASL.Morphism
import CASL.Sign
import CASL.AS_Basic_CASL
import CASL.Quantification
import Common.SExpr
import Common.Result
import Common.Id
import qualified Common.Lib.MapSet as MapSet
import Data.Function
import qualified Data.Map as Map
import qualified Data.Set as Set
import qualified Data.List as List
predToSSymbol :: Sign f e -> PRED_SYMB -> SExpr
predToSSymbol sign p = case p of
Pred_name _ -> error "predToSSymbol"
Qual_pred_name i t _ -> predIdToSSymbol sign i $ toPredType t
predIdToSSymbol :: Sign f e -> Id -> PredType -> SExpr
predIdToSSymbol sign i t =
case List.elemIndex t . Set.toList . MapSet.lookup i $ predMap sign of
Nothing -> error "predIdToSSymbol"
Just n -> idToSSymbol (n + 1) i
opToSSymbol :: Sign f e -> OP_SYMB -> SExpr
opToSSymbol sign o = case o of
Op_name _ -> error "opToSSymbol"
Qual_op_name i t _ -> opIdToSSymbol sign i $ toOpType t
opIdToSSymbol :: Sign f e -> Id -> OpType -> SExpr
opIdToSSymbol sign i t = case List.findIndex
(on (==) opSorts t) . Set.toList
. MapSet.lookup i $ opMap sign of
Nothing -> error $ "opIdToSSymbol " ++ show i
Just n -> idToSSymbol (n + 1) i
sortToSSymbol :: Id -> SExpr
sortToSSymbol = idToSSymbol 0
varToSSymbol :: Token -> SExpr
varToSSymbol = SSymbol . transToken
varDeclToSExpr :: (VAR, SORT) -> SExpr
varDeclToSExpr (v, s) =
SList [SSymbol "vardecl-indet", varToSSymbol v, sortToSSymbol s]
sfail :: String -> Range -> a
sfail s = error . show . Diag Error ("unexpected " ++ s)
sRec :: GetRange f => Sign a e -> (f -> SExpr) -> Record f SExpr SExpr
sRec sign mf = Record
{ foldQuantification = \ _ q vs f _ ->
let s = SSymbol $ case q of
Universal -> "all"
Existential -> "ex"
Unique_existential -> "ex1"
vl = SList $ map varDeclToSExpr $ flatVAR_DECLs vs
in SList [s, vl, f]
, foldJunction = \ _ j fs _ -> SList $ SSymbol (case j of
Con -> "and"
Dis -> "or") : fs
, foldRelation = \ _ f1 c f2 _ -> SList
[ SSymbol (if c == Equivalence then "equiv" else "implies"), f1, f2]
, foldNegation = \ _ f _ -> SList [SSymbol "not", f]
, foldAtom = \ _ b _ -> SSymbol $ if b then "true" else "false"
, foldPredication = \ _ p ts _ ->
SList $ SSymbol "papply" : predToSSymbol sign p : ts
, foldDefinedness = \ _ t _ -> SList [SSymbol "def", t]
, foldEquation = \ _ t1 e t2 _ -> SList
[ SSymbol $ if e == Existl then "eeq" else "eq", t1, t2]
, foldMembership = \ _ t s _ ->
SList [SSymbol "member", t, sortToSSymbol s]
, foldMixfix_formula = \ t _ -> sfail "Mixfix_formula" $ getRange t
, foldSort_gen_ax = \ _ cs b ->
let (srts, ops, _) = recover_Sort_gen_ax cs in
SList $ SSymbol ((if b then "freely-" else "") ++ "generated")
: (case srts of
[s] -> sortToSSymbol s
_ -> SList $ map sortToSSymbol srts)
: map (opToSSymbol sign) ops
, foldQuantOp = \ _ o _ _ -> sfail ("QuantOp " ++ show o) $ getRange o
, foldQuantPred = \ _ p _ _ -> sfail ("QuantPred " ++ show p) $ getRange p
, foldExtFORMULA = const mf
, foldQual_var = \ _ v _ _ ->
SList [SSymbol "varterm", varToSSymbol v]
, foldApplication = \ _ o ts _ ->
SList $ SSymbol "fapply" : opToSSymbol sign o : ts
, foldSorted_term = \ _ r _ _ -> r
, foldCast = \ _ t s _ -> SList [SSymbol "cast", t, sortToSSymbol s]
, foldConditional = \ _ e f t _ -> SList [SSymbol "condition", e, f, t]
, foldMixfix_qual_pred = \ _ -> sfail "Mixfix_qual_pred" . getRange
, foldMixfix_term = \ t _ -> sfail "Mixfix_term" $ getRange t
, foldMixfix_token = \ _ -> sfail "Mixfix_token" . tokPos
, foldMixfix_sorted_term = \ _ _ -> sfail "Mixfix_sorted_term"
, foldMixfix_cast = \ _ _ -> sfail "Mixfix_cast"
, foldMixfix_parenthesized = \ _ _ -> sfail "Mixfix_parenthesized"
, foldMixfix_bracketed = \ _ _ -> sfail "Mixfix_bracketed"
, foldMixfix_braced = \ _ _ -> sfail "Mixfix_braced"
, foldExtTERM = const mf }
signToSExprs :: Sign a e -> [SExpr]
signToSExprs sign = sortSignToSExprs sign
: predMapToSExprs sign (predMap sign) ++ opMapToSExprs sign (opMap sign)
sortSignToSExprs :: Sign a e -> SExpr
sortSignToSExprs sign =
SList (SSymbol "sorts"
: map sortToSSymbol (Set.toList $ sortSet sign))
predMapToSExprs :: Sign a e -> PredMap -> [SExpr]
predMapToSExprs sign =
map (\ (p, t) ->
SList [ SSymbol "predicate"
, predIdToSSymbol sign p t
, SList $ map sortToSSymbol $ predArgs t ])
. mapSetToList
opMapToSExprs :: Sign a e -> OpMap -> [SExpr]
opMapToSExprs sign =
map (\ (p, t) ->
SList [ SSymbol "function"
, opIdToSSymbol sign p t
, SList $ map sortToSSymbol $ opArgs t
, sortToSSymbol $ opRes t ])
. mapSetToList
morToSExprs :: Morphism f e m -> [SExpr]
morToSExprs m =
let src = msource m
tar = mtarget m
sm = sort_map m
in map (\ (s, t) -> SList [SSymbol "map", sortToSSymbol s, sortToSSymbol t])
(Map.toList sm)
++ Map.foldWithKey (\ i s -> case Set.toList s of
[] -> id
ot : _ -> let (j, nt) = mapOpSym sm (op_map m) (i, ot) in
if i == j then id else
(SList [ SSymbol "map", opIdToSSymbol src i ot
, opIdToSSymbol tar j nt] :)) []
(MapSet.toMap $ opMap src)
++ Map.foldWithKey (\ i s -> case Set.toList s of
[] -> id
ot : _ -> let (j, nt) = mapPredSym sm (pred_map m) (i, ot) in
if i == j then id else
(SList [ SSymbol "map", predIdToSSymbol src i ot
, predIdToSSymbol tar j nt] :)) []
(MapSet.toMap $ predMap src)
|
spechub/Hets
|
CASL/ToSExpr.hs
|
gpl-2.0
| 6,159 | 0 | 21 | 1,720 | 2,211 | 1,156 | 1,055 | 135 | 9 |
{- |
Module : ./TPTP/Prover/EProver/ProofParser.hs
Description : Parses an EProver proof.
Copyright : (c) Eugen Kuksa University of Magdeburg 2017
License : GPLv2 or higher, see LICENSE.txt
Maintainer : Eugen Kuksa <[email protected]>
Stability : provisional
Portability : non-portable (imports Logic)
-}
module TPTP.Prover.EProver.ProofParser (parseTimeUsed) where
import Data.Char
import Data.List
-- Find the "CPU Time" line and parse the time
parseTimeUsed :: [String] -> Int
parseTimeUsed = fst . foldl' checkLine (-1, False)
where
checkLine :: (Int, Bool) -> String -> (Int, Bool)
checkLine (time, found) line =
if found
then (time, found)
else if "CPU Time" `isPrefixOf` dropWhile (`elem` "%# ") line
then let time' = case takeWhile isDigit $ last (words line) of
ds@(_ : _) -> read ds
_ -> time
in (time', found)
else (time, found)
|
spechub/Hets
|
TPTP/Prover/EProver/ProofParser.hs
|
gpl-2.0
| 980 | 0 | 18 | 266 | 209 | 121 | 88 | 15 | 4 |
module NGramCrackers.Ops.String
( bigrams
, trigrams
, getNGramsFromString
, getNGramsFromList
, getAlphasOnlyToString
, getWordFrequency
) where
import Data.Char (isAlphaNum, toLower)
import NGramCrackers.NGramCrackers
import NGramCrackers.Utilities.List
{-| Extract bigrams from a string -}
bigrams :: String -> [String]
bigrams = getNGramsFromString 2
{-| Extract trigrams from a string -}
trigrams :: String -> [String]
trigrams = getNGramsFromString 3
{-| Extract n-grams from a string -}
getNGramsFromString :: Int -> String -> [String]
getNGramsFromString n wordString
| n < 0 = error "n must be a positive integer less than 7"
| n > 7 = error "n must be a positive integer less than 7"
| otherwise = map unwords $ getNGramsFromList n wordList
where wordList = getAlphasOnlyToList wordString
{-| Return only alphabetic characters from a string and return the
result as a string. Output of this function may need processing
into a list, tuple, etc. -}
getAlphasOnlyToString :: String -> String
getAlphasOnlyToString = unwords . map (filter isAlphaNum) . words
{-| Return only alphanumeric characters from a string and return the
result as a List.-}
getAlphasOnlyToList :: String -> [String]
getAlphasOnlyToList = map (filter isAlphaNum) . words . map toLower
{-| Get frequency of a single word's occurance in a string. Is eta-reduction
the easiest reading way to do this function? The arguments are fairly
instructive. However, the type declaration does say what kind of args
it takes. With type synonyms or further exploring the type system,
the declaration would be more informative-}
getWordFrequency:: String -> String -> Int
getWordFrequency word text = (length . filter (== word) . words) text
|
R-Morgan/NGramCrackers
|
testsuite/NGramCrackers/Ops/String.hs
|
agpl-3.0
| 1,788 | 0 | 10 | 342 | 295 | 159 | 136 | 26 | 1 |
-- |
-- Module : Example.Time.Compat
-- License : BSD-style
-- Maintainer : Nicolas DI PRIMA <[email protected]>
--
-- This file is an example on how to use the Data.Hourglass.Compat
-- module to transpose a ZonedTime (from time) into a LocalTime of DateTime
-- (from hourglass).
--
module Example.Time.Compat
( transpose
) where
import Data.Hourglass as H
import Data.Hourglass.Compat as C
import Data.Time as T
transpose :: T.ZonedTime
-> H.LocalTime H.DateTime
transpose oldTime =
H.localTime
offsetTime
(H.DateTime newDate timeofday)
where
(T.ZonedTime (T.LocalTime day tod) (T.TimeZone tzmin _ _)) = oldTime
newDate :: H.Date
newDate = C.dateFromTAIEpoch $ T.toModifiedJulianDay day
timeofday :: H.TimeOfDay
timeofday = C.diffTimeToTimeOfDay $ toRational $ T.timeOfDayToTime tod
offsetTime = H.TimezoneOffset $ fromIntegral tzmin
|
ppelleti/hs-hourglass
|
Example/Time/Compat.hs
|
bsd-3-clause
| 935 | 0 | 11 | 214 | 190 | 107 | 83 | 17 | 1 |
{- ------------------------------------------------------------------------
(c) The GHC Team, 1992-2012
DeriveConstants is a program that extracts information from the C
declarations in the header files (primarily struct field offsets)
and generates various files, such as a header file that can be #included
into non-C source containing this information.
------------------------------------------------------------------------ -}
import Control.Monad
import Data.Bits
import Data.Char
import Data.List
import Data.Map (Map)
import qualified Data.Map as Map
import Data.Maybe
import Numeric
import System.Environment
import System.Exit
import System.FilePath
import System.IO
import System.Info
import System.Process
main :: IO ()
main = do opts <- parseArgs
let getOption descr opt = case opt opts of
Just x -> return x
Nothing -> die ("No " ++ descr ++ " given")
mode <- getOption "mode" o_mode
fn <- getOption "output filename" o_outputFilename
case mode of
Gen_Haskell_Type -> writeHaskellType fn haskellWanteds
Gen_Haskell_Wrappers -> writeHaskellWrappers fn haskellWanteds
Gen_Haskell_Exports -> writeHaskellExports fn haskellWanteds
Gen_Computed cm ->
do tmpdir <- getOption "tmpdir" o_tmpdir
gccProg <- getOption "gcc program" o_gccProg
nmProg <- getOption "nm program" o_nmProg
let verbose = o_verbose opts
gccFlags = o_gccFlags opts
rs <- getWanted verbose tmpdir gccProg gccFlags nmProg
let haskellRs = [ what
| (wh, what) <- rs
, wh `elem` [Haskell, Both] ]
cRs = [ what
| (wh, what) <- rs
, wh `elem` [C, Both] ]
case cm of
ComputeHaskell -> writeHaskellValue fn haskellRs
ComputeHeader -> writeHeader fn cRs
where haskellWanteds = [ what | (wh, what) <- wanteds,
wh `elem` [Haskell, Both] ]
data Options = Options {
o_verbose :: Bool,
o_mode :: Maybe Mode,
o_tmpdir :: Maybe FilePath,
o_outputFilename :: Maybe FilePath,
o_gccProg :: Maybe FilePath,
o_gccFlags :: [String],
o_nmProg :: Maybe FilePath
}
parseArgs :: IO Options
parseArgs = do args <- getArgs
opts <- f emptyOptions args
return (opts {o_gccFlags = reverse (o_gccFlags opts)})
where emptyOptions = Options {
o_verbose = False,
o_mode = Nothing,
o_tmpdir = Nothing,
o_outputFilename = Nothing,
o_gccProg = Nothing,
o_gccFlags = [],
o_nmProg = Nothing
}
f opts [] = return opts
f opts ("-v" : args')
= f (opts {o_verbose = True}) args'
f opts ("--gen-haskell-type" : args')
= f (opts {o_mode = Just Gen_Haskell_Type}) args'
f opts ("--gen-haskell-value" : args')
= f (opts {o_mode = Just (Gen_Computed ComputeHaskell)}) args'
f opts ("--gen-haskell-wrappers" : args')
= f (opts {o_mode = Just Gen_Haskell_Wrappers}) args'
f opts ("--gen-haskell-exports" : args')
= f (opts {o_mode = Just Gen_Haskell_Exports}) args'
f opts ("--gen-header" : args')
= f (opts {o_mode = Just (Gen_Computed ComputeHeader)}) args'
f opts ("--tmpdir" : dir : args')
= f (opts {o_tmpdir = Just dir}) args'
f opts ("-o" : fn : args')
= f (opts {o_outputFilename = Just fn}) args'
f opts ("--gcc-program" : prog : args')
= f (opts {o_gccProg = Just prog}) args'
f opts ("--gcc-flag" : flag : args')
= f (opts {o_gccFlags = flag : o_gccFlags opts}) args'
f opts ("--nm-program" : prog : args')
= f (opts {o_nmProg = Just prog}) args'
f _ (flag : _) = die ("Unrecognised flag: " ++ show flag)
data Mode = Gen_Haskell_Type
| Gen_Haskell_Wrappers
| Gen_Haskell_Exports
| Gen_Computed ComputeMode
data ComputeMode = ComputeHaskell | ComputeHeader
type Wanteds = [(Where, What Fst)]
type Results = [(Where, What Snd)]
type Name = String
newtype CExpr = CExpr String
newtype CPPExpr = CPPExpr String
data What f = GetFieldType Name (f CExpr Integer)
| GetClosureSize Name (f CExpr Integer)
| GetWord Name (f CExpr Integer)
| GetInt Name (f CExpr Integer)
| GetNatural Name (f CExpr Integer)
| GetBool Name (f CPPExpr Bool)
| StructFieldMacro Name
| ClosureFieldMacro Name
| ClosurePayloadMacro Name
| FieldTypeGcptrMacro Name
data Fst a b = Fst a
data Snd a b = Snd b
data Where = C | Haskell | Both
deriving Eq
constantInt :: Where -> Name -> String -> Wanteds
constantInt w name expr = [(w, GetInt name (Fst (CExpr expr)))]
constantWord :: Where -> Name -> String -> Wanteds
constantWord w name expr = [(w, GetWord name (Fst (CExpr expr)))]
constantNatural :: Where -> Name -> String -> Wanteds
constantNatural w name expr = [(w, GetNatural name (Fst (CExpr expr)))]
constantBool :: Where -> Name -> String -> Wanteds
constantBool w name expr = [(w, GetBool name (Fst (CPPExpr expr)))]
fieldOffset :: Where -> String -> String -> Wanteds
fieldOffset w theType theField = fieldOffset_ w nameBase theType theField
where nameBase = theType ++ "_" ++ theField
fieldOffset_ :: Where -> Name -> String -> String -> Wanteds
fieldOffset_ w nameBase theType theField = [(w, GetWord name (Fst (CExpr expr)))]
where name = "OFFSET_" ++ nameBase
expr = "offsetof(" ++ theType ++ ", " ++ theField ++ ")"
-- FieldType is for defining REP_x to be b32 etc
-- These are both the C-- types used in a load
-- e.g. b32[addr]
-- and the names of the CmmTypes in the compiler
-- b32 :: CmmType
fieldType' :: Where -> String -> String -> Wanteds
fieldType' w theType theField
= fieldType_' w nameBase theType theField
where nameBase = theType ++ "_" ++ theField
fieldType_' :: Where -> Name -> String -> String -> Wanteds
fieldType_' w nameBase theType theField
= [(w, GetFieldType name (Fst (CExpr expr)))]
where name = "REP_" ++ nameBase
expr = "FIELD_SIZE(" ++ theType ++ ", " ++ theField ++ ")"
structField :: Where -> String -> String -> Wanteds
structField = structFieldHelper C
structFieldH :: Where -> String -> String -> Wanteds
structFieldH w = structFieldHelper w w
structField_ :: Where -> Name -> String -> String -> Wanteds
structField_ w nameBase theType theField
= fieldOffset_ w nameBase theType theField
++ fieldType_' C nameBase theType theField
++ structFieldMacro nameBase
structFieldMacro :: Name -> Wanteds
structFieldMacro nameBase = [(C, StructFieldMacro nameBase)]
-- Outputs the byte offset and MachRep for a field
structFieldHelper :: Where -> Where -> String -> String -> Wanteds
structFieldHelper wFT w theType theField = fieldOffset w theType theField
++ fieldType' wFT theType theField
++ structFieldMacro nameBase
where nameBase = theType ++ "_" ++ theField
closureFieldMacro :: Name -> Wanteds
closureFieldMacro nameBase = [(C, ClosureFieldMacro nameBase)]
closurePayload :: Where -> String -> String -> Wanteds
closurePayload w theType theField
= closureFieldOffset_ w nameBase theType theField
++ closurePayloadMacro nameBase
where nameBase = theType ++ "_" ++ theField
closurePayloadMacro :: Name -> Wanteds
closurePayloadMacro nameBase = [(C, ClosurePayloadMacro nameBase)]
-- Byte offset and MachRep for a closure field, minus the header
closureField_ :: Where -> Name -> String -> String -> Wanteds
closureField_ w nameBase theType theField
= closureFieldOffset_ w nameBase theType theField
++ fieldType_' C nameBase theType theField
++ closureFieldMacro nameBase
closureField :: Where -> String -> String -> Wanteds
closureField w theType theField = closureField_ w nameBase theType theField
where nameBase = theType ++ "_" ++ theField
closureFieldOffset_ :: Where -> Name -> String -> String -> Wanteds
closureFieldOffset_ w nameBase theType theField
= defOffset w nameBase (CExpr ("offsetof(" ++ theType ++ ", " ++ theField ++ ") - TYPE_SIZE(StgHeader)"))
-- Size of a closure type, minus the header, named SIZEOF_<type>_NoHdr
-- Also, we #define SIZEOF_<type> to be the size of the whole closure for .cmm.
closureSize :: Where -> String -> Wanteds
closureSize w theType = defSize w (theType ++ "_NoHdr") (CExpr expr)
++ defClosureSize C theType (CExpr expr)
where expr = "TYPE_SIZE(" ++ theType ++ ") - TYPE_SIZE(StgHeader)"
-- Byte offset and MachRep for a closure field, minus the header
closureFieldGcptr :: Where -> String -> String -> Wanteds
closureFieldGcptr w theType theField
= closureFieldOffset_ w nameBase theType theField
++ fieldTypeGcptr nameBase
++ closureFieldMacro nameBase
where nameBase = theType ++ "_" ++ theField
fieldTypeGcptr :: Name -> Wanteds
fieldTypeGcptr nameBase = [(C, FieldTypeGcptrMacro nameBase)]
closureFieldOffset :: Where -> String -> String -> Wanteds
closureFieldOffset w theType theField
= defOffset w nameBase (CExpr expr)
where nameBase = theType ++ "_" ++ theField
expr = "offsetof(" ++ theType ++ ", " ++ theField ++ ") - TYPE_SIZE(StgHeader)"
thunkSize :: Where -> String -> Wanteds
thunkSize w theType
= defSize w (theType ++ "_NoThunkHdr") (CExpr expr)
++ closureSize w theType
where expr = "TYPE_SIZE(" ++ theType ++ ") - TYPE_SIZE(StgThunkHeader)"
defIntOffset :: Where -> Name -> String -> Wanteds
defIntOffset w nameBase cExpr = [(w, GetInt ("OFFSET_" ++ nameBase) (Fst (CExpr cExpr)))]
defOffset :: Where -> Name -> CExpr -> Wanteds
defOffset w nameBase cExpr = [(w, GetWord ("OFFSET_" ++ nameBase) (Fst cExpr))]
structSize :: Where -> String -> Wanteds
structSize w theType = defSize w theType (CExpr ("TYPE_SIZE(" ++ theType ++ ")"))
defSize :: Where -> Name -> CExpr -> Wanteds
defSize w nameBase cExpr = [(w, GetWord ("SIZEOF_" ++ nameBase) (Fst cExpr))]
defClosureSize :: Where -> Name -> CExpr -> Wanteds
defClosureSize w nameBase cExpr = [(w, GetClosureSize ("SIZEOF_" ++ nameBase) (Fst cExpr))]
haskellise :: Name -> Name
haskellise (c : cs) = toLower c : cs
haskellise "" = ""
wanteds :: Wanteds
wanteds = concat
[-- Closure header sizes.
constantWord Both "STD_HDR_SIZE"
-- grrr.. PROFILING is on so we need to
-- subtract sizeofW(StgProfHeader)
"sizeofW(StgHeader) - sizeofW(StgProfHeader)"
,constantWord Both "PROF_HDR_SIZE" "sizeofW(StgProfHeader)"
-- Size of a storage manager block (in bytes).
,constantWord Both "BLOCK_SIZE" "BLOCK_SIZE"
,constantWord C "MBLOCK_SIZE" "MBLOCK_SIZE"
-- blocks that fit in an MBlock, leaving space for the block
-- descriptors
,constantWord Both "BLOCKS_PER_MBLOCK" "BLOCKS_PER_MBLOCK"
-- could be derived, but better to save doing the calculation twice
,fieldOffset Both "StgRegTable" "rR1"
,fieldOffset Both "StgRegTable" "rR2"
,fieldOffset Both "StgRegTable" "rR3"
,fieldOffset Both "StgRegTable" "rR4"
,fieldOffset Both "StgRegTable" "rR5"
,fieldOffset Both "StgRegTable" "rR6"
,fieldOffset Both "StgRegTable" "rR7"
,fieldOffset Both "StgRegTable" "rR8"
,fieldOffset Both "StgRegTable" "rR9"
,fieldOffset Both "StgRegTable" "rR10"
,fieldOffset Both "StgRegTable" "rF1"
,fieldOffset Both "StgRegTable" "rF2"
,fieldOffset Both "StgRegTable" "rF3"
,fieldOffset Both "StgRegTable" "rF4"
,fieldOffset Both "StgRegTable" "rF5"
,fieldOffset Both "StgRegTable" "rF6"
,fieldOffset Both "StgRegTable" "rD1"
,fieldOffset Both "StgRegTable" "rD2"
,fieldOffset Both "StgRegTable" "rD3"
,fieldOffset Both "StgRegTable" "rD4"
,fieldOffset Both "StgRegTable" "rD5"
,fieldOffset Both "StgRegTable" "rD6"
,fieldOffset Both "StgRegTable" "rXMM1"
,fieldOffset Both "StgRegTable" "rXMM2"
,fieldOffset Both "StgRegTable" "rXMM3"
,fieldOffset Both "StgRegTable" "rXMM4"
,fieldOffset Both "StgRegTable" "rXMM5"
,fieldOffset Both "StgRegTable" "rXMM6"
,fieldOffset Both "StgRegTable" "rYMM1"
,fieldOffset Both "StgRegTable" "rYMM2"
,fieldOffset Both "StgRegTable" "rYMM3"
,fieldOffset Both "StgRegTable" "rYMM4"
,fieldOffset Both "StgRegTable" "rYMM5"
,fieldOffset Both "StgRegTable" "rYMM6"
,fieldOffset Both "StgRegTable" "rZMM1"
,fieldOffset Both "StgRegTable" "rZMM2"
,fieldOffset Both "StgRegTable" "rZMM3"
,fieldOffset Both "StgRegTable" "rZMM4"
,fieldOffset Both "StgRegTable" "rZMM5"
,fieldOffset Both "StgRegTable" "rZMM6"
,fieldOffset Both "StgRegTable" "rL1"
,fieldOffset Both "StgRegTable" "rSp"
,fieldOffset Both "StgRegTable" "rSpLim"
,fieldOffset Both "StgRegTable" "rHp"
,fieldOffset Both "StgRegTable" "rHpLim"
,fieldOffset Both "StgRegTable" "rCCCS"
,fieldOffset Both "StgRegTable" "rCurrentTSO"
,fieldOffset Both "StgRegTable" "rCurrentNursery"
,fieldOffset Both "StgRegTable" "rHpAlloc"
,structField C "StgRegTable" "rRet"
,structField C "StgRegTable" "rNursery"
,defIntOffset Both "stgEagerBlackholeInfo"
"FUN_OFFSET(stgEagerBlackholeInfo)"
,defIntOffset Both "stgGCEnter1" "FUN_OFFSET(stgGCEnter1)"
,defIntOffset Both "stgGCFun" "FUN_OFFSET(stgGCFun)"
,fieldOffset Both "Capability" "r"
,fieldOffset C "Capability" "lock"
,structField C "Capability" "no"
,structField C "Capability" "mut_lists"
,structField C "Capability" "context_switch"
,structField C "Capability" "interrupt"
,structField C "Capability" "sparks"
,structField Both "bdescr" "start"
,structField Both "bdescr" "free"
,structField Both "bdescr" "blocks"
,structField C "bdescr" "gen_no"
,structField C "bdescr" "link"
,structSize C "generation"
,structField C "generation" "n_new_large_words"
,structField C "generation" "weak_ptr_list"
,structSize Both "CostCentreStack"
,structField C "CostCentreStack" "ccsID"
,structFieldH Both "CostCentreStack" "mem_alloc"
,structFieldH Both "CostCentreStack" "scc_count"
,structField C "CostCentreStack" "prevStack"
,structField C "CostCentre" "ccID"
,structField C "CostCentre" "link"
,structField C "StgHeader" "info"
,structField_ Both "StgHeader_ccs" "StgHeader" "prof.ccs"
,structField_ Both "StgHeader_ldvw" "StgHeader" "prof.hp.ldvw"
,structSize Both "StgSMPThunkHeader"
,closurePayload C "StgClosure" "payload"
,structFieldH Both "StgEntCounter" "allocs"
,structFieldH Both "StgEntCounter" "allocd"
,structField Both "StgEntCounter" "registeredp"
,structField Both "StgEntCounter" "link"
,structField Both "StgEntCounter" "entry_count"
,closureSize Both "StgUpdateFrame"
,closureSize C "StgCatchFrame"
,closureSize C "StgStopFrame"
,closureSize Both "StgMutArrPtrs"
,closureField Both "StgMutArrPtrs" "ptrs"
,closureField Both "StgMutArrPtrs" "size"
,closureSize Both "StgArrWords"
,closureField C "StgArrWords" "bytes"
,closurePayload C "StgArrWords" "payload"
,closureField C "StgTSO" "_link"
,closureField C "StgTSO" "global_link"
,closureField C "StgTSO" "what_next"
,closureField C "StgTSO" "why_blocked"
,closureField C "StgTSO" "block_info"
,closureField C "StgTSO" "blocked_exceptions"
,closureField C "StgTSO" "id"
,closureField C "StgTSO" "cap"
,closureField C "StgTSO" "saved_errno"
,closureField C "StgTSO" "trec"
,closureField C "StgTSO" "flags"
,closureField C "StgTSO" "dirty"
,closureField C "StgTSO" "bq"
,closureField_ Both "StgTSO_cccs" "StgTSO" "prof.cccs"
,closureField Both "StgTSO" "stackobj"
,closureField Both "StgStack" "sp"
,closureFieldOffset Both "StgStack" "stack"
,closureField C "StgStack" "stack_size"
,closureField C "StgStack" "dirty"
,structSize C "StgTSOProfInfo"
,closureField Both "StgUpdateFrame" "updatee"
,closureField C "StgCatchFrame" "handler"
,closureField C "StgCatchFrame" "exceptions_blocked"
,closureSize C "StgPAP"
,closureField C "StgPAP" "n_args"
,closureFieldGcptr C "StgPAP" "fun"
,closureField C "StgPAP" "arity"
,closurePayload C "StgPAP" "payload"
,thunkSize C "StgAP"
,closureField C "StgAP" "n_args"
,closureFieldGcptr C "StgAP" "fun"
,closurePayload C "StgAP" "payload"
,thunkSize C "StgAP_STACK"
,closureField C "StgAP_STACK" "size"
,closureFieldGcptr C "StgAP_STACK" "fun"
,closurePayload C "StgAP_STACK" "payload"
,thunkSize C "StgSelector"
,closureFieldGcptr C "StgInd" "indirectee"
,closureSize C "StgMutVar"
,closureField C "StgMutVar" "var"
,closureSize C "StgAtomicallyFrame"
,closureField C "StgAtomicallyFrame" "code"
,closureField C "StgAtomicallyFrame" "next_invariant_to_check"
,closureField C "StgAtomicallyFrame" "result"
,closureField C "StgInvariantCheckQueue" "invariant"
,closureField C "StgInvariantCheckQueue" "my_execution"
,closureField C "StgInvariantCheckQueue" "next_queue_entry"
,closureField C "StgAtomicInvariant" "code"
,closureField C "StgTRecHeader" "enclosing_trec"
,closureSize C "StgCatchSTMFrame"
,closureField C "StgCatchSTMFrame" "handler"
,closureField C "StgCatchSTMFrame" "code"
,closureSize C "StgCatchRetryFrame"
,closureField C "StgCatchRetryFrame" "running_alt_code"
,closureField C "StgCatchRetryFrame" "first_code"
,closureField C "StgCatchRetryFrame" "alt_code"
,closureField C "StgTVarWatchQueue" "closure"
,closureField C "StgTVarWatchQueue" "next_queue_entry"
,closureField C "StgTVarWatchQueue" "prev_queue_entry"
,closureSize C "StgTVar"
,closureField C "StgTVar" "current_value"
,closureField C "StgTVar" "first_watch_queue_entry"
,closureField C "StgTVar" "num_updates"
,closureSize C "StgWeak"
,closureField C "StgWeak" "link"
,closureField C "StgWeak" "key"
,closureField C "StgWeak" "value"
,closureField C "StgWeak" "finalizer"
,closureField C "StgWeak" "cfinalizers"
,closureSize C "StgCFinalizerList"
,closureField C "StgCFinalizerList" "link"
,closureField C "StgCFinalizerList" "fptr"
,closureField C "StgCFinalizerList" "ptr"
,closureField C "StgCFinalizerList" "eptr"
,closureField C "StgCFinalizerList" "flag"
,closureSize C "StgMVar"
,closureField C "StgMVar" "head"
,closureField C "StgMVar" "tail"
,closureField C "StgMVar" "value"
,closureSize C "StgMVarTSOQueue"
,closureField C "StgMVarTSOQueue" "link"
,closureField C "StgMVarTSOQueue" "tso"
,closureSize C "StgBCO"
,closureField C "StgBCO" "instrs"
,closureField C "StgBCO" "literals"
,closureField C "StgBCO" "ptrs"
,closureField C "StgBCO" "arity"
,closureField C "StgBCO" "size"
,closurePayload C "StgBCO" "bitmap"
,closureSize C "StgStableName"
,closureField C "StgStableName" "sn"
,closureSize C "StgBlockingQueue"
,closureField C "StgBlockingQueue" "bh"
,closureField C "StgBlockingQueue" "owner"
,closureField C "StgBlockingQueue" "queue"
,closureField C "StgBlockingQueue" "link"
,closureSize C "MessageBlackHole"
,closureField C "MessageBlackHole" "link"
,closureField C "MessageBlackHole" "tso"
,closureField C "MessageBlackHole" "bh"
,structField_ C "RtsFlags_ProfFlags_showCCSOnException"
"RTS_FLAGS" "ProfFlags.showCCSOnException"
,structField_ C "RtsFlags_DebugFlags_apply"
"RTS_FLAGS" "DebugFlags.apply"
,structField_ C "RtsFlags_DebugFlags_sanity"
"RTS_FLAGS" "DebugFlags.sanity"
,structField_ C "RtsFlags_DebugFlags_weak"
"RTS_FLAGS" "DebugFlags.weak"
,structField_ C "RtsFlags_GcFlags_initialStkSize"
"RTS_FLAGS" "GcFlags.initialStkSize"
,structField_ C "RtsFlags_MiscFlags_tickInterval"
"RTS_FLAGS" "MiscFlags.tickInterval"
,structSize C "StgFunInfoExtraFwd"
,structField C "StgFunInfoExtraFwd" "slow_apply"
,structField C "StgFunInfoExtraFwd" "fun_type"
,structFieldH Both "StgFunInfoExtraFwd" "arity"
,structField_ C "StgFunInfoExtraFwd_bitmap" "StgFunInfoExtraFwd" "b.bitmap"
,structSize Both "StgFunInfoExtraRev"
,structField C "StgFunInfoExtraRev" "slow_apply_offset"
,structField C "StgFunInfoExtraRev" "fun_type"
,structFieldH Both "StgFunInfoExtraRev" "arity"
,structField_ C "StgFunInfoExtraRev_bitmap" "StgFunInfoExtraRev" "b.bitmap"
,structField C "StgLargeBitmap" "size"
,fieldOffset C "StgLargeBitmap" "bitmap"
,structSize C "snEntry"
,structField C "snEntry" "sn_obj"
,structField C "snEntry" "addr"
,structSize C "spEntry"
,structField C "spEntry" "addr"
-- Note that this conditional part only affects the C headers.
-- That's important, as it means we get the same PlatformConstants
-- type on all platforms.
,if os == "mingw32"
then concat [structSize C "StgAsyncIOResult"
,structField C "StgAsyncIOResult" "reqID"
,structField C "StgAsyncIOResult" "len"
,structField C "StgAsyncIOResult" "errCode"]
else []
-- pre-compiled thunk types
,constantWord Haskell "MAX_SPEC_SELECTEE_SIZE" "MAX_SPEC_SELECTEE_SIZE"
,constantWord Haskell "MAX_SPEC_AP_SIZE" "MAX_SPEC_AP_SIZE"
-- closure sizes: these do NOT include the header (see below for
-- header sizes)
,constantWord Haskell "MIN_PAYLOAD_SIZE" "MIN_PAYLOAD_SIZE"
,constantInt Haskell "MIN_INTLIKE" "MIN_INTLIKE"
,constantWord Haskell "MAX_INTLIKE" "MAX_INTLIKE"
,constantWord Haskell "MIN_CHARLIKE" "MIN_CHARLIKE"
,constantWord Haskell "MAX_CHARLIKE" "MAX_CHARLIKE"
,constantWord Haskell "MUT_ARR_PTRS_CARD_BITS" "MUT_ARR_PTRS_CARD_BITS"
-- A section of code-generator-related MAGIC CONSTANTS.
,constantWord Haskell "MAX_Vanilla_REG" "MAX_VANILLA_REG"
,constantWord Haskell "MAX_Float_REG" "MAX_FLOAT_REG"
,constantWord Haskell "MAX_Double_REG" "MAX_DOUBLE_REG"
,constantWord Haskell "MAX_Long_REG" "MAX_LONG_REG"
,constantWord Haskell "MAX_XMM_REG" "MAX_XMM_REG"
,constantWord Haskell "MAX_Real_Vanilla_REG" "MAX_REAL_VANILLA_REG"
,constantWord Haskell "MAX_Real_Float_REG" "MAX_REAL_FLOAT_REG"
,constantWord Haskell "MAX_Real_Double_REG" "MAX_REAL_DOUBLE_REG"
,constantWord Haskell "MAX_Real_XMM_REG" "MAX_REAL_XMM_REG"
,constantWord Haskell "MAX_Real_Long_REG" "MAX_REAL_LONG_REG"
-- This tells the native code generator the size of the spill
-- area is has available.
,constantWord Haskell "RESERVED_C_STACK_BYTES" "RESERVED_C_STACK_BYTES"
-- The amount of (Haskell) stack to leave free for saving
-- registers when returning to the scheduler.
,constantWord Haskell "RESERVED_STACK_WORDS" "RESERVED_STACK_WORDS"
-- Continuations that need more than this amount of stack
-- should do their own stack check (see bug #1466).
,constantWord Haskell "AP_STACK_SPLIM" "AP_STACK_SPLIM"
-- Size of a word, in bytes
,constantWord Haskell "WORD_SIZE" "SIZEOF_HSWORD"
-- Size of a double in StgWords.
,constantWord Haskell "DOUBLE_SIZE" "SIZEOF_DOUBLE"
-- Size of a C int, in bytes. May be smaller than wORD_SIZE.
,constantWord Haskell "CINT_SIZE" "SIZEOF_INT"
,constantWord Haskell "CLONG_SIZE" "SIZEOF_LONG"
,constantWord Haskell "CLONG_LONG_SIZE" "SIZEOF_LONG_LONG"
-- Number of bits to shift a bitfield left by in an info table.
,constantWord Haskell "BITMAP_BITS_SHIFT" "BITMAP_BITS_SHIFT"
-- Amount of pointer bits used for semi-tagging constructor closures
,constantWord Haskell "TAG_BITS" "TAG_BITS"
,constantBool Haskell "WORDS_BIGENDIAN" "defined(WORDS_BIGENDIAN)"
,constantBool Haskell "DYNAMIC_BY_DEFAULT" "defined(DYNAMIC_BY_DEFAULT)"
,constantWord Haskell "LDV_SHIFT" "LDV_SHIFT"
,constantNatural Haskell "ILDV_CREATE_MASK" "LDV_CREATE_MASK"
,constantNatural Haskell "ILDV_STATE_CREATE" "LDV_STATE_CREATE"
,constantNatural Haskell "ILDV_STATE_USE" "LDV_STATE_USE"
]
getWanted :: Bool -> FilePath -> FilePath -> [String] -> FilePath -> IO Results
getWanted verbose tmpdir gccProgram gccFlags nmProgram
= do let cStuff = unlines (headers ++ concatMap (doWanted . snd) wanteds)
cFile = tmpdir </> "tmp.c"
oFile = tmpdir </> "tmp.o"
writeFile cFile cStuff
execute verbose gccProgram (gccFlags ++ ["-c", cFile, "-o", oFile])
xs <- readProcess nmProgram ["-P", oFile] ""
let ls = lines xs
ms = map parseNmLine ls
m = Map.fromList $ catMaybes ms
rs <- mapM (lookupResult m) wanteds
return rs
where headers = ["#define IN_STG_CODE 0",
"",
"/*",
" * We need offsets of profiled things...",
" * better be careful that this doesn't",
" * affect the offsets of anything else.",
" */",
"",
"#define PROFILING",
"#define THREADED_RTS",
"",
"#include \"PosixSource.h\"",
"#include \"Rts.h\"",
"#include \"Stable.h\"",
"#include \"Capability.h\"",
"",
"#include <inttypes.h>",
"#include <stddef.h>",
"#include <stdio.h>",
"#include <string.h>",
"",
"#define FIELD_SIZE(s_type, field) ((size_t)sizeof(((s_type*)0)->field))",
"#define TYPE_SIZE(type) (sizeof(type))",
"#define FUN_OFFSET(sym) (offsetof(Capability,f.sym) - offsetof(Capability,r))",
"",
"#pragma GCC poison sizeof"
]
prefix = "derivedConstant"
mkFullName name = prefix ++ name
-- We add 1 to the value, as some platforms will make a symbol
-- of size 1 when for
-- char foo[0];
-- We then subtract 1 again when parsing.
doWanted (GetFieldType name (Fst (CExpr cExpr)))
= ["char " ++ mkFullName name ++ "[1 + " ++ cExpr ++ "];"]
doWanted (GetClosureSize name (Fst (CExpr cExpr)))
= ["char " ++ mkFullName name ++ "[1 + " ++ cExpr ++ "];"]
doWanted (GetWord name (Fst (CExpr cExpr)))
= ["char " ++ mkFullName name ++ "[1 + " ++ cExpr ++ "];"]
doWanted (GetInt name (Fst (CExpr cExpr)))
= ["char " ++ mkFullName name ++ "Mag[1 + ((intptr_t)(" ++ cExpr ++ ") >= 0 ? (" ++ cExpr ++ ") : -(" ++ cExpr ++ "))];",
"char " ++ mkFullName name ++ "Sig[(intptr_t)(" ++ cExpr ++ ") >= 0 ? 3 : 1];"]
doWanted (GetNatural name (Fst (CExpr cExpr)))
= -- These casts fix "right shift count >= width of type"
-- warnings
let cExpr' = "(uint64_t)(size_t)(" ++ cExpr ++ ")"
in ["char " ++ mkFullName name ++ "0[1 + ((" ++ cExpr' ++ ") & 0xFFFF)];",
"char " ++ mkFullName name ++ "1[1 + (((" ++ cExpr' ++ ") >> 16) & 0xFFFF)];",
"char " ++ mkFullName name ++ "2[1 + (((" ++ cExpr' ++ ") >> 32) & 0xFFFF)];",
"char " ++ mkFullName name ++ "3[1 + (((" ++ cExpr' ++ ") >> 48) & 0xFFFF)];"]
doWanted (GetBool name (Fst (CPPExpr cppExpr)))
= ["#if " ++ cppExpr,
"char " ++ mkFullName name ++ "[1];",
"#else",
"char " ++ mkFullName name ++ "[2];",
"#endif"]
doWanted (StructFieldMacro {}) = []
doWanted (ClosureFieldMacro {}) = []
doWanted (ClosurePayloadMacro {}) = []
doWanted (FieldTypeGcptrMacro {}) = []
-- parseNmLine parses "nm -P" output that looks like
-- "derivedConstantMAX_Vanilla_REG C 0000000b 0000000b" (GNU nm)
-- "_derivedConstantMAX_Vanilla_REG C b 0" (Mac OS X)
-- "_derivedConstantMAX_Vanilla_REG C 000000b" (MinGW)
-- "derivedConstantMAX_Vanilla_REG D 1 b" (Solaris)
-- and returns ("MAX_Vanilla_REG", 11)
parseNmLine line
= case words line of
('_' : n) : "C" : s : _ -> mkP n s
n : "C" : s : _ -> mkP n s
[n, "D", _, s] -> mkP n s
_ -> Nothing
where mkP r s = case (stripPrefix prefix r, readHex s) of
(Just name, [(size, "")]) -> Just (name, size)
_ -> Nothing
-- If an Int value is larger than 2^28 or smaller
-- than -2^28, then fail.
-- This test is a bit conservative, but if any
-- constants are roughly maxBound or minBound then
-- we probably need them to be Integer rather than
-- Int so that -- cross-compiling between 32bit and
-- 64bit platforms works.
lookupSmall :: Map String Integer -> Name -> IO Integer
lookupSmall m name
= case Map.lookup name m of
Just v
| v > 2^(28 :: Int) ||
v < -(2^(28 :: Int)) ->
die ("Value too large for GetWord: " ++ show v)
| otherwise -> return v
Nothing -> die ("Can't find " ++ show name)
lookupResult :: Map String Integer -> (Where, What Fst)
-> IO (Where, What Snd)
lookupResult m (w, GetWord name _)
= do v <- lookupSmall m name
return (w, GetWord name (Snd (v - 1)))
lookupResult m (w, GetInt name _)
= do mag <- lookupSmall m (name ++ "Mag")
sig <- lookupSmall m (name ++ "Sig")
return (w, GetWord name (Snd ((mag - 1) * (sig - 2))))
lookupResult m (w, GetNatural name _)
= do v0 <- lookupSmall m (name ++ "0")
v1 <- lookupSmall m (name ++ "1")
v2 <- lookupSmall m (name ++ "2")
v3 <- lookupSmall m (name ++ "3")
let v = (v0 - 1)
+ shiftL (v1 - 1) 16
+ shiftL (v2 - 1) 32
+ shiftL (v3 - 1) 48
return (w, GetWord name (Snd v))
lookupResult m (w, GetBool name _)
= do v <- lookupSmall m name
case v of
1 -> return (w, GetBool name (Snd True))
2 -> return (w, GetBool name (Snd False))
_ -> die ("Bad boolean: " ++ show v)
lookupResult m (w, GetFieldType name _)
= do v <- lookupSmall m name
return (w, GetFieldType name (Snd (v - 1)))
lookupResult m (w, GetClosureSize name _)
= do v <- lookupSmall m name
return (w, GetClosureSize name (Snd (v - 1)))
lookupResult _ (w, StructFieldMacro name)
= return (w, StructFieldMacro name)
lookupResult _ (w, ClosureFieldMacro name)
= return (w, ClosureFieldMacro name)
lookupResult _ (w, ClosurePayloadMacro name)
= return (w, ClosurePayloadMacro name)
lookupResult _ (w, FieldTypeGcptrMacro name)
= return (w, FieldTypeGcptrMacro name)
writeHaskellType :: FilePath -> [What Fst] -> IO ()
writeHaskellType fn ws = writeFile fn xs
where xs = unlines (headers ++ body ++ footers)
headers = ["data PlatformConstants = PlatformConstants {"
-- Now a kludge that allows the real entries to
-- all start with a comma, which makes life a
-- little easier
," pc_platformConstants :: ()"]
footers = [" } deriving Read"]
body = concatMap doWhat ws
doWhat (GetClosureSize name _) = [" , pc_" ++ name ++ " :: Int"]
doWhat (GetFieldType name _) = [" , pc_" ++ name ++ " :: Int"]
doWhat (GetWord name _) = [" , pc_" ++ name ++ " :: Int"]
doWhat (GetInt name _) = [" , pc_" ++ name ++ " :: Int"]
doWhat (GetNatural name _) = [" , pc_" ++ name ++ " :: Integer"]
doWhat (GetBool name _) = [" , pc_" ++ name ++ " :: Bool"]
doWhat (StructFieldMacro {}) = []
doWhat (ClosureFieldMacro {}) = []
doWhat (ClosurePayloadMacro {}) = []
doWhat (FieldTypeGcptrMacro {}) = []
writeHaskellValue :: FilePath -> [What Snd] -> IO ()
writeHaskellValue fn rs = writeFile fn xs
where xs = unlines (headers ++ body ++ footers)
headers = ["PlatformConstants {"
," pc_platformConstants = ()"]
footers = [" }"]
body = concatMap doWhat rs
doWhat (GetClosureSize name (Snd v)) = [" , pc_" ++ name ++ " = " ++ show v]
doWhat (GetFieldType name (Snd v)) = [" , pc_" ++ name ++ " = " ++ show v]
doWhat (GetWord name (Snd v)) = [" , pc_" ++ name ++ " = " ++ show v]
doWhat (GetInt name (Snd v)) = [" , pc_" ++ name ++ " = " ++ show v]
doWhat (GetNatural name (Snd v)) = [" , pc_" ++ name ++ " = " ++ show v]
doWhat (GetBool name (Snd v)) = [" , pc_" ++ name ++ " = " ++ show v]
doWhat (StructFieldMacro {}) = []
doWhat (ClosureFieldMacro {}) = []
doWhat (ClosurePayloadMacro {}) = []
doWhat (FieldTypeGcptrMacro {}) = []
writeHaskellWrappers :: FilePath -> [What Fst] -> IO ()
writeHaskellWrappers fn ws = writeFile fn xs
where xs = unlines body
body = concatMap doWhat ws
doWhat (GetFieldType {}) = []
doWhat (GetClosureSize {}) = []
doWhat (GetWord name _) = [haskellise name ++ " :: DynFlags -> Int",
haskellise name ++ " dflags = pc_" ++ name ++ " (sPlatformConstants (settings dflags))"]
doWhat (GetInt name _) = [haskellise name ++ " :: DynFlags -> Int",
haskellise name ++ " dflags = pc_" ++ name ++ " (sPlatformConstants (settings dflags))"]
doWhat (GetNatural name _) = [haskellise name ++ " :: DynFlags -> Integer",
haskellise name ++ " dflags = pc_" ++ name ++ " (sPlatformConstants (settings dflags))"]
doWhat (GetBool name _) = [haskellise name ++ " :: DynFlags -> Bool",
haskellise name ++ " dflags = pc_" ++ name ++ " (sPlatformConstants (settings dflags))"]
doWhat (StructFieldMacro {}) = []
doWhat (ClosureFieldMacro {}) = []
doWhat (ClosurePayloadMacro {}) = []
doWhat (FieldTypeGcptrMacro {}) = []
writeHaskellExports :: FilePath -> [What Fst] -> IO ()
writeHaskellExports fn ws = writeFile fn xs
where xs = unlines body
body = concatMap doWhat ws
doWhat (GetFieldType {}) = []
doWhat (GetClosureSize {}) = []
doWhat (GetWord name _) = [" " ++ haskellise name ++ ","]
doWhat (GetInt name _) = [" " ++ haskellise name ++ ","]
doWhat (GetNatural name _) = [" " ++ haskellise name ++ ","]
doWhat (GetBool name _) = [" " ++ haskellise name ++ ","]
doWhat (StructFieldMacro {}) = []
doWhat (ClosureFieldMacro {}) = []
doWhat (ClosurePayloadMacro {}) = []
doWhat (FieldTypeGcptrMacro {}) = []
writeHeader :: FilePath -> [What Snd] -> IO ()
writeHeader fn rs = writeFile fn xs
where xs = unlines (headers ++ body)
headers = ["/* This file is created automatically. Do not edit by hand.*/", ""]
body = concatMap doWhat rs
doWhat (GetFieldType name (Snd v)) = ["#define " ++ name ++ " b" ++ show (v * 8)]
doWhat (GetClosureSize name (Snd v)) = ["#define " ++ name ++ " (SIZEOF_StgHeader+" ++ show v ++ ")"]
doWhat (GetWord name (Snd v)) = ["#define " ++ name ++ " " ++ show v]
doWhat (GetInt name (Snd v)) = ["#define " ++ name ++ " " ++ show v]
doWhat (GetNatural name (Snd v)) = ["#define " ++ name ++ " " ++ show v]
doWhat (GetBool name (Snd v)) = ["#define " ++ name ++ " " ++ show (fromEnum v)]
doWhat (StructFieldMacro nameBase) =
["#define " ++ nameBase ++ "(__ptr__) REP_" ++ nameBase ++ "[__ptr__+OFFSET_" ++ nameBase ++ "]"]
doWhat (ClosureFieldMacro nameBase) =
["#define " ++ nameBase ++ "(__ptr__) REP_" ++ nameBase ++ "[__ptr__+SIZEOF_StgHeader+OFFSET_" ++ nameBase ++ "]"]
doWhat (ClosurePayloadMacro nameBase) =
["#define " ++ nameBase ++ "(__ptr__,__ix__) W_[__ptr__+SIZEOF_StgHeader+OFFSET_" ++ nameBase ++ " + WDS(__ix__)]"]
doWhat (FieldTypeGcptrMacro nameBase) =
["#define REP_" ++ nameBase ++ " gcptr"]
die :: String -> IO a
die err = do hPutStrLn stderr err
exitFailure
execute :: Bool -> FilePath -> [String] -> IO ()
execute verbose prog args
= do when verbose $ putStrLn $ showCommandForUser prog args
ec <- rawSystem prog args
unless (ec == ExitSuccess) $
die ("Executing " ++ show prog ++ " failed")
|
lukexi/ghc-7.8-arm64
|
utils/deriveConstants/DeriveConstants.hs
|
bsd-3-clause
| 40,857 | 0 | 18 | 13,280 | 9,491 | 4,884 | 4,607 | 698 | 26 |
{-# LANGUAGE CPP #-}
-----------------------------------------------------------------------------
-- |
-- Module : Main
-- Copyright : (c) David Himmelstrup 2005
-- License : BSD-like
--
-- Maintainer : [email protected]
-- Stability : provisional
-- Portability : portable
--
-- Entry point to the default cabal-install front-end.
-----------------------------------------------------------------------------
module Main (main) where
import Distribution.Client.Setup
( GlobalFlags(..), globalCommand, globalRepos
, ConfigFlags(..)
, ConfigExFlags(..), defaultConfigExFlags, configureExCommand
, BuildFlags(..), BuildExFlags(..), SkipAddSourceDepsCheck(..)
, buildCommand, replCommand, testCommand, benchmarkCommand
, InstallFlags(..), defaultInstallFlags
, installCommand, upgradeCommand, uninstallCommand
, FetchFlags(..), fetchCommand
, FreezeFlags(..), freezeCommand
, GetFlags(..), getCommand, unpackCommand
, checkCommand
, formatCommand
, updateCommand
, ListFlags(..), listCommand
, InfoFlags(..), infoCommand
, UploadFlags(..), uploadCommand
, ReportFlags(..), reportCommand
, runCommand
, InitFlags(initVerbosity), initCommand
, SDistFlags(..), SDistExFlags(..), sdistCommand
, Win32SelfUpgradeFlags(..), win32SelfUpgradeCommand
, ActAsSetupFlags(..), actAsSetupCommand
, SandboxFlags(..), sandboxCommand
, ExecFlags(..), execCommand
, UserConfigFlags(..), userConfigCommand
, reportCommand
)
import Distribution.Simple.Setup
( HaddockFlags(..), haddockCommand, defaultHaddockFlags
, HscolourFlags(..), hscolourCommand
, ReplFlags(..)
, CopyFlags(..), copyCommand
, RegisterFlags(..), registerCommand
, CleanFlags(..), cleanCommand
, TestFlags(..), BenchmarkFlags(..)
, Flag(..), fromFlag, fromFlagOrDefault, flagToMaybe, toFlag
, configAbsolutePaths
)
import Distribution.Client.SetupWrapper
( setupWrapper, SetupScriptOptions(..), defaultSetupScriptOptions )
import Distribution.Client.Config
( SavedConfig(..), loadConfig, defaultConfigFile, userConfigDiff
, userConfigUpdate )
import Distribution.Client.Targets
( readUserTargets )
import qualified Distribution.Client.List as List
( list, info )
import Distribution.Client.Install (install)
import Distribution.Client.Configure (configure)
import Distribution.Client.Update (update)
import Distribution.Client.Exec (exec)
import Distribution.Client.Fetch (fetch)
import Distribution.Client.Freeze (freeze)
import Distribution.Client.Check as Check (check)
--import Distribution.Client.Clean (clean)
import Distribution.Client.Upload as Upload (upload, check, report)
import Distribution.Client.Run (run, splitRunArgs)
import Distribution.Client.HttpUtils (configureTransport)
import Distribution.Client.SrcDist (sdist)
import Distribution.Client.Get (get)
import Distribution.Client.Sandbox (sandboxInit
,sandboxAddSource
,sandboxDelete
,sandboxDeleteSource
,sandboxListSources
,sandboxHcPkg
,dumpPackageEnvironment
,getSandboxConfigFilePath
,loadConfigOrSandboxConfig
,findSavedDistPref
,initPackageDBIfNeeded
,maybeWithSandboxDirOnSearchPath
,maybeWithSandboxPackageInfo
,WereDepsReinstalled(..)
,maybeReinstallAddSourceDeps
,tryGetIndexFilePath
,sandboxBuildDir
,updateSandboxConfigFileFlag
,updateInstallDirs
,configCompilerAux'
,getPersistOrConfigCompiler
,configPackageDB')
import Distribution.Client.Sandbox.PackageEnvironment
(setPackageDB
,userPackageEnvironmentFile)
import Distribution.Client.Sandbox.Timestamp (maybeAddCompilerTimestampRecord)
import Distribution.Client.Sandbox.Types (UseSandbox(..), whenUsingSandbox)
import Distribution.Client.Types (Password (..))
import Distribution.Client.Init (initCabal)
import qualified Distribution.Client.Win32SelfUpgrade as Win32SelfUpgrade
import Distribution.Client.Utils (determineNumJobs
#if defined(mingw32_HOST_OS)
,relaxEncodingErrors
#endif
,existsAndIsMoreRecentThan)
import Distribution.PackageDescription
( BuildType(..), Executable(..), benchmarkName, benchmarkBuildInfo
, testName, testBuildInfo, buildable )
import Distribution.PackageDescription.Parse
( readPackageDescription )
import Distribution.PackageDescription.PrettyPrint
( writeGenericPackageDescription )
import qualified Distribution.Simple as Simple
import qualified Distribution.Make as Make
import Distribution.Simple.Build
( startInterpreter )
import Distribution.Simple.Command
( CommandParse(..), CommandUI(..), Command
, commandsRun, commandAddAction, hiddenCommand )
import Distribution.Simple.Compiler
( Compiler(..) )
import Distribution.Simple.Configure
( checkPersistBuildConfigOutdated, configCompilerAuxEx
, ConfigStateFileError(..), localBuildInfoFile
, getPersistBuildConfig, tryGetPersistBuildConfig )
import qualified Distribution.Simple.LocalBuildInfo as LBI
import Distribution.Simple.Program (defaultProgramConfiguration
,configureAllKnownPrograms
,simpleProgramInvocation
,getProgramInvocationOutput)
import Distribution.Simple.Program.Db (reconfigurePrograms)
import qualified Distribution.Simple.Setup as Cabal
import Distribution.Simple.Utils
( cabalVersion, die, notice, info, topHandler
, findPackageDesc, tryFindPackageDesc )
import Distribution.Text
( display )
import Distribution.Verbosity as Verbosity
( Verbosity, normal )
import Distribution.Version
( Version(..), orLaterVersion )
import qualified Paths_cabal_install (version)
import System.Environment (getArgs, getProgName)
import System.Exit (exitFailure)
import System.FilePath (splitExtension, takeExtension)
import System.IO ( BufferMode(LineBuffering), hSetBuffering
#ifdef mingw32_HOST_OS
, stderr
#endif
, stdout )
import System.Directory (doesFileExist, getCurrentDirectory)
import Data.List (intercalate)
import Data.Maybe (mapMaybe)
#if !MIN_VERSION_base(4,8,0)
import Data.Monoid (Monoid(..))
import Control.Applicative (pure, (<$>))
#endif
import Control.Monad (when, unless)
-- | Entry point
--
main :: IO ()
main = do
-- Enable line buffering so that we can get fast feedback even when piped.
-- This is especially important for CI and build systems.
hSetBuffering stdout LineBuffering
-- The default locale encoding for Windows CLI is not UTF-8 and printing
-- Unicode characters to it will fail unless we relax the handling of encoding
-- errors when writing to stderr and stdout.
#ifdef mingw32_HOST_OS
relaxEncodingErrors stdout
relaxEncodingErrors stderr
#endif
getArgs >>= mainWorker
mainWorker :: [String] -> IO ()
mainWorker args = topHandler $
case commandsRun (globalCommand commands) commands args of
CommandHelp help -> printGlobalHelp help
CommandList opts -> printOptionsList opts
CommandErrors errs -> printErrors errs
CommandReadyToGo (globalFlags, commandParse) ->
case commandParse of
_ | fromFlagOrDefault False (globalVersion globalFlags)
-> printVersion
| fromFlagOrDefault False (globalNumericVersion globalFlags)
-> printNumericVersion
CommandHelp help -> printCommandHelp help
CommandList opts -> printOptionsList opts
CommandErrors errs -> printErrors errs
CommandReadyToGo action -> do
globalFlags' <- updateSandboxConfigFileFlag globalFlags
action globalFlags'
where
printCommandHelp help = do
pname <- getProgName
putStr (help pname)
printGlobalHelp help = do
pname <- getProgName
configFile <- defaultConfigFile
putStr (help pname)
putStr $ "\nYou can edit the cabal configuration file to set defaults:\n"
++ " " ++ configFile ++ "\n"
exists <- doesFileExist configFile
when (not exists) $
putStrLn $ "This file will be generated with sensible "
++ "defaults if you run 'cabal update'."
printOptionsList = putStr . unlines
printErrors errs = die $ intercalate "\n" errs
printNumericVersion = putStrLn $ display Paths_cabal_install.version
printVersion = putStrLn $ "cabal-install version "
++ display Paths_cabal_install.version
++ "\nusing version "
++ display cabalVersion
++ " of the Cabal library "
commands =
[installCommand `commandAddAction` installAction
,updateCommand `commandAddAction` updateAction
,listCommand `commandAddAction` listAction
,infoCommand `commandAddAction` infoAction
,fetchCommand `commandAddAction` fetchAction
,freezeCommand `commandAddAction` freezeAction
,getCommand `commandAddAction` getAction
,hiddenCommand $
unpackCommand `commandAddAction` unpackAction
,checkCommand `commandAddAction` checkAction
,sdistCommand `commandAddAction` sdistAction
,uploadCommand `commandAddAction` uploadAction
,reportCommand `commandAddAction` reportAction
,runCommand `commandAddAction` runAction
,initCommand `commandAddAction` initAction
,configureExCommand `commandAddAction` configureAction
,buildCommand `commandAddAction` buildAction
,replCommand `commandAddAction` replAction
,sandboxCommand `commandAddAction` sandboxAction
,haddockCommand `commandAddAction` haddockAction
,execCommand `commandAddAction` execAction
,userConfigCommand `commandAddAction` userConfigAction
,cleanCommand `commandAddAction` cleanAction
,wrapperAction copyCommand
copyVerbosity copyDistPref
,wrapperAction hscolourCommand
hscolourVerbosity hscolourDistPref
,wrapperAction registerCommand
regVerbosity regDistPref
,testCommand `commandAddAction` testAction
,benchmarkCommand `commandAddAction` benchmarkAction
,hiddenCommand $
uninstallCommand `commandAddAction` uninstallAction
,hiddenCommand $
formatCommand `commandAddAction` formatAction
,hiddenCommand $
upgradeCommand `commandAddAction` upgradeAction
,hiddenCommand $
win32SelfUpgradeCommand`commandAddAction` win32SelfUpgradeAction
,hiddenCommand $
actAsSetupCommand`commandAddAction` actAsSetupAction
]
wrapperAction :: Monoid flags
=> CommandUI flags
-> (flags -> Flag Verbosity)
-> (flags -> Flag String)
-> Command (GlobalFlags -> IO ())
wrapperAction command verbosityFlag distPrefFlag =
commandAddAction command
{ commandDefaultFlags = mempty } $ \flags extraArgs globalFlags -> do
let verbosity = fromFlagOrDefault normal (verbosityFlag flags)
(_, config) <- loadConfigOrSandboxConfig verbosity globalFlags
distPref <- findSavedDistPref config (distPrefFlag flags)
let setupScriptOptions = defaultSetupScriptOptions { useDistPref = distPref }
setupWrapper verbosity setupScriptOptions Nothing
command (const flags) extraArgs
configureAction :: (ConfigFlags, ConfigExFlags)
-> [String] -> GlobalFlags -> IO ()
configureAction (configFlags, configExFlags) extraArgs globalFlags = do
let verbosity = fromFlagOrDefault normal (configVerbosity configFlags)
(useSandbox, config) <- fmap
(updateInstallDirs (configUserInstall configFlags))
(loadConfigOrSandboxConfig verbosity globalFlags)
let configFlags' = savedConfigureFlags config `mappend` configFlags
configExFlags' = savedConfigureExFlags config `mappend` configExFlags
globalFlags' = savedGlobalFlags config `mappend` globalFlags
(comp, platform, conf) <- configCompilerAuxEx configFlags'
-- If we're working inside a sandbox and the user has set the -w option, we
-- may need to create a sandbox-local package DB for this compiler and add a
-- timestamp record for this compiler to the timestamp file.
let configFlags'' = case useSandbox of
NoSandbox -> configFlags'
(UseSandbox sandboxDir) -> setPackageDB sandboxDir
comp platform configFlags'
whenUsingSandbox useSandbox $ \sandboxDir -> do
initPackageDBIfNeeded verbosity configFlags'' comp conf
-- NOTE: We do not write the new sandbox package DB location to
-- 'cabal.sandbox.config' here because 'configure -w' must not affect
-- subsequent 'install' (for UI compatibility with non-sandboxed mode).
indexFile <- tryGetIndexFilePath config
maybeAddCompilerTimestampRecord verbosity sandboxDir indexFile
(compilerId comp) platform
maybeWithSandboxDirOnSearchPath useSandbox $
configure verbosity
(configPackageDB' configFlags'')
(globalRepos globalFlags')
comp platform conf configFlags'' configExFlags' extraArgs
buildAction :: (BuildFlags, BuildExFlags) -> [String] -> GlobalFlags -> IO ()
buildAction (buildFlags, buildExFlags) extraArgs globalFlags = do
let verbosity = fromFlagOrDefault normal (buildVerbosity buildFlags)
noAddSource = fromFlagOrDefault DontSkipAddSourceDepsCheck
(buildOnly buildExFlags)
-- Calls 'configureAction' to do the real work, so nothing special has to be
-- done to support sandboxes.
(useSandbox, config, distPref) <- reconfigure verbosity
(buildDistPref buildFlags)
mempty [] globalFlags noAddSource
(buildNumJobs buildFlags) (const Nothing)
maybeWithSandboxDirOnSearchPath useSandbox $
build verbosity config distPref buildFlags extraArgs
-- | Actually do the work of building the package. This is separate from
-- 'buildAction' so that 'testAction' and 'benchmarkAction' do not invoke
-- 'reconfigure' twice.
build :: Verbosity -> SavedConfig -> FilePath -> BuildFlags -> [String] -> IO ()
build verbosity config distPref buildFlags extraArgs =
setupWrapper verbosity setupOptions Nothing
(Cabal.buildCommand progConf) mkBuildFlags extraArgs
where
progConf = defaultProgramConfiguration
setupOptions = defaultSetupScriptOptions { useDistPref = distPref }
mkBuildFlags version = filterBuildFlags version config buildFlags'
buildFlags' = buildFlags
{ buildVerbosity = toFlag verbosity
, buildDistPref = toFlag distPref
}
-- | Make sure that we don't pass new flags to setup scripts compiled against
-- old versions of Cabal.
filterBuildFlags :: Version -> SavedConfig -> BuildFlags -> BuildFlags
filterBuildFlags version config buildFlags
| version >= Version [1,19,1] [] = buildFlags_latest
-- Cabal < 1.19.1 doesn't support 'build -j'.
| otherwise = buildFlags_pre_1_19_1
where
buildFlags_pre_1_19_1 = buildFlags {
buildNumJobs = NoFlag
}
buildFlags_latest = buildFlags {
-- Take the 'jobs' setting '~/.cabal/config' into account.
buildNumJobs = Flag . Just . determineNumJobs $
(numJobsConfigFlag `mappend` numJobsCmdLineFlag)
}
numJobsConfigFlag = installNumJobs . savedInstallFlags $ config
numJobsCmdLineFlag = buildNumJobs buildFlags
replAction :: (ReplFlags, BuildExFlags) -> [String] -> GlobalFlags -> IO ()
replAction (replFlags, buildExFlags) extraArgs globalFlags = do
cwd <- getCurrentDirectory
pkgDesc <- findPackageDesc cwd
either (const onNoPkgDesc) (const onPkgDesc) pkgDesc
where
verbosity = fromFlagOrDefault normal (replVerbosity replFlags)
-- There is a .cabal file in the current directory: start a REPL and load
-- the project's modules.
onPkgDesc = do
let noAddSource = case replReload replFlags of
Flag True -> SkipAddSourceDepsCheck
_ -> fromFlagOrDefault DontSkipAddSourceDepsCheck
(buildOnly buildExFlags)
-- Calls 'configureAction' to do the real work, so nothing special has to
-- be done to support sandboxes.
(useSandbox, _config, distPref) <-
reconfigure verbosity (replDistPref replFlags)
mempty [] globalFlags noAddSource NoFlag
(const Nothing)
let progConf = defaultProgramConfiguration
setupOptions = defaultSetupScriptOptions
{ useCabalVersion = orLaterVersion $ Version [1,18,0] []
, useDistPref = distPref
}
replFlags' = replFlags
{ replVerbosity = toFlag verbosity
, replDistPref = toFlag distPref
}
maybeWithSandboxDirOnSearchPath useSandbox $
setupWrapper verbosity setupOptions Nothing
(Cabal.replCommand progConf) (const replFlags') extraArgs
-- No .cabal file in the current directory: just start the REPL (possibly
-- using the sandbox package DB).
onNoPkgDesc = do
(_useSandbox, config) <- loadConfigOrSandboxConfig verbosity globalFlags
let configFlags = savedConfigureFlags config
(comp, _platform, programDb) <- configCompilerAux' configFlags
programDb' <- reconfigurePrograms verbosity
(replProgramPaths replFlags)
(replProgramArgs replFlags)
programDb
startInterpreter verbosity programDb' comp (configPackageDB' configFlags)
-- | Re-configure the package in the current directory if needed. Deciding
-- when to reconfigure and with which options is convoluted:
--
-- If we are reconfiguring, we must always run @configure@ with the
-- verbosity option we are given; however, that a previous configuration
-- uses a different verbosity setting is not reason enough to reconfigure.
--
-- The package should be configured to use the same \"dist\" prefix as
-- given to the @build@ command, otherwise the build will probably
-- fail. Not only does this determine the \"dist\" prefix setting if we
-- need to reconfigure anyway, but an existing configuration should be
-- invalidated if its \"dist\" prefix differs.
--
-- If the package has never been configured (i.e., there is no
-- LocalBuildInfo), we must configure first, using the default options.
--
-- If the package has been configured, there will be a 'LocalBuildInfo'.
-- If there no package description file, we assume that the
-- 'PackageDescription' is up to date, though the configuration may need
-- to be updated for other reasons (see above). If there is a package
-- description file, and it has been modified since the 'LocalBuildInfo'
-- was generated, then we need to reconfigure.
--
-- The caller of this function may also have specific requirements
-- regarding the flags the last configuration used. For example,
-- 'testAction' requires that the package be configured with test suites
-- enabled. The caller may pass the required settings to this function
-- along with a function to check the validity of the saved 'ConfigFlags';
-- these required settings will be checked first upon determining that
-- a previous configuration exists.
reconfigure :: Verbosity -- ^ Verbosity setting
-> Flag FilePath -- ^ \"dist\" prefix
-> ConfigFlags -- ^ Additional config flags to set. These flags
-- will be 'mappend'ed to the last used or
-- default 'ConfigFlags' as appropriate, so
-- this value should be 'mempty' with only the
-- required flags set. The required verbosity
-- and \"dist\" prefix flags will be set
-- automatically because they are always
-- required; therefore, it is not necessary to
-- set them here.
-> [String] -- ^ Extra arguments
-> GlobalFlags -- ^ Global flags
-> SkipAddSourceDepsCheck
-- ^ Should we skip the timestamp check for modified
-- add-source dependencies?
-> Flag (Maybe Int)
-- ^ -j flag for reinstalling add-source deps.
-> (ConfigFlags -> Maybe String)
-- ^ Check that the required flags are set in
-- the last used 'ConfigFlags'. If the required
-- flags are not set, provide a message to the
-- user explaining the reason for
-- reconfiguration. Because the correct \"dist\"
-- prefix setting is always required, it is checked
-- automatically; this function need not check
-- for it.
-> IO (UseSandbox, SavedConfig, FilePath)
reconfigure verbosity flagDistPref addConfigFlags extraArgs globalFlags
skipAddSourceDepsCheck numJobsFlag checkFlags = do
(useSandbox, config) <- loadConfigOrSandboxConfig verbosity globalFlags
distPref <- findSavedDistPref config flagDistPref
eLbi <- tryGetPersistBuildConfig distPref
config' <- case eLbi of
Left err -> onNoBuildConfig (useSandbox, config) distPref err
Right lbi -> onBuildConfig (useSandbox, config) distPref lbi
return (useSandbox, config', distPref)
where
-- We couldn't load the saved package config file.
--
-- If we're in a sandbox: add-source deps don't have to be reinstalled
-- (since we don't know the compiler & platform).
onNoBuildConfig :: (UseSandbox, SavedConfig) -> FilePath
-> ConfigStateFileError -> IO SavedConfig
onNoBuildConfig (_, config) distPref err = do
let msg = case err of
ConfigStateFileMissing -> "Package has never been configured."
ConfigStateFileNoParse -> "Saved package config file seems "
++ "to be corrupt."
_ -> show err
case err of
ConfigStateFileBadVersion _ _ _ -> info verbosity msg
_ -> do
let distVerbFlags = mempty
{ configVerbosity = toFlag verbosity
, configDistPref = toFlag distPref
}
defaultFlags = mappend addConfigFlags distVerbFlags
notice verbosity
$ msg ++ " Configuring with default flags." ++ configureManually
configureAction (defaultFlags, defaultConfigExFlags)
extraArgs globalFlags
return config
-- Package has been configured, but the configuration may be out of
-- date or required flags may not be set.
--
-- If we're in a sandbox: reinstall the modified add-source deps and
-- force reconfigure if we did.
onBuildConfig :: (UseSandbox, SavedConfig) -> FilePath
-> LBI.LocalBuildInfo -> IO SavedConfig
onBuildConfig (useSandbox, config) distPref lbi = do
let configFlags = LBI.configFlags lbi
distVerbFlags = mempty
{ configVerbosity = toFlag verbosity
, configDistPref = toFlag distPref
}
flags = mconcat [configFlags, addConfigFlags, distVerbFlags]
-- Was the sandbox created after the package was already configured? We
-- may need to skip reinstallation of add-source deps and force
-- reconfigure.
let buildConfig = localBuildInfoFile distPref
sandboxConfig <- getSandboxConfigFilePath globalFlags
isSandboxConfigNewer <-
sandboxConfig `existsAndIsMoreRecentThan` buildConfig
let skipAddSourceDepsCheck'
| isSandboxConfigNewer = SkipAddSourceDepsCheck
| otherwise = skipAddSourceDepsCheck
when (skipAddSourceDepsCheck' == SkipAddSourceDepsCheck) $
info verbosity "Skipping add-source deps check..."
let (_, config') = updateInstallDirs
(configUserInstall flags)
(useSandbox, config)
depsReinstalled <-
case skipAddSourceDepsCheck' of
DontSkipAddSourceDepsCheck ->
maybeReinstallAddSourceDeps
verbosity numJobsFlag flags globalFlags
(useSandbox, config')
SkipAddSourceDepsCheck -> do
return NoDepsReinstalled
-- Is the @cabal.config@ file newer than @dist/setup.config@? Then we need
-- to force reconfigure. Note that it's possible to use @cabal.config@
-- even without sandboxes.
isUserPackageEnvironmentFileNewer <-
userPackageEnvironmentFile `existsAndIsMoreRecentThan` buildConfig
-- Determine whether we need to reconfigure and which message to show to
-- the user if that is the case.
mMsg <- determineMessageToShow distPref lbi configFlags
depsReinstalled isSandboxConfigNewer
isUserPackageEnvironmentFileNewer
case mMsg of
-- No message for the user indicates that reconfiguration
-- is not required.
Nothing -> return config'
-- Show the message and reconfigure.
Just msg -> do
notice verbosity msg
configureAction (flags, defaultConfigExFlags)
extraArgs globalFlags
return config'
-- Determine what message, if any, to display to the user if reconfiguration
-- is required.
determineMessageToShow :: FilePath -> LBI.LocalBuildInfo -> ConfigFlags
-> WereDepsReinstalled -> Bool -> Bool
-> IO (Maybe String)
determineMessageToShow _ _ _ _ True _ =
-- The sandbox was created after the package was already configured.
return $! Just $! sandboxConfigNewerMessage
determineMessageToShow _ _ _ _ False True =
-- The user package environment file was modified.
return $! Just $! userPackageEnvironmentFileModifiedMessage
determineMessageToShow distPref lbi configFlags depsReinstalled
False False = do
let savedDistPref = fromFlagOrDefault
(useDistPref defaultSetupScriptOptions)
(configDistPref configFlags)
case depsReinstalled of
ReinstalledSomeDeps ->
-- Some add-source deps were reinstalled.
return $! Just $! reinstalledDepsMessage
NoDepsReinstalled ->
case checkFlags configFlags of
-- Flag required by the caller is not set.
Just msg -> return $! Just $! msg ++ configureManually
Nothing
-- Required "dist" prefix is not set.
| savedDistPref /= distPref ->
return $! Just distPrefMessage
-- All required flags are set, but the configuration
-- may be outdated.
| otherwise -> case LBI.pkgDescrFile lbi of
Nothing -> return Nothing
Just pdFile -> do
outdated <- checkPersistBuildConfigOutdated
distPref pdFile
return $! if outdated
then Just $! outdatedMessage pdFile
else Nothing
reconfiguringMostRecent = " Re-configuring with most recently used options."
configureManually = " If this fails, please run configure manually."
sandboxConfigNewerMessage =
"The sandbox was created after the package was already configured."
++ reconfiguringMostRecent
++ configureManually
userPackageEnvironmentFileModifiedMessage =
"The user package environment file ('"
++ userPackageEnvironmentFile ++ "') was modified."
++ reconfiguringMostRecent
++ configureManually
distPrefMessage =
"Package previously configured with different \"dist\" prefix."
++ reconfiguringMostRecent
++ configureManually
outdatedMessage pdFile =
pdFile ++ " has been changed."
++ reconfiguringMostRecent
++ configureManually
reinstalledDepsMessage =
"Some add-source dependencies have been reinstalled."
++ reconfiguringMostRecent
++ configureManually
installAction :: (ConfigFlags, ConfigExFlags, InstallFlags, HaddockFlags)
-> [String] -> GlobalFlags -> IO ()
installAction (configFlags, _, installFlags, _) _ globalFlags
| fromFlagOrDefault False (installOnly installFlags) = do
let verbosity = fromFlagOrDefault normal (configVerbosity configFlags)
(_, config) <- loadConfigOrSandboxConfig verbosity globalFlags
distPref <- findSavedDistPref config (configDistPref configFlags)
let setupOpts = defaultSetupScriptOptions { useDistPref = distPref }
setupWrapper verbosity setupOpts Nothing installCommand (const mempty) []
installAction (configFlags, configExFlags, installFlags, haddockFlags)
extraArgs globalFlags = do
let verbosity = fromFlagOrDefault normal (configVerbosity configFlags)
(useSandbox, config) <- fmap
(updateInstallDirs (configUserInstall configFlags))
(loadConfigOrSandboxConfig verbosity globalFlags)
targets <- readUserTargets verbosity extraArgs
-- TODO: It'd be nice if 'cabal install' picked up the '-w' flag passed to
-- 'configure' when run inside a sandbox. Right now, running
--
-- $ cabal sandbox init && cabal configure -w /path/to/ghc
-- && cabal build && cabal install
--
-- performs the compilation twice unless you also pass -w to 'install'.
-- However, this is the same behaviour that 'cabal install' has in the normal
-- mode of operation, so we stick to it for consistency.
let sandboxDistPref = case useSandbox of
NoSandbox -> NoFlag
UseSandbox sandboxDir -> Flag $ sandboxBuildDir sandboxDir
distPref <- findSavedDistPref config
(configDistPref configFlags `mappend` sandboxDistPref)
let configFlags' = maybeForceTests installFlags' $
savedConfigureFlags config `mappend`
configFlags { configDistPref = toFlag distPref }
configExFlags' = defaultConfigExFlags `mappend`
savedConfigureExFlags config `mappend` configExFlags
installFlags' = defaultInstallFlags `mappend`
savedInstallFlags config `mappend` installFlags
haddockFlags' = defaultHaddockFlags `mappend`
savedHaddockFlags config `mappend`
haddockFlags { haddockDistPref = toFlag distPref }
globalFlags' = savedGlobalFlags config `mappend` globalFlags
(comp, platform, conf) <- configCompilerAux' configFlags'
-- TODO: Redesign ProgramDB API to prevent such problems as #2241 in the future.
conf' <- configureAllKnownPrograms verbosity conf
-- If we're working inside a sandbox and the user has set the -w option, we
-- may need to create a sandbox-local package DB for this compiler and add a
-- timestamp record for this compiler to the timestamp file.
configFlags'' <- case useSandbox of
NoSandbox -> configAbsolutePaths $ configFlags'
(UseSandbox sandboxDir) -> return $ setPackageDB sandboxDir comp platform configFlags'
whenUsingSandbox useSandbox $ \sandboxDir -> do
initPackageDBIfNeeded verbosity configFlags'' comp conf'
indexFile <- tryGetIndexFilePath config
maybeAddCompilerTimestampRecord verbosity sandboxDir indexFile
(compilerId comp) platform
-- FIXME: Passing 'SandboxPackageInfo' to install unconditionally here means
-- that 'cabal install some-package' inside a sandbox will sometimes reinstall
-- modified add-source deps, even if they are not among the dependencies of
-- 'some-package'. This can also prevent packages that depend on older
-- versions of add-source'd packages from building (see #1362).
maybeWithSandboxPackageInfo verbosity configFlags'' globalFlags'
comp platform conf useSandbox $ \mSandboxPkgInfo ->
maybeWithSandboxDirOnSearchPath useSandbox $
install verbosity
(configPackageDB' configFlags'')
(globalRepos globalFlags')
comp platform conf'
useSandbox mSandboxPkgInfo
globalFlags' configFlags'' configExFlags'
installFlags' haddockFlags'
targets
where
-- '--run-tests' implies '--enable-tests'.
maybeForceTests installFlags' configFlags' =
if fromFlagOrDefault False (installRunTests installFlags')
then configFlags' { configTests = toFlag True }
else configFlags'
testAction :: (TestFlags, BuildFlags, BuildExFlags) -> [String] -> GlobalFlags
-> IO ()
testAction (testFlags, buildFlags, buildExFlags) extraArgs globalFlags = do
let verbosity = fromFlagOrDefault normal (testVerbosity testFlags)
addConfigFlags = mempty { configTests = toFlag True }
noAddSource = fromFlagOrDefault DontSkipAddSourceDepsCheck
(buildOnly buildExFlags)
buildFlags' = buildFlags
{ buildVerbosity = testVerbosity testFlags }
checkFlags flags
| fromFlagOrDefault False (configTests flags) = Nothing
| otherwise = Just "Re-configuring with test suites enabled."
-- reconfigure also checks if we're in a sandbox and reinstalls add-source
-- deps if needed.
(useSandbox, config, distPref) <-
reconfigure verbosity (testDistPref testFlags)
addConfigFlags [] globalFlags noAddSource
(buildNumJobs buildFlags') checkFlags
let setupOptions = defaultSetupScriptOptions { useDistPref = distPref }
testFlags' = testFlags { testDistPref = toFlag distPref }
-- the package was just configured, so the LBI must be available
lbi <- getPersistBuildConfig distPref
let pkgDescr = LBI.localPkgDescr lbi
nameTestsOnly =
LBI.foldComponent
(const Nothing)
(const Nothing)
(\t ->
if buildable (testBuildInfo t)
then Just (testName t)
else Nothing)
(const Nothing)
tests = mapMaybe nameTestsOnly $ LBI.pkgComponents pkgDescr
extraArgs'
| null extraArgs = tests
| otherwise = extraArgs
if null tests
then notice verbosity "Package has no buildable test suites."
else do
maybeWithSandboxDirOnSearchPath useSandbox $
build verbosity config distPref buildFlags' extraArgs'
maybeWithSandboxDirOnSearchPath useSandbox $
setupWrapper verbosity setupOptions Nothing
Cabal.testCommand (const testFlags') extraArgs'
benchmarkAction :: (BenchmarkFlags, BuildFlags, BuildExFlags)
-> [String] -> GlobalFlags
-> IO ()
benchmarkAction (benchmarkFlags, buildFlags, buildExFlags)
extraArgs globalFlags = do
let verbosity = fromFlagOrDefault normal
(benchmarkVerbosity benchmarkFlags)
addConfigFlags = mempty { configBenchmarks = toFlag True }
buildFlags' = buildFlags
{ buildVerbosity = benchmarkVerbosity benchmarkFlags }
checkFlags flags
| fromFlagOrDefault False (configBenchmarks flags) = Nothing
| otherwise = Just "Re-configuring with benchmarks enabled."
noAddSource = fromFlagOrDefault DontSkipAddSourceDepsCheck
(buildOnly buildExFlags)
-- reconfigure also checks if we're in a sandbox and reinstalls add-source
-- deps if needed.
(useSandbox, config, distPref) <-
reconfigure verbosity (benchmarkDistPref benchmarkFlags)
addConfigFlags [] globalFlags noAddSource
(buildNumJobs buildFlags') checkFlags
let setupOptions = defaultSetupScriptOptions { useDistPref = distPref }
benchmarkFlags'= benchmarkFlags { benchmarkDistPref = toFlag distPref }
-- the package was just configured, so the LBI must be available
lbi <- getPersistBuildConfig distPref
let pkgDescr = LBI.localPkgDescr lbi
nameBenchsOnly =
LBI.foldComponent
(const Nothing)
(const Nothing)
(const Nothing)
(\b ->
if buildable (benchmarkBuildInfo b)
then Just (benchmarkName b)
else Nothing)
benchs = mapMaybe nameBenchsOnly $ LBI.pkgComponents pkgDescr
extraArgs'
| null extraArgs = benchs
| otherwise = extraArgs
if null benchs
then notice verbosity "Package has no buildable benchmarks."
else do
maybeWithSandboxDirOnSearchPath useSandbox $
build verbosity config distPref buildFlags' extraArgs'
maybeWithSandboxDirOnSearchPath useSandbox $
setupWrapper verbosity setupOptions Nothing
Cabal.benchmarkCommand (const benchmarkFlags') extraArgs'
haddockAction :: HaddockFlags -> [String] -> GlobalFlags -> IO ()
haddockAction haddockFlags extraArgs globalFlags = do
let verbosity = fromFlag (haddockVerbosity haddockFlags)
(_useSandbox, config, distPref) <-
reconfigure verbosity (haddockDistPref haddockFlags)
mempty [] globalFlags DontSkipAddSourceDepsCheck
NoFlag (const Nothing)
let haddockFlags' = defaultHaddockFlags `mappend`
savedHaddockFlags config `mappend`
haddockFlags { haddockDistPref = toFlag distPref }
setupScriptOptions = defaultSetupScriptOptions { useDistPref = distPref }
setupWrapper verbosity setupScriptOptions Nothing
haddockCommand (const haddockFlags') extraArgs
cleanAction :: CleanFlags -> [String] -> GlobalFlags -> IO ()
cleanAction cleanFlags extraArgs globalFlags = do
(_, config) <- loadConfigOrSandboxConfig verbosity globalFlags
distPref <- findSavedDistPref config (cleanDistPref cleanFlags)
let setupScriptOptions = defaultSetupScriptOptions
{ useDistPref = distPref
, useWin32CleanHack = True
}
cleanFlags' = cleanFlags { cleanDistPref = toFlag distPref }
setupWrapper verbosity setupScriptOptions Nothing
cleanCommand (const cleanFlags') extraArgs
where
verbosity = fromFlagOrDefault normal (cleanVerbosity cleanFlags)
listAction :: ListFlags -> [String] -> GlobalFlags -> IO ()
listAction listFlags extraArgs globalFlags = do
let verbosity = fromFlag (listVerbosity listFlags)
(_useSandbox, config) <- loadConfigOrSandboxConfig verbosity
(globalFlags { globalRequireSandbox = Flag False })
let configFlags' = savedConfigureFlags config
configFlags = configFlags' {
configPackageDBs = configPackageDBs configFlags'
`mappend` listPackageDBs listFlags
}
globalFlags' = savedGlobalFlags config `mappend` globalFlags
(comp, _, conf) <- configCompilerAux' configFlags
List.list verbosity
(configPackageDB' configFlags)
(globalRepos globalFlags')
comp
conf
listFlags
extraArgs
infoAction :: InfoFlags -> [String] -> GlobalFlags -> IO ()
infoAction infoFlags extraArgs globalFlags = do
let verbosity = fromFlag (infoVerbosity infoFlags)
targets <- readUserTargets verbosity extraArgs
(_useSandbox, config) <- loadConfigOrSandboxConfig verbosity
(globalFlags { globalRequireSandbox = Flag False })
let configFlags' = savedConfigureFlags config
configFlags = configFlags' {
configPackageDBs = configPackageDBs configFlags'
`mappend` infoPackageDBs infoFlags
}
globalFlags' = savedGlobalFlags config `mappend` globalFlags
(comp, _, conf) <- configCompilerAuxEx configFlags
List.info verbosity
(configPackageDB' configFlags)
(globalRepos globalFlags')
comp
conf
globalFlags'
infoFlags
targets
updateAction :: Flag Verbosity -> [String] -> GlobalFlags -> IO ()
updateAction verbosityFlag extraArgs globalFlags = do
unless (null extraArgs) $
die $ "'update' doesn't take any extra arguments: " ++ unwords extraArgs
let verbosity = fromFlag verbosityFlag
(_useSandbox, config) <- loadConfigOrSandboxConfig verbosity
(globalFlags { globalRequireSandbox = Flag False })
let globalFlags' = savedGlobalFlags config `mappend` globalFlags
transport <- configureTransport verbosity (flagToMaybe (globalHttpTransport globalFlags'))
update transport verbosity (globalRepos globalFlags')
upgradeAction :: (ConfigFlags, ConfigExFlags, InstallFlags, HaddockFlags)
-> [String] -> GlobalFlags -> IO ()
upgradeAction _ _ _ = die $
"Use the 'cabal install' command instead of 'cabal upgrade'.\n"
++ "You can install the latest version of a package using 'cabal install'. "
++ "The 'cabal upgrade' command has been removed because people found it "
++ "confusing and it often led to broken packages.\n"
++ "If you want the old upgrade behaviour then use the install command "
++ "with the --upgrade-dependencies flag (but check first with --dry-run "
++ "to see what would happen). This will try to pick the latest versions "
++ "of all dependencies, rather than the usual behaviour of trying to pick "
++ "installed versions of all dependencies. If you do use "
++ "--upgrade-dependencies, it is recommended that you do not upgrade core "
++ "packages (e.g. by using appropriate --constraint= flags)."
fetchAction :: FetchFlags -> [String] -> GlobalFlags -> IO ()
fetchAction fetchFlags extraArgs globalFlags = do
let verbosity = fromFlag (fetchVerbosity fetchFlags)
targets <- readUserTargets verbosity extraArgs
config <- loadConfig verbosity (globalConfigFile globalFlags)
let configFlags = savedConfigureFlags config
globalFlags' = savedGlobalFlags config `mappend` globalFlags
(comp, platform, conf) <- configCompilerAux' configFlags
fetch verbosity
(configPackageDB' configFlags)
(globalRepos globalFlags')
comp platform conf globalFlags' fetchFlags
targets
freezeAction :: FreezeFlags -> [String] -> GlobalFlags -> IO ()
freezeAction freezeFlags _extraArgs globalFlags = do
let verbosity = fromFlag (freezeVerbosity freezeFlags)
(useSandbox, config) <- loadConfigOrSandboxConfig verbosity globalFlags
let configFlags = savedConfigureFlags config
globalFlags' = savedGlobalFlags config `mappend` globalFlags
(comp, platform, conf) <- configCompilerAux' configFlags
maybeWithSandboxPackageInfo verbosity configFlags globalFlags'
comp platform conf useSandbox $ \mSandboxPkgInfo ->
maybeWithSandboxDirOnSearchPath useSandbox $
freeze verbosity
(configPackageDB' configFlags)
(globalRepos globalFlags')
comp platform conf
mSandboxPkgInfo
globalFlags' freezeFlags
uploadAction :: UploadFlags -> [String] -> GlobalFlags -> IO ()
uploadAction uploadFlags extraArgs globalFlags = do
let verbosity = fromFlag (uploadVerbosity uploadFlags)
config <- loadConfig verbosity (globalConfigFile globalFlags)
let uploadFlags' = savedUploadFlags config `mappend` uploadFlags
globalFlags' = savedGlobalFlags config `mappend` globalFlags
tarfiles = extraArgs
checkTarFiles extraArgs
maybe_password <-
case uploadPasswordCmd uploadFlags'
of Flag (xs:xss) -> Just . Password <$>
getProgramInvocationOutput verbosity
(simpleProgramInvocation xs xss)
_ -> pure $ flagToMaybe $ uploadPassword uploadFlags'
transport <- configureTransport verbosity (flagToMaybe (globalHttpTransport globalFlags'))
if fromFlag (uploadCheck uploadFlags')
then Upload.check transport verbosity tarfiles
else upload transport
verbosity
(globalRepos globalFlags')
(flagToMaybe $ uploadUsername uploadFlags')
maybe_password
tarfiles
where
checkTarFiles tarfiles
| null tarfiles
= die "the 'upload' command expects one or more .tar.gz packages."
| not (null otherFiles)
= die $ "the 'upload' command expects only .tar.gz packages: "
++ intercalate ", " otherFiles
| otherwise = sequence_
[ do exists <- doesFileExist tarfile
unless exists $ die $ "file not found: " ++ tarfile
| tarfile <- tarfiles ]
where otherFiles = filter (not . isTarGzFile) tarfiles
isTarGzFile file = case splitExtension file of
(file', ".gz") -> takeExtension file' == ".tar"
_ -> False
checkAction :: Flag Verbosity -> [String] -> GlobalFlags -> IO ()
checkAction verbosityFlag extraArgs _globalFlags = do
unless (null extraArgs) $
die $ "'check' doesn't take any extra arguments: " ++ unwords extraArgs
allOk <- Check.check (fromFlag verbosityFlag)
unless allOk exitFailure
formatAction :: Flag Verbosity -> [String] -> GlobalFlags -> IO ()
formatAction verbosityFlag extraArgs _globalFlags = do
let verbosity = fromFlag verbosityFlag
path <- case extraArgs of
[] -> do cwd <- getCurrentDirectory
tryFindPackageDesc cwd
(p:_) -> return p
pkgDesc <- readPackageDescription verbosity path
-- Uses 'writeFileAtomic' under the hood.
writeGenericPackageDescription path pkgDesc
uninstallAction :: Flag Verbosity -> [String] -> GlobalFlags -> IO ()
uninstallAction _verbosityFlag extraArgs _globalFlags = do
let package = case extraArgs of
p:_ -> p
_ -> "PACKAGE_NAME"
die $ "This version of 'cabal-install' does not support the 'uninstall' operation. "
++ "It will likely be implemented at some point in the future; in the meantime "
++ "you're advised to use either 'ghc-pkg unregister " ++ package ++ "' or "
++ "'cabal sandbox hc-pkg -- unregister " ++ package ++ "'."
sdistAction :: (SDistFlags, SDistExFlags) -> [String] -> GlobalFlags -> IO ()
sdistAction (sdistFlags, sdistExFlags) extraArgs globalFlags = do
unless (null extraArgs) $
die $ "'sdist' doesn't take any extra arguments: " ++ unwords extraArgs
let verbosity = fromFlag (sDistVerbosity sdistFlags)
(_, config) <- loadConfigOrSandboxConfig verbosity globalFlags
distPref <- findSavedDistPref config (sDistDistPref sdistFlags)
let sdistFlags' = sdistFlags { sDistDistPref = toFlag distPref }
sdist sdistFlags' sdistExFlags
reportAction :: ReportFlags -> [String] -> GlobalFlags -> IO ()
reportAction reportFlags extraArgs globalFlags = do
unless (null extraArgs) $
die $ "'report' doesn't take any extra arguments: " ++ unwords extraArgs
let verbosity = fromFlag (reportVerbosity reportFlags)
config <- loadConfig verbosity (globalConfigFile globalFlags)
let globalFlags' = savedGlobalFlags config `mappend` globalFlags
reportFlags' = savedReportFlags config `mappend` reportFlags
Upload.report verbosity (globalRepos globalFlags')
(flagToMaybe $ reportUsername reportFlags')
(flagToMaybe $ reportPassword reportFlags')
runAction :: (BuildFlags, BuildExFlags) -> [String] -> GlobalFlags -> IO ()
runAction (buildFlags, buildExFlags) extraArgs globalFlags = do
let verbosity = fromFlagOrDefault normal (buildVerbosity buildFlags)
let noAddSource = fromFlagOrDefault DontSkipAddSourceDepsCheck
(buildOnly buildExFlags)
-- reconfigure also checks if we're in a sandbox and reinstalls add-source
-- deps if needed.
(useSandbox, config, distPref) <-
reconfigure verbosity (buildDistPref buildFlags) mempty []
globalFlags noAddSource (buildNumJobs buildFlags)
(const Nothing)
lbi <- getPersistBuildConfig distPref
(exe, exeArgs) <- splitRunArgs verbosity lbi extraArgs
maybeWithSandboxDirOnSearchPath useSandbox $
build verbosity config distPref buildFlags ["exe:" ++ exeName exe]
maybeWithSandboxDirOnSearchPath useSandbox $
run verbosity lbi exe exeArgs
getAction :: GetFlags -> [String] -> GlobalFlags -> IO ()
getAction getFlags extraArgs globalFlags = do
let verbosity = fromFlag (getVerbosity getFlags)
targets <- readUserTargets verbosity extraArgs
(_useSandbox, config) <- loadConfigOrSandboxConfig verbosity
(globalFlags { globalRequireSandbox = Flag False })
let globalFlags' = savedGlobalFlags config `mappend` globalFlags
get verbosity
(globalRepos (savedGlobalFlags config))
globalFlags'
getFlags
targets
unpackAction :: GetFlags -> [String] -> GlobalFlags -> IO ()
unpackAction getFlags extraArgs globalFlags = do
getAction getFlags extraArgs globalFlags
initAction :: InitFlags -> [String] -> GlobalFlags -> IO ()
initAction initFlags _extraArgs globalFlags = do
let verbosity = fromFlag (initVerbosity initFlags)
(_useSandbox, config) <- loadConfigOrSandboxConfig verbosity
(globalFlags { globalRequireSandbox = Flag False })
let configFlags = savedConfigureFlags config
let globalFlags' = savedGlobalFlags config `mappend` globalFlags
(comp, _, conf) <- configCompilerAux' configFlags
initCabal verbosity
(configPackageDB' configFlags)
(globalRepos globalFlags')
comp
conf
initFlags
sandboxAction :: SandboxFlags -> [String] -> GlobalFlags -> IO ()
sandboxAction sandboxFlags extraArgs globalFlags = do
let verbosity = fromFlag (sandboxVerbosity sandboxFlags)
case extraArgs of
-- Basic sandbox commands.
["init"] -> sandboxInit verbosity sandboxFlags globalFlags
["delete"] -> sandboxDelete verbosity sandboxFlags globalFlags
("add-source":extra) -> do
when (noExtraArgs extra) $
die "The 'sandbox add-source' command expects at least one argument"
sandboxAddSource verbosity extra sandboxFlags globalFlags
("delete-source":extra) -> do
when (noExtraArgs extra) $
die ("The 'sandbox delete-source' command expects " ++
"at least one argument")
sandboxDeleteSource verbosity extra sandboxFlags globalFlags
["list-sources"] -> sandboxListSources verbosity sandboxFlags globalFlags
-- More advanced commands.
("hc-pkg":extra) -> do
when (noExtraArgs extra) $
die $ "The 'sandbox hc-pkg' command expects at least one argument"
sandboxHcPkg verbosity sandboxFlags globalFlags extra
["buildopts"] -> die "Not implemented!"
-- Hidden commands.
["dump-pkgenv"] -> dumpPackageEnvironment verbosity sandboxFlags globalFlags
-- Error handling.
[] -> die $ "Please specify a subcommand (see 'help sandbox')"
_ -> die $ "Unknown 'sandbox' subcommand: " ++ unwords extraArgs
where
noExtraArgs = (<1) . length
execAction :: ExecFlags -> [String] -> GlobalFlags -> IO ()
execAction execFlags extraArgs globalFlags = do
let verbosity = fromFlag (execVerbosity execFlags)
(useSandbox, config) <- loadConfigOrSandboxConfig verbosity globalFlags
let configFlags = savedConfigureFlags config
(comp, platform, conf) <- getPersistOrConfigCompiler configFlags
exec verbosity useSandbox comp platform conf extraArgs
userConfigAction :: UserConfigFlags -> [String] -> GlobalFlags -> IO ()
userConfigAction ucflags extraArgs globalFlags = do
let verbosity = fromFlag (userConfigVerbosity ucflags)
case extraArgs of
("diff":_) -> mapM_ putStrLn =<< userConfigDiff globalFlags
("update":_) -> userConfigUpdate verbosity globalFlags
-- Error handling.
[] -> die $ "Please specify a subcommand (see 'help user-config')"
_ -> die $ "Unknown 'user-config' subcommand: " ++ unwords extraArgs
-- | See 'Distribution.Client.Install.withWin32SelfUpgrade' for details.
--
win32SelfUpgradeAction :: Win32SelfUpgradeFlags -> [String] -> GlobalFlags
-> IO ()
win32SelfUpgradeAction selfUpgradeFlags (pid:path:_extraArgs) _globalFlags = do
let verbosity = fromFlag (win32SelfUpgradeVerbosity selfUpgradeFlags)
Win32SelfUpgrade.deleteOldExeFile verbosity (read pid) path
win32SelfUpgradeAction _ _ _ = return ()
-- | Used as an entry point when cabal-install needs to invoke itself
-- as a setup script. This can happen e.g. when doing parallel builds.
--
actAsSetupAction :: ActAsSetupFlags -> [String] -> GlobalFlags -> IO ()
actAsSetupAction actAsSetupFlags args _globalFlags =
let bt = fromFlag (actAsSetupBuildType actAsSetupFlags)
in case bt of
Simple -> Simple.defaultMainArgs args
Configure -> Simple.defaultMainWithHooksArgs
Simple.autoconfUserHooks args
Make -> Make.defaultMainArgs args
Custom -> error "actAsSetupAction Custom"
(UnknownBuildType _) -> error "actAsSetupAction UnknownBuildType"
|
mmakowski/cabal
|
cabal-install/Main.hs
|
bsd-3-clause
| 55,596 | 0 | 24 | 15,404 | 9,943 | 5,227 | 4,716 | 898 | 13 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- Module : Network.AWS.CloudSearch.DefineExpression
-- Copyright : (c) 2013-2014 Brendan Hay <[email protected]>
-- License : This Source Code Form is subject to the terms of
-- the Mozilla Public License, v. 2.0.
-- A copy of the MPL can be found in the LICENSE file or
-- you can obtain it at http://mozilla.org/MPL/2.0/.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : experimental
-- Portability : non-portable (GHC extensions)
--
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- | Configures an ''Expression' for the search domain. Used to create new
-- expressions and modify existing ones. If the expression exists, the new
-- configuration replaces the old one. For more information, see Configuring
-- Expressions in the /Amazon CloudSearch Developer Guide/.
--
-- <http://docs.aws.amazon.com/cloudsearch/latest/developerguide/API_DefineExpression.html>
module Network.AWS.CloudSearch.DefineExpression
(
-- * Request
DefineExpression
-- ** Request constructor
, defineExpression
-- ** Request lenses
, de1DomainName
, de1Expression
-- * Response
, DefineExpressionResponse
-- ** Response constructor
, defineExpressionResponse
-- ** Response lenses
, derExpression
) where
import Network.AWS.Prelude
import Network.AWS.Request.Query
import Network.AWS.CloudSearch.Types
import qualified GHC.Exts
data DefineExpression = DefineExpression
{ _de1DomainName :: Text
, _de1Expression :: Expression
} deriving (Eq, Read, Show)
-- | 'DefineExpression' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'de1DomainName' @::@ 'Text'
--
-- * 'de1Expression' @::@ 'Expression'
--
defineExpression :: Text -- ^ 'de1DomainName'
-> Expression -- ^ 'de1Expression'
-> DefineExpression
defineExpression p1 p2 = DefineExpression
{ _de1DomainName = p1
, _de1Expression = p2
}
de1DomainName :: Lens' DefineExpression Text
de1DomainName = lens _de1DomainName (\s a -> s { _de1DomainName = a })
de1Expression :: Lens' DefineExpression Expression
de1Expression = lens _de1Expression (\s a -> s { _de1Expression = a })
newtype DefineExpressionResponse = DefineExpressionResponse
{ _derExpression :: ExpressionStatus
} deriving (Eq, Read, Show)
-- | 'DefineExpressionResponse' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'derExpression' @::@ 'ExpressionStatus'
--
defineExpressionResponse :: ExpressionStatus -- ^ 'derExpression'
-> DefineExpressionResponse
defineExpressionResponse p1 = DefineExpressionResponse
{ _derExpression = p1
}
derExpression :: Lens' DefineExpressionResponse ExpressionStatus
derExpression = lens _derExpression (\s a -> s { _derExpression = a })
instance ToPath DefineExpression where
toPath = const "/"
instance ToQuery DefineExpression where
toQuery DefineExpression{..} = mconcat
[ "DomainName" =? _de1DomainName
, "Expression" =? _de1Expression
]
instance ToHeaders DefineExpression
instance AWSRequest DefineExpression where
type Sv DefineExpression = CloudSearch
type Rs DefineExpression = DefineExpressionResponse
request = post "DefineExpression"
response = xmlResponse
instance FromXML DefineExpressionResponse where
parseXML = withElement "DefineExpressionResult" $ \x -> DefineExpressionResponse
<$> x .@ "Expression"
|
romanb/amazonka
|
amazonka-cloudsearch/gen/Network/AWS/CloudSearch/DefineExpression.hs
|
mpl-2.0
| 4,010 | 0 | 9 | 859 | 481 | 294 | 187 | 61 | 1 |
{-# LANGUAGE FlexibleInstances, MultiParamTypeClasses #-}
-----------------------------------------------------------------------------
-- |
-- Module : XMonad.Layout.Spacing
-- Copyright : (c) Brent Yorgey
-- License : BSD-style (see LICENSE)
--
-- Maintainer : <[email protected]>
-- Stability : unstable
-- Portability : portable
--
-- Add a configurable amount of space around windows.
-----------------------------------------------------------------------------
module XMonad.Layout.Spacing (
-- * Usage
-- $usage
spacing, Spacing,
smartSpacing, SmartSpacing,
) where
import Graphics.X11 (Rectangle(..))
import Control.Arrow (second)
import XMonad.Util.Font (fi)
import XMonad.Layout.LayoutModifier
-- $usage
-- You can use this module by importing it into your @~\/.xmonad\/xmonad.hs@ file:
--
-- > import XMonad.Layout.Spacing
--
-- and modifying your layoutHook as follows (for example):
--
-- > layoutHook = spacing 2 $ Tall 1 (3/100) (1/2)
-- > -- put a 2px space around every window
--
-- | Surround all windows by a certain number of pixels of blank space.
spacing :: Int -> l a -> ModifiedLayout Spacing l a
spacing p = ModifiedLayout (Spacing p)
data Spacing a = Spacing Int deriving (Show, Read)
instance LayoutModifier Spacing a where
pureModifier (Spacing p) _ _ wrs = (map (second $ shrinkRect p) wrs, Nothing)
modifierDescription (Spacing p) = "Spacing " ++ show p
shrinkRect :: Int -> Rectangle -> Rectangle
shrinkRect p (Rectangle x y w h) = Rectangle (x+fi p) (y+fi p) (w-2*fi p) (h-2*fi p)
-- | Surrounds all windows with blank space, except when the window is the only
-- visible window on the current workspace.
smartSpacing :: Int -> l a -> ModifiedLayout SmartSpacing l a
smartSpacing p = ModifiedLayout (SmartSpacing p)
data SmartSpacing a = SmartSpacing Int deriving (Show, Read)
instance LayoutModifier SmartSpacing a where
pureModifier _ _ _ [x] = ([x], Nothing)
pureModifier (SmartSpacing p) _ _ wrs = (map (second $ shrinkRect p) wrs, Nothing)
modifierDescription (SmartSpacing p) = "SmartSpacing " ++ show p
|
markus1189/xmonad-contrib-710
|
XMonad/Layout/Spacing.hs
|
bsd-3-clause
| 2,275 | 0 | 10 | 534 | 475 | 264 | 211 | 23 | 1 |
module C1
(Tree, leaf1, branch1, branch2, isLeaf, isBranch,
mkLeaf, mkBranch, myFringe, SameOrNot(..))
where
data Tree a
= Leaf {leaf1 :: a}
| Branch {branch1 :: Tree a, branch2 :: Tree a}
mkLeaf :: a -> Tree a
mkLeaf = Leaf
mkBranch :: (Tree a) -> (Tree a) -> Tree a
mkBranch = Branch
isLeaf :: (Tree a) -> Bool
isLeaf (Leaf _) = True
isLeaf _ = False
isBranch :: (Tree a) -> Bool
isBranch (Branch _ _) = True
isBranch _ = False
sumTree :: Num a => (Tree a) -> a
sumTree p | isLeaf p = (leaf1 p)
sumTree p
| isBranch p =
(sumTree (branch1 p)) + (sumTree (branch2 p))
myFringe :: (Tree a) -> [a]
myFringe p | isLeaf p = [(leaf1 p)]
myFringe p | isBranch p = myFringe (branch1 p)
class SameOrNot a
where
isSame :: a -> a -> Bool
isNotSame :: a -> a -> Bool
instance SameOrNot Int
where
isSame a b = a == b
isNotSame a b = a /= b
|
SAdams601/HaRe
|
old/testing/fromConcreteToAbstract/C1_AstOut.hs
|
bsd-3-clause
| 958 | 2 | 10 | 303 | 438 | 227 | 211 | 30 | 1 |
-----------------------------------------------------------------------------
-- |
-- Module : Distribution.Simple.GHC.IPI641
-- Copyright : (c) The University of Glasgow 2004
-- License : BSD3
--
-- Maintainer : [email protected]
-- Portability : portable
--
module Distribution.Simple.GHC.IPI641 (
InstalledPackageInfo(..),
toCurrent,
) where
import qualified Distribution.InstalledPackageInfo as Current
import qualified Distribution.Package as Current hiding (installedComponentId)
import Distribution.Text (display)
import Distribution.Simple.GHC.IPI642
( PackageIdentifier, convertPackageId
, License, convertLicense, convertModuleName )
-- | This is the InstalledPackageInfo type used by ghc-6.4 and 6.4.1.
--
-- It's here purely for the 'Read' instance so that we can read the package
-- database used by those ghc versions. It is a little hacky to read the
-- package db directly, but we do need the info and until ghc-6.9 there was
-- no better method.
--
-- In ghc-6.4.2 the format changed a bit. See "Distribution.Simple.GHC.IPI642"
--
data InstalledPackageInfo = InstalledPackageInfo {
package :: PackageIdentifier,
license :: License,
copyright :: String,
maintainer :: String,
author :: String,
stability :: String,
homepage :: String,
pkgUrl :: String,
description :: String,
category :: String,
exposed :: Bool,
exposedModules :: [String],
hiddenModules :: [String],
importDirs :: [FilePath],
libraryDirs :: [FilePath],
hsLibraries :: [String],
extraLibraries :: [String],
includeDirs :: [FilePath],
includes :: [String],
depends :: [PackageIdentifier],
hugsOptions :: [String],
ccOptions :: [String],
ldOptions :: [String],
frameworkDirs :: [FilePath],
frameworks :: [String],
haddockInterfaces :: [FilePath],
haddockHTMLs :: [FilePath]
}
deriving Read
mkComponentId :: Current.PackageIdentifier -> Current.ComponentId
mkComponentId = Current.ComponentId . display
toCurrent :: InstalledPackageInfo -> Current.InstalledPackageInfo
toCurrent ipi@InstalledPackageInfo{} =
let pid = convertPackageId (package ipi)
mkExposedModule m = Current.ExposedModule m Nothing Nothing
in Current.InstalledPackageInfo {
Current.sourcePackageId = pid,
Current.installedComponentId = mkComponentId pid,
Current.compatPackageKey = mkComponentId pid,
Current.license = convertLicense (license ipi),
Current.copyright = copyright ipi,
Current.maintainer = maintainer ipi,
Current.author = author ipi,
Current.stability = stability ipi,
Current.homepage = homepage ipi,
Current.pkgUrl = pkgUrl ipi,
Current.synopsis = "",
Current.description = description ipi,
Current.category = category ipi,
Current.abiHash = Current.AbiHash "",
Current.exposed = exposed ipi,
Current.exposedModules = map (mkExposedModule . convertModuleName) (exposedModules ipi),
Current.instantiatedWith = [],
Current.hiddenModules = map convertModuleName (hiddenModules ipi),
Current.trusted = Current.trusted Current.emptyInstalledPackageInfo,
Current.importDirs = importDirs ipi,
Current.libraryDirs = libraryDirs ipi,
Current.dataDir = "",
Current.hsLibraries = hsLibraries ipi,
Current.extraLibraries = extraLibraries ipi,
Current.extraGHCiLibraries = [],
Current.includeDirs = includeDirs ipi,
Current.includes = includes ipi,
Current.depends = map (mkComponentId.convertPackageId) (depends ipi),
Current.ccOptions = ccOptions ipi,
Current.ldOptions = ldOptions ipi,
Current.frameworkDirs = frameworkDirs ipi,
Current.frameworks = frameworks ipi,
Current.haddockInterfaces = haddockInterfaces ipi,
Current.haddockHTMLs = haddockHTMLs ipi,
Current.pkgRoot = Nothing
}
|
randen/cabal
|
Cabal/Distribution/Simple/GHC/IPI641.hs
|
bsd-3-clause
| 4,324 | 0 | 11 | 1,178 | 827 | 495 | 332 | 80 | 1 |
module Foo1 where
-- Variant: ill-kinded.
class XClass a where
xFun :: a -> XData
data XData = XCon XClass
|
urbanslug/ghc
|
testsuite/tests/typecheck/should_fail/tcfail147.hs
|
bsd-3-clause
| 119 | 0 | 7 | 32 | 32 | 18 | 14 | 4 | 0 |
{-# LANGUAGE PatternSynonyms #-}
{-# LANGUAGE DataKinds #-}
pattern PATTERN = ()
wrongLift :: PATTERN
wrongLift = undefined
|
hferreiro/replay
|
testsuite/tests/patsyn/should_fail/T9161-1.hs
|
bsd-3-clause
| 126 | 0 | 6 | 20 | 23 | 13 | 10 | 5 | 1 |
{-# LANGUAGE ForeignFunctionInterface, JavaScriptFFI #-}
module GHCJS.DOM.JSFFI.Database (
module Generated
, js_changeVersion
, changeVersion'
, changeVersion
, js_transaction
, transaction'
, transaction
, js_readTransaction
, readTransaction'
, readTransaction
) where
import Data.Maybe (fromJust, maybe)
import Control.Monad.IO.Class (MonadIO(..))
import Control.Exception (Exception, bracket)
import GHCJS.Types (JSVal, JSString)
import GHCJS.Foreign (jsNull)
import GHCJS.Foreign.Callback (OnBlocked(..))
import GHCJS.Marshal (fromJSVal)
import GHCJS.Marshal.Pure (pToJSVal)
import GHCJS.Foreign.Callback (releaseCallback)
import GHCJS.DOM.Types
import GHCJS.DOM.JSFFI.SQLError (throwSQLException)
import GHCJS.DOM.JSFFI.Generated.SQLTransactionCallback (newSQLTransactionCallbackSync)
import GHCJS.DOM.JSFFI.Generated.Database as Generated hiding (js_changeVersion, changeVersion, js_transaction, transaction, js_readTransaction, readTransaction)
withSQLTransactionCallback :: (SQLTransaction -> IO ()) -> (SQLTransactionCallback -> IO a) -> IO a
withSQLTransactionCallback f = bracket (newSQLTransactionCallbackSync (f . fromJust)) (\(SQLTransactionCallback c) -> releaseCallback c)
foreign import javascript interruptible
"$1[\"changeVersion\"]($2, $3, $4, $c, function() { $c(null); });"
js_changeVersion :: Database -> JSString -> JSString -> Nullable SQLTransactionCallback -> IO (Nullable SQLError)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/Database.changeVersion Mozilla Database.changeVersion documentation>
changeVersion' :: (MonadIO m, ToJSString oldVersion, ToJSString newVersion) =>
Database -> oldVersion -> newVersion -> Maybe (SQLTransaction -> IO ()) -> m (Maybe SQLError)
changeVersion' self oldVersion newVersion Nothing = liftIO $ nullableToMaybe <$>
js_changeVersion self (toJSString oldVersion) (toJSString newVersion) (Nullable jsNull)
changeVersion' self oldVersion newVersion (Just callback) = liftIO $ nullableToMaybe <$>
withSQLTransactionCallback callback
(js_changeVersion self (toJSString oldVersion) (toJSString newVersion) . Nullable . pToJSVal)
changeVersion :: (MonadIO m, ToJSString oldVersion, ToJSString newVersion) =>
Database -> oldVersion -> newVersion -> Maybe (SQLTransaction -> IO ()) -> m ()
changeVersion self oldVersion newVersion callback =
changeVersion' self oldVersion newVersion callback >>= maybe (return ()) throwSQLException
foreign import javascript interruptible "$1[\"transaction\"]($2, $c, function() { $c(null); });"
js_transaction :: Database -> SQLTransactionCallback -> IO (Nullable SQLError)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/Database.transaction Mozilla Database.transaction documentation>
transaction' :: (MonadIO m) => Database -> (SQLTransaction -> IO ()) -> m (Maybe SQLError)
transaction' self callback = liftIO $ nullableToMaybe <$>
withSQLTransactionCallback callback
(js_transaction self)
transaction :: (MonadIO m) => Database -> (SQLTransaction -> IO ()) -> m ()
transaction self callback = transaction' self callback >>= maybe (return ()) throwSQLException
foreign import javascript interruptible
"$1[\"readTransaction\"]($2, $c, function() { $c(null); });"
js_readTransaction :: Database -> SQLTransactionCallback -> IO (Nullable SQLError)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/Database.readTransaction Mozilla Database.readTransaction documentation>
readTransaction' :: (MonadIO m) => Database -> (SQLTransaction -> IO ()) -> m (Maybe SQLError)
readTransaction' self callback = liftIO $ nullableToMaybe <$>
withSQLTransactionCallback callback (js_readTransaction self)
readTransaction :: (MonadIO m) => Database -> (SQLTransaction -> IO ()) -> m ()
readTransaction self callback = readTransaction' self callback >>= maybe (return ()) throwSQLException
|
manyoo/ghcjs-dom
|
ghcjs-dom-jsffi/src/GHCJS/DOM/JSFFI/Database.hs
|
mit
| 3,935 | 28 | 14 | 547 | 971 | 520 | 451 | -1 | -1 |
module Main where
import Control.Applicative
import Control.Concurrent.Suspend
import Control.Exception
import Control.Monad
import Data.Int (Int64)
import Data.List (intersperse)
import Options
import Text.Printf
import Sound.ALUT
import System.Console.ANSI
import System.Console.Readline
import System.Exit (exitFailure)
import System.IO
main = do
-- Initialise ALUT and eat any ALUT-specific commandline flags.
withProgNameAndArgs runALUT $ \progName args -> do
runCommand $ \opts args -> runMenuLoop opts
data MainOptions = MainOptions { optAlarm :: FilePath
, optPomodoro :: Int64
, optShortBreak :: Int64
, optLongBreak :: Int64
} deriving (Show, Eq, Ord)
instance Options MainOptions where
defineOptions = pure MainOptions
<*> simpleOption "alarm" "./audio/alarm.wav"
"Path to alarm sound file"
<*> simpleOption "pomodoro" 25
"Pomodoro length"
<*> simpleOption "shortBreak" 5
"Short break length"
<*> simpleOption "longBreak" 20
"Long break length"
data UserChoice = StartPomodoro
| StartShortBreak
| StartLongBreak
| Settings
| Exit
| UnknownChoice
deriving (Show)
------------------------------------------------------------
-- Runs inifinite loop and waits for user input
------------------------------------------------------------
runMenuLoop :: MainOptions -> IO ()
runMenuLoop opts = runMenu
where runMenu :: IO ()
runMenu = do
clearScreen
choice <- getMenuChoice
case choice of
StartPomodoro -> (startPomodoro (pomodoro * 60) fileName) >> runMenu
StartShortBreak -> (startShortBreak (shortBreak * 60) fileName) >> runMenu
StartLongBreak -> (startLongBreak (longBreak * 60) fileName) >> runMenu
Exit -> return ()
otherwise -> runMenu
fileName = optAlarm opts
pomodoro = optPomodoro opts
shortBreak = optShortBreak opts
longBreak = optLongBreak opts
------------------------------------------------------------
-- Draws menu and waits for user input
------------------------------------------------------------
getMenuChoice :: IO UserChoice
getMenuChoice = do
putStrLn "##############################"
putStrLn "####### Pomodoro Timer #######"
putStrLn "##############################"
putStrLn "# 1 - Start pomodoro timer #"
putStrLn "# 2 - Start short break #"
putStrLn "# 3 - Start long break #"
putStrLn "# 4 - Exit #"
putStrLn "##############################"
maybeLine <- readline "λ> "
case maybeLine of
Nothing -> return Exit
Just "exit" -> return Exit
Just line -> parseChoice line
------------------------------------------------------------
-- Tries to match user input to the one of main menu item.
-- Returns `UnknownChoice` if fails.
------------------------------------------------------------
parseChoice :: String -> IO UserChoice
parseChoice s =
handle handler (return $ (read s :: UserChoice))
where
handler :: NonTermination -> IO UserChoice
handler e = return UnknownChoice
startPomodoro :: Int64 -> FilePath -> IO ()
startPomodoro s fileName = do
putStrLn "Pomodoro started"
startTimer s
playFile fileName 5
putStrLn "Pomodoro finished!"
startLongBreak :: Int64 -> FilePath -> IO ()
startLongBreak s fileName = do
putStrLn "Long break started"
startTimer s
playFile fileName 5
putStrLn "Long break finished!"
startShortBreak :: Int64 -> FilePath -> IO ()
startShortBreak s fileName = do
putStrLn "Short break started"
startTimer s
playFile fileName 5
putStrLn "Short break finished!"
startTimer :: Int64 -> IO ()
startTimer s = do runTimer $ s * 1000
where runTimer :: Int64 -> IO ()
runTimer ms =
if ms > 0 then
do clearLine
putStrLn $ formatTime ms
cursorUpLine 1
suspend $ msDelay tick
runTimer $ ms - tick
else do putStrLn ""
return ()
tick = 1000 :: Int64
formatTime :: Int64 -> String
formatTime ms = let ss = ms `div` 1000
mm = ss `div` 60
in printf "%02d:%02d" mm (ss - mm * 60)
------------------------------------------------------------
-- Plays sound from file during `s` seconds.
------------------------------------------------------------
playFile :: FilePath -> Float -> IO ()
playFile fileName s = do
-- Create an AL buffer from the given sound file.
buf <- createBuffer (File fileName)
-- Generate a single source, attach the buffer to it and start playing.
source <- genObjectName
buffer source $= Just buf
play [source]
-- Normally nothing should go wrong above, but one never knows...
errs <- get alErrors
unless (null errs) $ do
hPutStrLn stderr (concat (intersperse "," [ d | ALError _ d <- errs ]))
exitFailure
sleep s
stop [source]
instance Read UserChoice where
readsPrec _ v =
case v of
'1':xs -> [(StartPomodoro, xs)]
'2':xs -> [(StartShortBreak, xs)]
'3':xs -> [(StartLongBreak, xs)]
'4':xs -> [(Exit, xs)]
otherwise -> [(UnknownChoice, "")]
|
AZaviruha/pomodoro-cli
|
src/Main.hs
|
mit
| 5,818 | 0 | 18 | 1,854 | 1,259 | 628 | 631 | 130 | 5 |
import Data.List.Split
import qualified Data.Map as Map
data Direction
= N
| E
| S
| W
deriving (Show, Ord, Eq)
turnMap =
Map.fromList $
[ ((dirs !! i, 'L'), dirs !! ((i - 1) `mod` 4))
| i <- [0 .. 3] ] ++
[ ((dirs !! i, 'R'), dirs !! ((i + 1) `mod` 4))
| i <- [0 .. 3] ]
where
dirs = [N, E, S, W]
move facing x y [] = (x, y)
move facing x y ((turn, numSteps):ss)
| facing' == N = move facing' (x + numSteps) y ss
| facing' == S = move facing' (x - numSteps) y ss
| facing' == E = move facing' x (y + numSteps) ss
| facing' == W = move facing' x (y - numSteps) ss
where
facing' = turnMap Map.! (facing, turn)
parseStep :: String -> (Char, Integer)
parseStep (turn:numSteps) = (turn, read numSteps)
main = do
line <- getLine
let steps = map parseStep $ splitOn ", " line
let (x, y) = move N 0 0 steps
print $ abs x + abs y
|
lzlarryli/advent_of_code_2016
|
day1/part1.hs
|
mit
| 875 | 0 | 13 | 237 | 481 | 260 | 221 | 29 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Persistence.DBConnection
( loadConnection
) where
import Control.Applicative
import Control.Monad
import Data.Aeson
import qualified Data.ByteString.Lazy.Char8 as BSL
import Database.PostgreSQL.Simple
instance FromJSON ConnectInfo where
parseJSON (Object v) = ConnectInfo
<$> v .: "host"
<*> v .: "port"
<*> v .: "user"
<*> v .: "password"
<*> v .: "dbname"
parseJSON _ = mzero
loadConnection :: String -> IO (Either String ConnectInfo)
loadConnection file = eitherDecode <$> BSL.readFile file
|
ostapneko/stld2
|
src/main/Persistence/DBConnection.hs
|
mit
| 761 | 0 | 15 | 262 | 151 | 83 | 68 | 19 | 1 |
module Group where
import Data.List
import Data.Maybe
import GroupUtils
{-
Types
-}
type BinOp a = (a -> a -> a)
type MTable a = ([a], [[a]])
data Group a = Group { set :: [a], op :: (BinOp a) }
data GAction a b = GAction (Group a) [b] (a -> b -> b)
instance (Show a, Eq a) => Show (Group a) where
show (Group s f) =
"G = {\n" ++ tableToString (groupToTable (Group s f)) 6 ++ " }"
instance (Show a, Show b, Eq a, Eq b) => Show (GAction a b) where
show (GAction g xs p) = "Action = {\n\n " ++ show xs ++ "\n\n G = {\n" ++
tableToString (groupToTable g) 8 ++ " }\n}"
{-
Construction
-}
isValidGroup :: Eq a => Group a -> Bool
isValidGroup (Group s f) = formsGroup s f
constructGroup :: Eq a => [a] -> BinOp a -> Maybe (Group a)
constructGroup s f | formsGroup s f = Just (Group s f)
| otherwise = Nothing
isValidAction :: (Eq a, Eq b) => GAction a b -> Bool
isValidAction (GAction g xs p) = formsAction g xs p
constructAction :: (Eq a, Eq b) => Group a -> [b] -> (a -> b -> b) ->
Maybe (GAction a b)
constructAction g xs p | formsAction g xs p = Just (GAction g xs p)
| otherwise = Nothing
{-
Basics
-}
one :: Eq a => Group a -> a
one (Group s f) = fromJust (one_ s f)
inv :: Eq a => Group a -> a -> a
inv (Group s f) x = fromJust $ inv_ s f x
-- | b = xax^-1
conj :: Eq a => Group a -> a -> a -> a
conj (Group s f) a x = f x (f a (inv (Group s f) x))
-- | Y = xAx^-1
conjs :: Eq a => Group a -> [a] -> a -> [a]
conjs g as x = [conj g a x | a <- as]
conjg :: Eq a => Group a -> a -> [a]
conjg g x = conjs g (set g) x
order :: Eq a => Group a -> Int
order (Group s f) = length s
elemOrder :: Eq a => Group a -> a -> Int
elemOrder (Group s f) x = go (Group s f) x 1
where go (Group s f) y acc
| y == e = acc
| otherwise = go (Group s f) (f y x) (acc + 1)
e = one (Group s f)
isAbelian :: Eq a => Group a -> Bool
isAbelian g = tab == tab'
where tab = snd (groupToTable g)
tab' = [[l !! i | l <- tab] | i <- [0..length (head tab) - 1]]
isCyclic :: Eq a => Group a -> Bool
isCyclic (Group s f) = go s f
where go [] f = False
go (x : xs) f | elemOrder (Group s f) x == o = True
| otherwise = go xs f
o = order (Group s f)
{-
Generating
-}
minimalGenerator :: Eq a => Group a -> [a]
minimalGenerator g = head $ minimalGeneratingSets g
minimalGeneratingSets :: Eq a => Group a -> [[a]]
minimalGeneratingSets (Group s f) = go 1
where go l | not (null (gener l)) = gener l
| otherwise = go (l + 1)
gener l = [x | x <- lenSubSets l s,
setEq s (generateFromSet (Group s f) x)]
generateFromSet :: Eq a => Group a -> [a] -> [a]
generateFromSet (Group s f) xs = go xs
where go xs | setEq nextGen xs = xs
| otherwise = go nextGen
where nextGen = takeCrossProduct (Group s f)
(generateFromSetOnce (Group s f) xs)
-- | produces wrong result
generateFromSet2 :: Eq a => Group a -> [a] -> [a]
generateFromSet2 (Group s f) xs = go xs
where go xs | setEq nextGen xs = xs
| otherwise = go nextGen
where nextGen = takeCrossProduct (Group s f) xs
generateFromSetOnce :: Eq a => Group a -> [a] -> [a]
generateFromSetOnce (Group s f) xs =
nub (foldl (++) [] [generateFrom (Group s f) x | x <- xs])
takeCrossProduct :: Eq a => Group a -> [a] -> [a]
takeCrossProduct (Group s f) xs = nub [f x y | x <- xs, y <- xs]
generateFrom :: Eq a => Group a -> a -> [a]
generateFrom (Group s f) x = go x x
where go x y | y == e = [y]
| otherwise = y : go x (f x y)
e = one (Group s f)
{-
Subgroups
-}
subgroups :: Eq a => Group a -> [Group a]
subgroups g = go atoms
where atoms = cyclicSubgroups g
go xs | length xs == length nextGen = nextGen
| otherwise = go nextGen
where nextGen = compoSubgroups g atoms xs
-- | Takes atoms and previous composites and produces cross-product-gen
compoSubgroups :: Eq a => Group a -> [Group a] -> [Group a] -> [Group a]
compoSubgroups g ato comp = nubSubgroups r
where o = order g
unions = (nubSEq [union (set a) (set c) | a <- ato, c <- comp])
constr x | o `mod` length x /= 0 = Nothing
| otherwise = constructGroup x (op g)
r = catMaybes (map constr generated)
where generated = nubSEq (map (generateFromSet g) unions)
-- | Less efficient, generates from whole cross-prod including duplicates
compoSubgroups2 :: Eq a => Group a -> [Group a] -> [Group a] -> [Group a]
compoSubgroups2 g ato comp = catMaybes [subgrp a c | a <- ato, c <- comp]
where subgrp a c | (order g) `mod` (length subg) /= 0 = Nothing
| otherwise = constructGroup subg (op g)
where subg = generateFromSet g (union (set a) (set c))
cyclicSubgroups :: Eq a => Group a -> [Group a]
cyclicSubgroups (Group s f) = nubSubgroups subgrps
where subgrps = map fromJust (
filter isJust
[constructGroup (generateFrom (Group s f) x) f | x <- s])
nubSubgroups :: Eq a => [Group a] -> [Group a]
nubSubgroups subgrps = nubBy (\a b -> setEq (set a) (set b)) subgrps
nubSubgroups2 :: Eq a => [Group a] -> [Group a]
nubSubgroups2 subgrps = go subgrps []
where go [] ys = ys
go (x : xs) ys
| null [z | z <- ys, setEq (set x) (set z)] = go xs (x : ys)
| otherwise = go xs ys
leftCoset :: Eq a => Group a -> a -> [a]
leftCoset (Group s f) g = [f g x | x <- s]
-- | Group -> Subgroup
leftCosets :: Eq a => Group a -> Group a -> [[a]]
leftCosets g h = nubBy setEq [leftCoset h x | x <- (set g)]
rightCoset :: Eq a => Group a -> a -> [a]
rightCoset (Group s f) g = [f x g | x <- s]
rightCosets :: Eq a => Group a -> Group a -> [[a]]
rightCosets g h = nubBy setEq [rightCoset h x | x <- (set g)]
-- | Group -> Subgroup
isNormalSubgroup :: Eq a => Group a -> Group a -> Bool
isNormalSubgroup g h =
null [x | x <- (set g), not $ setEq (leftCoset h x) (rightCoset h x)]
normalSubgroups :: Eq a => Group a -> [Group a]
normalSubgroups g = [h | h <- subgroups g, isNormalSubgroup g h]
centralizer :: Eq a => Group a -> [a] -> Group a
centralizer (Group s f) as =
fromJust $
constructGroup [x | x <- s, null [a | a <- as, a /= conj (Group s f) a x]] f
normalizer :: Eq a => Group a -> [a] -> Group a
normalizer (Group s f) as =
fromJust $ constructGroup [x | x <- s, setEq as (conjs (Group s f) as x)] f
center :: Eq a => Group a -> Group a
center g = centralizer g (set g)
{-
Group action stuff
-}
stabilizer :: (Eq a, Eq b) => GAction a b -> b -> Group a
stabilizer (GAction g xs p) a =
fromJust $ constructGroup [y | y <- (set g), p y a == a] (op g)
kernel :: (Eq a, Eq b) => GAction a b -> Group a
kernel (GAction g xs p) =
fromJust $
constructGroup [y | y <- (set g), null [x | x <- xs, x /= p y x]] (op g)
{-
Isomorphism
-}
areIsomorphic :: (Eq a, Eq b) => Group a -> Group b -> Bool
areIsomorphic g1 g2
| order g1 /= order g2 = False
| not $ setEq (map (elemOrder g1) (set g1)) (map (elemOrder g2) (set g2)) =
False
| otherwise = True
{-
Helper for to-be groups
-}
formsGroup :: Eq a => [a] -> BinOp a -> Bool
formsGroup s f = ckSet && ckOne && ckInv && ckClo && ckAssGen
where ckSet = not $ null s && s == nub s
ckOne = isJust (one_ s f)
ckInv = length (filter isJust [inv_ s f x | x <- s]) == length s
ckClo = null [x | x <- s, y <- s, not $ f x y `elem` s]
ckAssGen = checkAss (minimalGenerator (Group s f)) f
-- | runs in O(n^3)
checkAss :: Eq a => [a] -> BinOp a -> Bool
checkAss s f = null xs
where xs = [a | a <- s, b <- s, c <- s, f (f a b) c /= f a (f b c)]
formsAction :: (Eq a, Eq b) => Group a -> [b] -> (a -> b -> b) -> Bool
formsAction (Group s f) xs p = ckCo && ckId && ckCl
where ckCo = null [g | g <- s, h <- s, x <- xs, p (f g h) x /= p g (p h x)]
ckId = null [x | x <- xs, p (one (Group s f)) x /= x ]
ckCl = null [x | g <- s, x <- xs, not $ (p g x) `elem` xs]
one_ :: Eq a => [a] -> BinOp a -> Maybe a
one_ s f | null xs = Nothing
| otherwise = Just $ head xs
where xs = [x | x <- s, f x someE == someE]
someE = head s
-- | slower than above
one_2 :: Eq a => [a] -> BinOp a -> Maybe a
one_2 s f | isNothing ind = Nothing
| otherwise = Just (s !! (fromJust ind))
where ind = elemIndex s (snd (groupToTable_ s f))
inv_ :: Eq a => [a] -> BinOp a -> a -> Maybe a
inv_ s f x | isNothing e || not (x `elem` s) = Nothing
| otherwise = find ((== fromJust e) . (f x)) s
where e = one_ s f
groupToTable_ :: Eq a => [a] -> BinOp a -> MTable a
groupToTable_ s f = (s, [[f a b | a <- s] | b <- s])
tableToGroup :: Eq a => MTable a -> Maybe (Group a)
tableToGroup (axis, tab) = constructGroup axis (tableToFunction (axis, tab))
tableToFunction :: Eq a => MTable a -> BinOp a
tableToFunction (axis, tab) = \x y -> (tab !! pos x) !! pos y
where pos x = fromJust $ elemIndex x axis
groupToTable :: Eq a => Group a -> MTable a
groupToTable (Group s f) = groupToTable_ s f
|
elfeck/grouphs
|
src/Group.hs
|
mit
| 9,129 | 0 | 15 | 2,664 | 4,839 | 2,391 | 2,448 | 186 | 2 |
module ByteString.BuildersBenchmark.Inputs where
import Prelude
import qualified ByteString.BuildersBenchmark.Subjects as A
import qualified ByteString.BuildersBenchmark.Actions as B
sized :: Int -> [ByteString]
sized factor =
replicate factor "abcdefg"
|
nikita-volkov/bytestring-builders-benchmark
|
library/ByteString/BuildersBenchmark/Inputs.hs
|
mit
| 259 | 0 | 6 | 31 | 53 | 34 | 19 | 7 | 1 |
-- 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, RecordWildCards #-}
module Language.Bond.Codegen.Cpp.Apply_h (apply_h) where
import System.FilePath
import Prelude
import Data.Text.Lazy (Text)
import Text.Shakespeare.Text
import Language.Bond.Syntax.Types
import Language.Bond.Util
import Language.Bond.Codegen.Util
import Language.Bond.Codegen.TypeMapping
import Language.Bond.Codegen.Cpp.ApplyOverloads
import qualified Language.Bond.Codegen.Cpp.Util as CPP
-- | Codegen template for generating /base_name/_apply.h containing declarations of
-- <https://microsoft.github.io/bond/manual/bond_cpp.html#optimizing-build-time Apply>
-- function overloads for the specified protocols.
apply_h :: [Protocol] -- ^ List of protocols for which @Apply@ overloads should be generated
-> Maybe String -- ^ Optional attribute to decorate function declarations
-> MappingContext -> String -> [Import] -> [Declaration] -> (String, Text)
apply_h protocols attribute cpp file imports declarations = ("_apply.h", [lt|
#pragma once
#include "#{file}_types.h"
#include <bond/core/bond.h>
#include <bond/stream/output_buffer.h>
#{newlineSep 0 includeImport imports}
#{CPP.openNamespace cpp}
#{newlineSepEnd 1 (applyOverloads protocols attr semi) declarations}
#{CPP.closeNamespace cpp}
|])
where
includeImport (Import path) = [lt|#include "#{dropExtension path}_apply.h"|]
attr = optional (\a -> [lt|#{a}
|]) attribute
semi = [lt|;|]
|
upsoft/bond
|
compiler/src/Language/Bond/Codegen/Cpp/Apply_h.hs
|
mit
| 1,611 | 0 | 11 | 217 | 219 | 144 | 75 | 20 | 1 |
-- |
-- Module : CmdLineParser
-- Description : Parser for command line options.
-- Copyright : (c) Maximilian Nitsch, 2015
--
-- License : MIT
-- Maintainer : [email protected]
-- Stability : experimental
-- Portability : portable
--
-- This module enables to parse command line option and put them in a
-- suitable data structure.
module Spellchecker.CmdLineParser
( -- * Configuration type
Configuration (..)
-- * Run parser
, parseConfig
) where
import Options.Applicative hiding (empty, value)
import Data.Maybe (fromMaybe)
-- | Repository for all command line options
data Configuration = Configuration
{ inFile :: FilePath
, outFile :: FilePath
, corpus :: FilePath
, limit :: Int
, quiet :: Bool
} deriving (Show)
-- | Parse command line options, use default on unset options
cmdLine :: Parser Configuration
cmdLine = Configuration
<$> strOption (short 'i'
<> long "input"
<> metavar "FILE"
<> help "Specifies the input file.")
<*> (fromMaybe "out.txt" -- Default output file
<$> optional (strOption $ short 'o'
<> long "output"
<> metavar "FILE"
<> help "Specifies the output file."))
<*> (fromMaybe "data/corpus_de.dict" -- Default dictionary file
<$> optional (strOption $ short 'c'
<> long "corpus"
<> metavar "FILE"
<> help "Specifies the word corpus."))
<*> (fromMaybe 5 -- Default limit
<$> optional (option auto $ short 'l'
<> long "limit"
<> metavar "NUMBER"
<> help "Edit distance limit."))
<*> switch (short 'q'
<> long "quite"
<> help "Don't ask, take always the best match.")
-- | Execute the command line parser and return the configuration of the
-- spellchecker.
parseConfig :: IO Configuration
parseConfig = execParser $ info (helper <*> cmdLine) fullDesc
|
Ma-Ni/haspell
|
lib/Spellchecker/CmdLineParser.hs
|
mit
| 2,455 | 0 | 17 | 1,033 | 359 | 193 | 166 | 39 | 1 |
module Text.XmlTv (
Channel(..)
, Program(..)
, xmlToChannel
, xmlToProgram
, parseChannels
, parsePrograms
, filterChans
, updateChannel
, findChan
, sortChans
, previous
, current
, later
) where
import Control.Monad
import Data.Maybe
import Text.XML.Light
import Data.Time
import System.Locale
data Channel = Channel {
cid :: String
, lang :: String
, name :: String
, base :: String
, programs :: [Program]
} deriving (Show, Eq)
data Program = Program {
start :: UTCTime
, stop :: UTCTime
, title :: String
, description :: String
} deriving (Show, Eq)
toDate :: String -> Maybe UTCTime
toDate str = parseTime defaultTimeLocale "%Y%m%d%H%M%S %z" str
previous, current, later :: Program -> UTCTime -> Bool
previous (Program start stop _ _) now = diffUTCTime start now < 0 && diffUTCTime stop now < 0
current (Program start stop _ _) now = diffUTCTime start now < 0 && diffUTCTime stop now > 0
later (Program start stop _ _) now = diffUTCTime start now > 0 && diffUTCTime stop now > 0
xmlToChannel :: Element -> Maybe Channel
xmlToChannel e = do
id <- findAttr (QName "id" Nothing Nothing) e
d <- findChild (QName "display-name" Nothing Nothing) e
lang <- findAttr (QName "lang" Nothing Nothing) d
title <- listToMaybe . map cdData . onlyText . elContent $ d
b <- findChild (QName "base-url" Nothing Nothing) e
base <- listToMaybe . map cdData . onlyText . elContent $ b
return $ Channel id lang title base []
-- A lot of optional fields that we should parse
xmlToProgram :: Element -> Maybe Program
xmlToProgram e = do
start <- findAttr (QName "start" Nothing Nothing) e >>= toDate
stop <- findAttr (QName "stop" Nothing Nothing) e >>= toDate
t <- findChild (QName "title" Nothing Nothing) e
--d <- findChild (QName "desc" Nothing Nothing) e
title <- listToMaybe . map cdData . onlyText . elContent $ t
--desc <- listToMaybe . map cdData . onlyText . elContent $ d
return (Program start stop title "")
parseChannels :: String -> [Maybe Channel]
parseChannels str = do
case parseXMLDoc str of
Just p ->
let f = findElements (QName "channel" Nothing Nothing) p
in map xmlToChannel f
Nothing -> []
parsePrograms :: String -> [Maybe Program]
parsePrograms str = do
case parseXMLDoc str of
Just p ->
let f = findElements (QName "programme" Nothing Nothing) p
in map xmlToProgram f
Nothing -> []
-- Starts of by filtering empty channels and then applies another filter.
filterChans :: (Channel -> Bool) -> [Maybe Channel] -> [Channel]
filterChans f chans =
let pure = catMaybes chans
in filter f pure
sortChans :: [String] -> [Channel] -> [Channel]
sortChans strs chans =
map (findChan chans) strs
findChan :: [Channel] -> String -> Channel
findChan chans str =
head . filter ((==) str . name) $ chans
-- takes a channel, a prefix and a fetch method;
-- then etches all programs for that channel using prefix
-- (often date).
updateChannel :: String -> (String -> IO String) -> Channel -> IO Channel
updateChannel prefix fetch c = do
let url = base c ++ cid c ++ prefix
tv <- liftM (catMaybes . parsePrograms) . fetch $ url
return c { programs = (programs c) ++ tv}
|
dagle/hs-xmltv
|
src/Text/XmlTv.hs
|
mit
| 3,370 | 0 | 16 | 846 | 1,105 | 563 | 542 | 83 | 2 |
{-# LANGUAGE DeriveDataTypeable #-}
module Main where
import Data.Map.MultiKey
import Data.Typeable
import Prelude hiding (lookup, null)
data Record = Record
{ rIntKey :: Int
, rStringKey :: String
, rData :: String
} deriving (Show, Typeable)
instance MultiKeyable Record where
empty = MultiKey [key rIntKey, key rStringKey]
records :: [Record]
records =
[ Record 1 "key 1" "data 1"
, Record 20 "key 20" "data 20"
, Record 3 "key 3" "data 3"
]
mk :: MultiKey Record
mk = fromList records
|
jhickner/data-map-multikey
|
example.hs
|
mit
| 514 | 0 | 8 | 107 | 153 | 87 | 66 | 19 | 1 |
{-# LANGUAGE PatternSynonyms, ForeignFunctionInterface, JavaScriptFFI #-}
module GHCJS.DOM.JSFFI.Generated.PositionCallback
(newPositionCallback, newPositionCallbackSync,
newPositionCallbackAsync, PositionCallback)
where
import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, fmap, Show, Read, Eq, Ord)
import Data.Typeable (Typeable)
import GHCJS.Types (JSRef(..), JSString, castRef)
import GHCJS.Foreign (jsNull)
import GHCJS.Foreign.Callback (syncCallback, asyncCallback, syncCallback1, asyncCallback1, syncCallback2, asyncCallback2, OnBlocked(..))
import GHCJS.Marshal (ToJSRef(..), FromJSRef(..))
import GHCJS.Marshal.Pure (PToJSRef(..), PFromJSRef(..))
import Control.Monad.IO.Class (MonadIO(..))
import Data.Int (Int64)
import Data.Word (Word, Word64)
import GHCJS.DOM.Types
import Control.Applicative ((<$>))
import GHCJS.DOM.EventTargetClosures (EventName, unsafeEventName)
import GHCJS.DOM.Enums
-- | <https://developer.mozilla.org/en-US/docs/Web/API/PositionCallback Mozilla PositionCallback documentation>
newPositionCallback ::
(MonadIO m) => (Maybe Geoposition -> IO ()) -> m PositionCallback
newPositionCallback callback
= liftIO
(syncCallback1 ThrowWouldBlock
(\ position ->
fromJSRefUnchecked position >>= \ position' -> callback position'))
-- | <https://developer.mozilla.org/en-US/docs/Web/API/PositionCallback Mozilla PositionCallback documentation>
newPositionCallbackSync ::
(MonadIO m) => (Maybe Geoposition -> IO ()) -> m PositionCallback
newPositionCallbackSync callback
= liftIO
(syncCallback1 ContinueAsync
(\ position ->
fromJSRefUnchecked position >>= \ position' -> callback position'))
-- | <https://developer.mozilla.org/en-US/docs/Web/API/PositionCallback Mozilla PositionCallback documentation>
newPositionCallbackAsync ::
(MonadIO m) => (Maybe Geoposition -> IO ()) -> m PositionCallback
newPositionCallbackAsync callback
= liftIO
(asyncCallback1
(\ position ->
fromJSRefUnchecked position >>= \ position' -> callback position'))
|
plow-technologies/ghcjs-dom
|
src/GHCJS/DOM/JSFFI/Generated/PositionCallback.hs
|
mit
| 2,205 | 0 | 12 | 372 | 521 | 310 | 211 | 39 | 1 |
module Main where
import Control.Lens
import Control.Monad ( unless, when )
import Data.IORef
import System.Exit ( exitFailure, exitSuccess )
import System.IO ( hPutStrLn, stderr )
import qualified Graphics.UI.GLFW as W
import Graphics.Rendering.OpenGL
import Graphics.Event
import Graphics.RenderableItem
import Graphics.Types
import Graphics.Utils
errorCallBack :: W.ErrorCallback
errorCallBack _ desc = hPutStrLn stderr desc
keyCallback :: IORef ViewerState -> W.KeyCallback
keyCallback ref window key _ action mods =
when (action == W.KeyState'Pressed) $ do
case lookup key keyEventFunctions of
Nothing -> return ()
Just f -> f ref mods window
mouseButtonCallback :: IORef ViewerState -> W.MouseButtonCallback
mouseButtonCallback ref window button state _ = do
when (state == W.MouseButtonState'Pressed) $ do
case lookup button mouseEventFunctions of
Nothing -> return ()
Just f -> f ref window
initialize :: String -> IORef ViewerState -> IO W.Window
initialize title stateRef = do
W.setErrorCallback (Just errorCallBack)
successfulInit <- W.init
if not successfulInit then exitFailure else do
W.windowHint $ W.WindowHint'ContextVersionMajor 2
W.windowHint $ W.WindowHint'ContextVersionMinor 1
W.windowHint $ W.WindowHint'Resizable False
mw <- W.createWindow width height title Nothing Nothing
case mw of
Nothing -> W.terminate >> exitFailure
Just window -> do
W.makeContextCurrent mw
W.setKeyCallback window (Just $ keyCallback stateRef)
W.setMouseButtonCallback window (Just $ mouseButtonCallback stateRef)
initGLParams
return window
main :: IO ()
main = do
stateRef <- newIORef initialViewerState
w <- initialize "cghs" stateRef
mainLoop stateRef w
cleanup w
cleanup :: W.Window -> IO ()
cleanup w = do
W.destroyWindow w
W.terminate
exitSuccess
mainLoop :: IORef ViewerState -> W.Window -> IO ()
mainLoop ref window = do
close <- W.windowShouldClose window
unless close $ do
clear [ColorBuffer]
viewerState <- readIORef ref
changeTitle viewerState window
renderItemList $ viewerState ^. renderList
W.swapBuffers window
W.pollEvents
mainLoop ref window
changeTitle :: ViewerState -> W.Window -> IO ()
changeTitle state w = do
let mode = state ^. selectionMode
W.setWindowTitle w $ "cghs - " ++ show mode
|
nyorem/cghs
|
viewer/Main.hs
|
mit
| 2,592 | 0 | 18 | 683 | 765 | 362 | 403 | 69 | 3 |
module List3 where
-- 21
insertAt :: a -> [a] -> Int -> [a]
insertAt _ _ 0 = error "0 is not a valid position"
insertAt elem list pos = fst split ++ [elem] ++ snd split
where split = splitAt (pos - 1) list
range :: Int -> Int -> [Int]
range from to = [from..to]
|
matteosister/haskell-exercises
|
List3.hs
|
mit
| 272 | 0 | 9 | 68 | 122 | 65 | 57 | 7 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE StrictData #-}
{-# LANGUAGE TupleSections #-}
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-glue-trigger.html
module Stratosphere.Resources.GlueTrigger where
import Stratosphere.ResourceImports
import Stratosphere.ResourceProperties.GlueTriggerAction
import Stratosphere.ResourceProperties.GlueTriggerPredicate
-- | Full data type definition for GlueTrigger. See 'glueTrigger' for a more
-- convenient constructor.
data GlueTrigger =
GlueTrigger
{ _glueTriggerActions :: [GlueTriggerAction]
, _glueTriggerDescription :: Maybe (Val Text)
, _glueTriggerName :: Maybe (Val Text)
, _glueTriggerPredicate :: Maybe GlueTriggerPredicate
, _glueTriggerSchedule :: Maybe (Val Text)
, _glueTriggerType :: Val Text
} deriving (Show, Eq)
instance ToResourceProperties GlueTrigger where
toResourceProperties GlueTrigger{..} =
ResourceProperties
{ resourcePropertiesType = "AWS::Glue::Trigger"
, resourcePropertiesProperties =
hashMapFromList $ catMaybes
[ (Just . ("Actions",) . toJSON) _glueTriggerActions
, fmap (("Description",) . toJSON) _glueTriggerDescription
, fmap (("Name",) . toJSON) _glueTriggerName
, fmap (("Predicate",) . toJSON) _glueTriggerPredicate
, fmap (("Schedule",) . toJSON) _glueTriggerSchedule
, (Just . ("Type",) . toJSON) _glueTriggerType
]
}
-- | Constructor for 'GlueTrigger' containing required fields as arguments.
glueTrigger
:: [GlueTriggerAction] -- ^ 'gtActions'
-> Val Text -- ^ 'gtType'
-> GlueTrigger
glueTrigger actionsarg typearg =
GlueTrigger
{ _glueTriggerActions = actionsarg
, _glueTriggerDescription = Nothing
, _glueTriggerName = Nothing
, _glueTriggerPredicate = Nothing
, _glueTriggerSchedule = Nothing
, _glueTriggerType = typearg
}
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-glue-trigger.html#cfn-glue-trigger-actions
gtActions :: Lens' GlueTrigger [GlueTriggerAction]
gtActions = lens _glueTriggerActions (\s a -> s { _glueTriggerActions = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-glue-trigger.html#cfn-glue-trigger-description
gtDescription :: Lens' GlueTrigger (Maybe (Val Text))
gtDescription = lens _glueTriggerDescription (\s a -> s { _glueTriggerDescription = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-glue-trigger.html#cfn-glue-trigger-name
gtName :: Lens' GlueTrigger (Maybe (Val Text))
gtName = lens _glueTriggerName (\s a -> s { _glueTriggerName = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-glue-trigger.html#cfn-glue-trigger-predicate
gtPredicate :: Lens' GlueTrigger (Maybe GlueTriggerPredicate)
gtPredicate = lens _glueTriggerPredicate (\s a -> s { _glueTriggerPredicate = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-glue-trigger.html#cfn-glue-trigger-schedule
gtSchedule :: Lens' GlueTrigger (Maybe (Val Text))
gtSchedule = lens _glueTriggerSchedule (\s a -> s { _glueTriggerSchedule = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-glue-trigger.html#cfn-glue-trigger-type
gtType :: Lens' GlueTrigger (Val Text)
gtType = lens _glueTriggerType (\s a -> s { _glueTriggerType = a })
|
frontrowed/stratosphere
|
library-gen/Stratosphere/Resources/GlueTrigger.hs
|
mit
| 3,424 | 0 | 15 | 462 | 639 | 366 | 273 | 53 | 1 |
{-# LANGUAGE TypeSynonymInstances, FlexibleInstances #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
{-| JSON utility functions. -}
{-
Copyright (C) 2009, 2010, 2011, 2012, 2013 Google Inc.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301, USA.
-}
module Ganeti.JSON
( fromJResult
, readEitherString
, JSRecord
, loadJSArray
, fromObj
, maybeFromObj
, fromObjWithDefault
, fromKeyValue
, fromJVal
, jsonHead
, getMaybeJsonHead
, getMaybeJsonElem
, asJSObject
, asObjectList
, tryFromObj
, arrayMaybeFromJVal
, tryArrayMaybeFromObj
, toArray
, optionalJSField
, optFieldsToObj
, HasStringRepr(..)
, GenericContainer(..)
, Container
)
where
import Control.DeepSeq
import Control.Monad (liftM)
import Data.Maybe (fromMaybe, catMaybes)
import qualified Data.Map as Map
import Text.Printf (printf)
import qualified Text.JSON as J
import Text.JSON.Pretty (pp_value)
-- Note: this module should not import any Ganeti-specific modules
-- beside BasicTypes, since it's used in THH which is used itself to
-- build many other modules.
import Ganeti.BasicTypes
-- * JSON-related functions
instance NFData J.JSValue where
rnf J.JSNull = ()
rnf (J.JSBool b) = rnf b
rnf (J.JSRational b r) = rnf b `seq` rnf r
rnf (J.JSString s) = rnf $ J.fromJSString s
rnf (J.JSArray a) = rnf a
rnf (J.JSObject o) = rnf o
instance (NFData a) => NFData (J.JSObject a) where
rnf = rnf . J.fromJSObject
-- | A type alias for a field of a JSRecord.
type JSField = (String, J.JSValue)
-- | A type alias for the list-based representation of J.JSObject.
type JSRecord = [JSField]
-- | Converts a JSON Result into a monadic value.
fromJResult :: Monad m => String -> J.Result a -> m a
fromJResult s (J.Error x) = fail (s ++ ": " ++ x)
fromJResult _ (J.Ok x) = return x
-- | Tries to read a string from a JSON value.
--
-- In case the value was not a string, we fail the read (in the
-- context of the current monad.
readEitherString :: (Monad m) => J.JSValue -> m String
readEitherString v =
case v of
J.JSString s -> return $ J.fromJSString s
_ -> fail "Wrong JSON type"
-- | Converts a JSON message into an array of JSON objects.
loadJSArray :: (Monad m)
=> String -- ^ Operation description (for error reporting)
-> String -- ^ Input message
-> m [J.JSObject J.JSValue]
loadJSArray s = fromJResult s . J.decodeStrict
-- | Helper function for missing-key errors
buildNoKeyError :: JSRecord -> String -> String
buildNoKeyError o k =
printf "key '%s' not found, object contains only %s" k (show (map fst o))
-- | Reads the value of a key in a JSON object.
fromObj :: (J.JSON a, Monad m) => JSRecord -> String -> m a
fromObj o k =
case lookup k o of
Nothing -> fail $ buildNoKeyError o k
Just val -> fromKeyValue k val
-- | Reads the value of an optional key in a JSON object. Missing
-- keys, or keys that have a \'null\' value, will be returned as
-- 'Nothing', otherwise we attempt deserialisation and return a 'Just'
-- value.
maybeFromObj :: (J.JSON a, Monad m) =>
JSRecord -> String -> m (Maybe a)
maybeFromObj o k =
case lookup k o of
Nothing -> return Nothing
-- a optional key with value JSNull is the same as missing, since
-- we can't convert it meaningfully anyway to a Haskell type, and
-- the Python code can emit 'null' for optional values (depending
-- on usage), and finally our encoding rules treat 'null' values
-- as 'missing'
Just J.JSNull -> return Nothing
Just val -> liftM Just (fromKeyValue k val)
-- | Reads the value of a key in a JSON object with a default if
-- missing. Note that both missing keys and keys with value \'null\'
-- will cause the default value to be returned.
fromObjWithDefault :: (J.JSON a, Monad m) =>
JSRecord -> String -> a -> m a
fromObjWithDefault o k d = liftM (fromMaybe d) $ maybeFromObj o k
arrayMaybeFromJVal :: (J.JSON a, Monad m) => J.JSValue -> m [Maybe a]
arrayMaybeFromJVal (J.JSArray xs) =
mapM parse xs
where
parse J.JSNull = return Nothing
parse x = liftM Just $ fromJVal x
arrayMaybeFromJVal v =
fail $ "Expecting array, got '" ++ show (pp_value v) ++ "'"
-- | Reads an array of optional items
arrayMaybeFromObj :: (J.JSON a, Monad m) =>
JSRecord -> String -> m [Maybe a]
arrayMaybeFromObj o k =
case lookup k o of
Just a -> arrayMaybeFromJVal a
_ -> fail $ buildNoKeyError o k
-- | Wrapper for arrayMaybeFromObj with better diagnostic
tryArrayMaybeFromObj :: (J.JSON a)
=> String -- ^ Textual "owner" in error messages
-> JSRecord -- ^ The object array
-> String -- ^ The desired key from the object
-> Result [Maybe a]
tryArrayMaybeFromObj t o = annotateResult t . arrayMaybeFromObj o
-- | Reads a JValue, that originated from an object key.
fromKeyValue :: (J.JSON a, Monad m)
=> String -- ^ The key name
-> J.JSValue -- ^ The value to read
-> m a
fromKeyValue k val =
fromJResult (printf "key '%s'" k) (J.readJSON val)
-- | Small wrapper over readJSON.
fromJVal :: (Monad m, J.JSON a) => J.JSValue -> m a
fromJVal v =
case J.readJSON v of
J.Error s -> fail ("Cannot convert value '" ++ show (pp_value v) ++
"', error: " ++ s)
J.Ok x -> return x
-- | Helper function that returns Null or first element of the list.
jsonHead :: (J.JSON b) => [a] -> (a -> b) -> J.JSValue
jsonHead [] _ = J.JSNull
jsonHead (x:_) f = J.showJSON $ f x
-- | Helper for extracting Maybe values from a possibly empty list.
getMaybeJsonHead :: (J.JSON b) => [a] -> (a -> Maybe b) -> J.JSValue
getMaybeJsonHead [] _ = J.JSNull
getMaybeJsonHead (x:_) f = maybe J.JSNull J.showJSON (f x)
-- | Helper for extracting Maybe values from a list that might be too short.
getMaybeJsonElem :: (J.JSON b) => [a] -> Int -> (a -> Maybe b) -> J.JSValue
getMaybeJsonElem [] _ _ = J.JSNull
getMaybeJsonElem xs 0 f = getMaybeJsonHead xs f
getMaybeJsonElem (_:xs) n f
| n < 0 = J.JSNull
| otherwise = getMaybeJsonElem xs (n - 1) f
-- | Converts a JSON value into a JSON object.
asJSObject :: (Monad m) => J.JSValue -> m (J.JSObject J.JSValue)
asJSObject (J.JSObject a) = return a
asJSObject _ = fail "not an object"
-- | Coneverts a list of JSON values into a list of JSON objects.
asObjectList :: (Monad m) => [J.JSValue] -> m [J.JSObject J.JSValue]
asObjectList = mapM asJSObject
-- | Try to extract a key from an object with better error reporting
-- than fromObj.
tryFromObj :: (J.JSON a) =>
String -- ^ Textual "owner" in error messages
-> JSRecord -- ^ The object array
-> String -- ^ The desired key from the object
-> Result a
tryFromObj t o = annotateResult t . fromObj o
-- | Ensure a given JSValue is actually a JSArray.
toArray :: (Monad m) => J.JSValue -> m [J.JSValue]
toArray (J.JSArray arr) = return arr
toArray o =
fail $ "Invalid input, expected array but got " ++ show (pp_value o)
-- | Creates a Maybe JSField. If the value string is Nothing, the JSField
-- will be Nothing as well.
optionalJSField :: (J.JSON a) => String -> Maybe a -> Maybe JSField
optionalJSField name (Just value) = Just (name, J.showJSON value)
optionalJSField _ Nothing = Nothing
-- | Creates an object with all the non-Nothing fields of the given list.
optFieldsToObj :: [Maybe JSField] -> J.JSValue
optFieldsToObj = J.makeObj . catMaybes
-- * Container type (special type for JSON serialisation)
-- | Class of types that can be converted from Strings. This is
-- similar to the 'Read' class, but it's using a different
-- serialisation format, so we have to define a separate class. Mostly
-- useful for custom key types in JSON dictionaries, which have to be
-- backed by strings.
class HasStringRepr a where
fromStringRepr :: (Monad m) => String -> m a
toStringRepr :: a -> String
-- | Trivial instance 'HasStringRepr' for 'String'.
instance HasStringRepr String where
fromStringRepr = return
toStringRepr = id
-- | The container type, a wrapper over Data.Map
newtype GenericContainer a b =
GenericContainer { fromContainer :: Map.Map a b }
deriving (Show, Eq)
instance (NFData a, NFData b) => NFData (GenericContainer a b) where
rnf = rnf . Map.toList . fromContainer
-- | Type alias for string keys.
type Container = GenericContainer String
-- | Container loader.
readContainer :: (Monad m, HasStringRepr a, Ord a, J.JSON b) =>
J.JSObject J.JSValue -> m (GenericContainer a b)
readContainer obj = do
let kjvlist = J.fromJSObject obj
kalist <- mapM (\(k, v) -> do
k' <- fromStringRepr k
v' <- fromKeyValue k v
return (k', v')) kjvlist
return $ GenericContainer (Map.fromList kalist)
{-# ANN showContainer "HLint: ignore Use ***" #-}
-- | Container dumper.
showContainer :: (HasStringRepr a, J.JSON b) =>
GenericContainer a b -> J.JSValue
showContainer =
J.makeObj . map (\(k, v) -> (toStringRepr k, J.showJSON v)) .
Map.toList . fromContainer
instance (HasStringRepr a, Ord a, J.JSON b) =>
J.JSON (GenericContainer a b) where
showJSON = showContainer
readJSON (J.JSObject o) = readContainer o
readJSON v = fail $ "Failed to load container, expected object but got "
++ show (pp_value v)
|
vladimir-ipatov/ganeti
|
src/Ganeti/JSON.hs
|
gpl-2.0
| 10,107 | 0 | 15 | 2,364 | 2,432 | 1,274 | 1,158 | 172 | 3 |
{-# LANGUAGE OverloadedStrings #-}
module Tombot.Errors where
import Data.Monoid
left <\> right = left <> "\n" <> right
noFileInPath file = "No file '" <> file <> "' found in path."
noConfig = noFileInPath "Config.json"
<\> "Parhaps you forgot to configure Tombot?"
|
Shou/Tombot
|
Tombot/Errors.hs
|
gpl-2.0
| 283 | 0 | 6 | 59 | 59 | 31 | 28 | 7 | 1 |
-- Tema_11.hs
-- Tema 11: Aplicaciones de programación funcional.
-- José A. Alonso Jiménez https://jaalonso.github.com
-- =====================================================================
module Tema_11 where
import Data.List ((\\))
-- ---------------------------------------------------------------------
-- § El juego de cifras y letras --
-- ---------------------------------------------------------------------
-- La esencia del juego es la siguiente: Dada una sucesión de números
-- naturales y un número objetivo, intentar construir una expresión cuyo
-- valor es el objetivo combinando los números de la sucesión usando
-- suma, resta, multiplicación, división y paréntesis. Cada número de la
-- sucesión puede usarse como máximo una vez. Además, todos los números,
-- incluyendo los resultados intermedios tienen que ser enteros
-- positivos (1,2,3,...).
--
-- Ejemplos:
-- + Dada la sucesión 1, 3, 7, 10, 25, 50 y el objetivo 765, una solución es
-- (1+50)*(25−10).
-- + Para el problema anterior, existen 780 soluciones.
-- + Con la sucesión anterior y el objetivo 831, no hay solución.
-- Las operaciones son sumar, restar, multiplicar o dividir.
data Op = Sum | Res | Mul | Div
instance Show Op where
show Sum = "+"
show Res = "-"
show Mul = "*"
show Div = "/"
-- ops es la lista de las operaciones.
ops :: [Op]
ops = [Sum,Res,Mul,Div]
-- (valida o x y) se verifica si la operación o aplicada a los números
-- naturales x e y da un número natural. Por ejemplo,
-- valida Res 5 3 == True
-- valida Res 3 5 == False
-- valida Div 6 3 == True
-- valida Div 6 4 == False
valida :: Op -> Int -> Int -> Bool
valida Sum _ _ = True
valida Res x y = x > y
valida Mul _ _ = True
valida Div x y = y /= 0 && x `mod` y == 0
-- (aplica o x y) es el resultado de aplicar la operación o a los números
-- naturales x e y. Por ejemplo,
-- aplica Sum 2 3 == 5
-- aplica Div 6 3 == 2
aplica :: Op -> Int -> Int -> Int
aplica Sum x y = x + y
aplica Res x y = x - y
aplica Mul x y = x * y
aplica Div x y = x `div` y
-- Las expresiones son números enteros o aplicaciones de operaciones a
-- dos expresiones.
data Expr = Num Int | Apl Op Expr Expr
instance Show Expr where
show (Num n) = show n
show (Apl o i d) = parentesis i ++ show o ++ parentesis d
where
parentesis (Num n) = show n
parentesis e = "(" ++ show e ++ ")"
-- Ejemplo: Expresión correspondiente a (1+50)*(25−10)
ejExpr :: Expr
ejExpr = Apl Mul e1 e2
where e1 = Apl Sum (Num 1) (Num 50)
e2 = Apl Res (Num 25) (Num 10)
-- (numeros e) es la lista de los números que aparecen en la expresión
-- e. Por ejemplo,
-- λ> numeros (Apl Mul (Apl Sum (Num 2) (Num 3)) (Num 7))
-- [2,3,7]
numeros :: Expr -> [Int]
numeros (Num n) = [n]
numeros (Apl _ l r) = numeros l ++ numeros r
-- (valor e) es la lista formada por el valor de la expresión e si todas
-- las operaciones para calcular el valor de e son números positivos y
-- la lista vacía en caso contrario. Por ejemplo,
-- valor (Apl Mul (Apl Sum (Num 2) (Num 3)) (Num 7)) == [35]
-- valor (Apl Res (Apl Sum (Num 2) (Num 3)) (Num 7)) == []
-- valor (Apl Sum (Apl Res (Num 2) (Num 3)) (Num 7)) == []
valor :: Expr -> [Int]
valor (Num n) = [n | n > 0]
valor (Apl o i d) = [aplica o x y | x <- valor i
, y <- valor d
, valida o x y]
-- (sublistas xs) es la lista de las sublistas de xs. Por ejemplo,
-- λ> sublistas "bc"
-- ["","c","b","bc"]
-- λ> sublistas "abc"
-- ["","c","b","bc","a","ac","ab","abc"]
sublistas :: [a] -> [[a]]
sublistas [] = [[]]
sublistas (x:xs) = yss ++ map (x:) yss
where yss = sublistas xs
-- (intercala x ys) es la lista de las listas obtenidas intercalando x
-- entre los elementos de ys. Por ejemplo,
-- intercala 'x' "bc" == ["xbc","bxc","bcx"]
-- intercala 'x' "abc" == ["xabc","axbc","abxc","abcx"]
intercala :: a -> [a] -> [[a]]
intercala x [] = [[x]]
intercala x (y:ys) = (x:y:ys) : map (y:) (intercala x ys)
-- (permutaciones xs) es la lista de las permutaciones de xs. Por
-- ejemplo,
-- permutaciones "bc" == ["bc","cb"]
-- permutaciones "abc" == ["abc","bac","bca","acb","cab","cba"]
permutaciones :: [a] -> [[a]]
permutaciones [] = [[]]
permutaciones (x:xs) = concatMap (intercala x) (permutaciones xs)
-- (elecciones xs) es la lista formada por todas las sublistas de xs en
-- cualquier orden. Por ejemplo,
-- λ> elecciones "abc"
-- ["","c","b","bc","cb","a","ac","ca","ab","ba",
-- "abc","bac","bca","acb","cab","cba"]
elecciones :: [a] -> [[a]]
elecciones xs = concatMap permutaciones (sublistas xs)
-- (solucion e ns n) se verifica si la expresión e es una solución para
-- la sucesión ns y objetivo n; es decir. si los números de e es una
-- posible elección de ns y el valor de e es n. Por ejemplo,
-- solucion ejExpr [1,3,7,10,25,50] 765 == True
solucion :: Expr -> [Int] -> Int -> Bool
solucion e ns n = elem (numeros e) (elecciones ns) && valor e == [n]
-- (divisiones xs) es la lista de las divisiones de xs en dos listas no
-- vacías. Por ejemplo,
-- divisiones "bcd" == [("b","cd"),("bc","d")]
-- divisiones "abcd" == [("a","bcd"),("ab","cd"),("abc","d")]
divisiones :: [a] -> [([a],[a])]
divisiones [] = []
divisiones [_] = []
divisiones (x:xs) = ([x],xs) : [(x:is,ds) | (is,ds) <- divisiones xs]
-- (expresiones ns) es la lista de todas las expresiones construibles a
-- partir de la lista de números ns. Por ejemplo,
-- λ> expresiones [2,3,5]
-- [2+(3+5),2-(3+5),2*(3+5),2/(3+5),2+(3-5),2-(3-5),
-- 2*(3-5),2/(3-5),2+(3*5),2-(3*5),2*(3*5),2/(3*5),
-- 2+(3/5),2-(3/5),2*(3/5),2/(3/5),(2+3)+5,(2+3)-5,
-- ...
expresiones :: [Int] -> [Expr]
expresiones [] = []
expresiones [n] = [Num n]
expresiones ns = [e | (is,ds) <- divisiones ns
, i <- expresiones is
, d <- expresiones ds
, e <- combina i d]
-- (combina e1 e2) es la lista de las expresiones obtenidas combinando
-- las expresiones e1 y e2 con una operación. Por ejemplo,
-- combina (Num 2) (Num 3) == [2+3,2-3,2*3,2/3]
combina :: Expr -> Expr -> [Expr]
combina e1 e2 = [Apl o e1 e2 | o <- ops]
-- (soluciones ns n) es la lista de las soluciones para la sucesión ns y
-- objetivo n calculadas por fuerza bruta. Por ejemplo,
-- λ> soluciones [1,3,7,10,25,50] 765
-- [3*((7*(50-10))-25), ((7*(50-10))-25)*3, ...
-- λ> length (soluciones [1,3,7,10,25,50] 765)
-- 780
-- λ> length (soluciones [1,3,7,10,25,50] 831)
-- 0
soluciones :: [Int] -> Int -> [Expr]
soluciones ns n = [e | ns' <- elecciones ns
, e <- expresiones ns'
, valor e == [n]]
-- Resultado es el tipo de los pares formados por expresiones válidas y
-- su valor.
type Resultado = (Expr,Int)
-- (resultados ns) es la lista de todos los resultados construibles a
-- partir de la lista de números ns. Por ejemplo,
-- λ> resultados [2,3,5]
-- [(2+(3+5),10), (2*(3+5),16), (2+(3*5),17), (2*(3*5),30), ((2+3)+5,10),
-- ((2+3)*5,25), ((2+3)/5,1), ((2*3)+5,11), ((2*3)-5,1), ((2*3)*5,30)]
resultados :: [Int] -> [Resultado]
resultados [] = []
resultados [n] = [(Num n,n) | n > 0]
resultados ns = [res | (is,ds) <- divisiones ns
, ix <- resultados is
, dy <- resultados ds
, res <- combina' ix dy]
-- (combina' r1 r2) es la lista de los resultados obtenidos combinando
-- los resultados r1 y r2 con una operación. Por ejemplo,
-- combina' (Num 2,2) (Num 3,3) == [(2+3,5),(2*3,6)]
-- combina' (Num 3,3) (Num 2,2) == [(3+2,5),(3-2,1),(3*2,6)]
-- combina' (Num 2,2) (Num 6,6) == [(2+6,8),(2*6,12)]
-- combina' (Num 6,6) (Num 2,2) == [(6+2,8),(6-2,4),(6*2,12),(6/2,3)]
combina' :: Resultado -> Resultado -> [Resultado]
combina' (i,x) (d,y) = [(Apl o i d, aplica o x y) | o <- ops
, valida o x y]
-- (soluciones' ns n) es la lista de las soluciones para la sucesión ns
-- y objetivo n calculadas intercalando generación y evaluación. Por
-- λ> head (soluciones' [1,3,7,10,25,50] 765)
-- 3*((7*(50-10))-25)
-- λ> length (soluciones' [1,3,7,10,25,50] 765)
-- 780
-- λ> length (soluciones' [1,3,7,10,25,50] 831)
-- 0
soluciones' :: [Int] -> Int -> [Expr]
soluciones' ns n = [e | ns' <- elecciones ns
, (e,m) <- resultados ns'
, m == n]
-- (valida' o x y) se verifica si la operación o aplicada a los números
-- naturales x e y da un número natural, teniendo en cuenta las
-- siguientes reducciones algebraicas
-- x + y = y + x
-- x * y = y * x
-- x * 1 = x
-- 1 * y = y
-- x / 1 = x
valida' :: Op -> Int -> Int -> Bool
valida' Sum x y = x <= y
valida' Res x y = x > y
valida' Mul x y = x /= 1 && y /= 1 && x <= y
valida' Div x y = y /= 0 && y /= 1 && x `mod` y == 0
-- (resultados' ns) es la lista de todos los resultados válidos
-- construibles a partir de la lista de números ns. Por ejemplo,
-- λ> resultados' [5,3,2]
-- [(5-(3-2),4),((5-3)+2,4),((5-3)*2,4),((5-3)/2,1)]
resultados' :: [Int] -> [Resultado]
resultados' [] = []
resultados' [n] = [(Num n,n) | n > 0]
resultados' ns = [res | (is,ds) <- divisiones ns
, ix <- resultados' is
, dy <- resultados' ds
, res <- combina'' ix dy]
-- (combina'' r1 r2) es la lista de los resultados válidos obtenidos
-- combinando los resultados r1 y r2 con una operación. Por ejemplo,
-- combina'' (Num 2,2) (Num 3,3) == [(2+3,5),(2*3,6)]
-- combina'' (Num 3,3) (Num 2,2) == [(3-2,1)]
-- combina'' (Num 2,2) (Num 6,6) == [(2+6,8),(2*6,12)]
-- combina'' (Num 6,6) (Num 2,2) == [(6-2,4),(6/2,3)]
combina'' :: Resultado -> Resultado -> [Resultado]
combina'' (i,x) (d,y) = [(Apl o i d, aplica o x y) | o <- ops
, valida' o x y]
-- (soluciones'' ns n) es la lista de las soluciones para la sucesión ns
-- y objetivo n calculadas intercalando generación y evaluación y usando
-- las mejoras aritméticas. Por ejemplo,
-- λ> head (soluciones'' [1,3,7,10,25,50] 765)
-- 3*((7*(50-10))-25)
-- λ> length (soluciones'' [1,3,7,10,25,50] 765)
-- 49
-- λ> length (soluciones'' [1,3,7,10,25,50] 831)
-- 0
soluciones'' :: [Int] -> Int -> [Expr]
soluciones'' ns n = [e | ns' <- elecciones ns
, (e,m) <- resultados' ns'
, m == n]
-- ---------------------------------------------------------------------
-- § El problema de las reinas --
-- ---------------------------------------------------------------------
-- Enunciado: Colocar N reinas en un tablero rectangular de dimensiones
-- N por N de forma que no se encuentren más de una en la misma línea:
-- horizontal, vertical o diagonal.
-- El tablero se representa por una lista de números que indican las
-- filas donde se han colocado las reinas. Por ejemplo, [3,5] indica que
-- se han colocado las reinas (1,3) y (2,5).
type Tablero = [Int]
-- reinas n es la lista de soluciones del problema de las N reinas. Por
-- ejemplo,
-- reinas 4 == [[3,1,4,2],[2,4,1,3]]
-- La primera solución [3,1,4,2] se interpreta como
-- |---|---|---|---|
-- | | R | | |
-- |---|---|---|---|
-- | | | | R |
-- |---|---|---|---|
-- | R | | | |
-- |---|---|---|---|
-- | | | R | |
-- |---|---|---|---|
reinas :: Int -> [Tablero]
reinas n = aux n
where aux 0 = [[]]
aux m = [r:rs | rs <- aux (m-1),
r <- ([1..n] \\ rs),
noAtaca r rs 1]
-- (noAtaca r rs d) se verifica si la reina r no ataca a ninguna de las
-- de la lista rs donde la primera de la lista está a una distancia
-- horizontal d.
noAtaca :: Int -> Tablero -> Int -> Bool
noAtaca _ [] _ = True
noAtaca r (a:rs) distH = abs(r-a) /= distH &&
noAtaca r rs (distH+1)
-- ---------------------------------------------------------------------
-- § Números de Hamming --
-- ---------------------------------------------------------------------
-- Enunciado: Los números de Hamming forman una sucesión estrictamente
-- creciente de números que cumplen las siguientes condiciones:
-- + El número 1 está en la sucesión.
-- + Si x está en la sucesión, entonces 2x, 3x y 5x también están.
-- + Ningún otro número está en la sucesión.
-- hamming es la sucesión de Hamming. Por ejemplo,
-- take 12 hamming == [1,2,3,4,5,6,8,9,10,12,15,16]
hamming :: [Int]
hamming = 1 : mezcla3 [2*i | i <- hamming]
[3*i | i <- hamming]
[5*i | i <- hamming]
-- (mezcla3 xs ys zs) es la lista obtenida mezclando las listas
-- ordenadas xs, ys y zs y eliminando los elementos duplicados. Por
-- ejemplo,
-- λ> mezcla3 [2,4,6,8,10] [3,6,9,12] [5,10]
-- [2,3,4,5,6,8,9,10,12]
mezcla3 :: [Int] -> [Int] -> [Int] -> [Int]
mezcla3 xs ys zs = mezcla2 xs (mezcla2 ys zs)
-- (mezcla2 xs ys) es la lista obtenida mezclando las listas ordenadas xs e
-- ys y eliminando los elementos duplicados. Por ejemplo,
-- mezcla2 [2,4,6,8,10,12] [3,6,9,12] == [2,3,4,6,8,9,10,12]
mezcla2 :: [Int] -> [Int] -> [Int]
mezcla2 p@(x:xs) q@(y:ys) | x < y = x:mezcla2 xs q
| x > y = y:mezcla2 p ys
| otherwise = x:mezcla2 xs ys
mezcla2 [] ys = ys
mezcla2 xs [] = xs
|
jaalonso/I1M-Cod-Temas
|
src/Tema_11.hs
|
gpl-2.0
| 13,834 | 0 | 12 | 3,614 | 2,559 | 1,432 | 1,127 | 126 | 2 |
module Datum where
data Jahreszeit = Fruehling | Sommer | Herbst | Winter
deriving (Eq, Ord, Enum, Show, Read)
data Monat = Januar | Februar | Maerz | April | Mai | Juni | Juli |
August | September | Oktober | November | Dezember
deriving (Eq, Ord, Enum, Show, Read)
type Jahr = Int
type Tag = Int
|
collective/ECSpooler
|
backends/haskell/haskell_libs/Datum.hs
|
gpl-2.0
| 329 | 0 | 6 | 90 | 118 | 71 | 47 | 8 | 0 |
module UI.App where
import Control.Concurrent.STM.TMChan (TMChan)
import Brick
import Brick.BChan
import Brick.Widgets.Border
import Brick.Widgets.Border.Style
import Graphics.Vty
import Data.Maybe (isJust, fromJust)
import Data.List (find)
import qualified Data.TCP as TCP
import Data.Entity (Entity)
import qualified Data.Entity as E
import Data.Default
data State = State
{ stateChan :: TMChan TCP.Command
, stateTerrain :: [String]
, stateEntities :: [Entity]
, stateLog :: [String]
, statePlayer :: Entity
}
data Resource = Resource ()
deriving (Eq, Ord)
runApp :: BChan TCP.Event -> TMChan TCP.Command -> IO State
runApp downChan upChan = customMain
(Graphics.Vty.mkVty Graphics.Vty.defaultConfig)
(Just downChan) app (initialState upChan)
app :: App State TCP.Event Resource
app = App
{ appDraw = draw
, appChooseCursor = const $ const Nothing
, appHandleEvent = handleEvent
, appStartEvent = return
, appAttrMap = const $ attrMap Graphics.Vty.defAttr []
}
initialState :: TMChan TCP.Command -> State
initialState chan = State
{ stateChan = chan
, stateTerrain = ["Loading..."]
, stateEntities = []
, stateLog = ["If the log is empty, UI breaks."]
, statePlayer = def
}
draw :: State -> [Widget Resource]
draw s = [withBorderStyle unicodeRounded $ (drawMap s) <+> (drawStatus s)]
drawMap :: State -> Widget Resource
drawMap s = padRight Max $ str (unlines (stateTerrain s))
drawStatus :: State -> Widget Resource
drawStatus s = (drawPlayerInfo s) <=> (drawLog (stateLog s))
drawPlayerInfo :: State -> Widget Resource
drawPlayerInfo s = borderWithLabel (str (E.stateName playerState)) $ hLimit 40 $ padRight Max $
str $ "HP : " ++ show (E.stateHP playerState) ++ " / " ++ show (E.stateMaxHP playerState)
where playerState = E.entityState (statePlayer s)
drawLog :: [String] -> Widget Resource
drawLog l = borderWithLabel (str "Log") $ padBottom Max $ hLimit 40 $ padRight Max $
(str . unlines) l
findEntity :: E.Id -> State -> Maybe Entity
findEntity e s = find (\e' -> E.entityId e' == e) (stateEntities s)
handleEvent :: State -> BrickEvent Resource TCP.Event -> EventM Resource (Next State)
handleEvent s (VtyEvent e) = handleVtyEvent s e
handleEvent s (AppEvent e) = handleAppEvent s e
handleVtyEvent :: State -> Event -> EventM Resource (Next State)
handleVtyEvent s (EvKey (KChar 'd') [MCtrl]) = halt s
handleVtyEvent s (EvKey k mod) = continue s
handleVtyEvent s (EvResize k y) = continue s
handleVtyEvent s _ = continue s
handleAppEvent :: State -> TCP.Event -> EventM Resource (Next State)
handleAppEvent s e = continue (s {stateLog = (show e):(stateLog s)})
--handleAppEvent s (TCP.EventFail msg) =
-- continue (s {stateLog = ("Failed to parse TCP. message: " ++ msg):(stateLog s)})
--handleAppEvent s (TCP.EventLog msg) =
-- continue (s {stateLog = msg:(stateLog s)})
--handleAppEvent s (TCP.EventTerrain t) =
-- continue (s {stateTerrain = t})
--handleAppEvent s (TCP.EventEntityAdd e) =
-- continue (s {stateEntities = e:(stateEntities s)})
--handleAppEvent s (TCP.EventEntityRemove eid) =
-- continue (s {stateEntities = filter (\e -> E.entityId e /= eid) (stateEntities s)})
--handleAppEvent s (TCP.EventPlayerId eid) =
-- if isJust player then
-- continue (s {statePlayer = fromJust player})
-- else
-- handleAppEvent s (TCP.EventFail $ "Failed to find player entity with Id " ++ show eid)
-- where player = findEntity eid s
|
osense/stalkerlike-client-cli
|
app/UI/App.hs
|
gpl-3.0
| 3,429 | 0 | 17 | 593 | 1,007 | 538 | 469 | 64 | 1 |
module Main where
import qualified Lib as L
import Text.Printf (printf)
main :: IO ()
--main = printf "2 + 3 = %d\n" (ourAdd 2 3)
main = L.main
|
stephane-rolland/aastraal
|
aastraal-client-brick/app/Main.hs
|
gpl-3.0
| 147 | 0 | 6 | 32 | 38 | 24 | 14 | 5 | 1 |
-- the Reader Functor
--
instance Functor ((->) r) where
fmap = (.)
f :: r -> a
-- Challenge 2: Prove functor laws for the reader functor. Hint: its really simple.
--
-- ... 1. preserves identity
-- fmap id f
-- = id . f
-- = f
-- = (id f)
-- fmap f id
-- = f . id
-- = f
-- = (id f)
--
-- ... 2. preserves composition
-- (fmap f . fmap g) f
-- = fmap g (fmap h f) - defn of composition
-- = fmap g (h . f) - defn of fmap on (->)
-- = g . (h . f) - defn of fmap on (->)
-- = (g . h) . f - associativity of regular function composition
-- = fmap (g . h) f - defn of fmap on (->)
-- fmap (g . h) f
-- = (g . h) . f - defn of fmap on (->)
-- = g . (h . f) - associativity of regular function composition
-- = fmap g (h . f) - defn of fmap on (->)
-- = fmap g (fmap h f) - defn of fmap on (->)
-- = (fmap f . fmap g) f - defn of composition
|
sujeet4github/MyLangUtils
|
CategoryTheory_BartoszMilewsky/PI_07_Functors/ex2_Reader.hs
|
gpl-3.0
| 943 | 0 | 8 | 321 | 61 | 46 | 15 | 3 | 0 |
newtype BiComp bf fu gu a b = BiComp (bf (fu a) (gu b))
|
hmemcpy/milewski-ctfp-pdf
|
src/content/1.8/code/haskell/snippet09.hs
|
gpl-3.0
| 55 | 0 | 9 | 13 | 34 | 20 | 14 | 1 | 0 |
module Database.Design.Ampersand.Output.PredLogic
( PredLogicShow(..), showLatex, showRtf, mkVar
) where
import Data.List
import Database.Design.Ampersand.Basics
import Database.Design.Ampersand.ADL1
import Database.Design.Ampersand.Classes
import Database.Design.Ampersand.Misc
import Database.Design.Ampersand.FSpec.ShowADL
import Data.Char
import Database.Design.Ampersand.Output.PandocAux (latexEscShw,texOnly_Id)
-- data PredVar = PV String -- TODO Bedoeld om predicaten inzichtelijk te maken. Er bestaan namelijk nu verschillende manieren om hier mee om te gaan (zie ook Motivations. HJO.
data PredLogic
= Forall [Var] PredLogic |
Exists [Var] PredLogic |
Implies PredLogic PredLogic |
Equiv PredLogic PredLogic |
Conj [PredLogic] |
Disj [PredLogic] |
Not PredLogic |
Pred String String | -- Pred nm v, with v::type is equiv. to Rel nm Nowhere [] (type,type) True (Sgn (showADL e) type type [] "" "" "" [Asy,Sym] Nowhere 0 False)
PlK0 PredLogic |
PlK1 PredLogic |
R PredLogic Declaration PredLogic |
Atom String |
Funs String [Declaration] |
Dom Expression Var |
Cod Expression Var deriving Eq
data Notation = Flr | Frl | Rn | Wrap deriving Eq -- yields notations y=r(x) | x=r(y) | x r y | exists ... respectively.
-- predKeyWords l =
-- case l of
-- English ->
class PredLogicShow a where
showPredLogic :: Lang -> a -> String
showPredLogic l r =
predLshow (natLangOps l) (toPredLogic r) -- predLshow produces raw LaTeX
toPredLogic :: a -> PredLogic
instance PredLogicShow Rule where
toPredLogic ru = assemble (rrexp ru)
instance PredLogicShow Expression where
toPredLogic = assemble
-- showLatex ought to produce PandDoc mathematics instead of LaTeX source code.
-- PanDoc, however, does not support mathematics sufficiently, as to date. For this reason we have showLatex.
-- It circumvents the PanDoc structure and goes straight to LaTeX source code.
-- TODO when PanDoc is up to the job.
showLatex :: PredLogic -> [[String]]
showLatex x
= chop (predLshow ("\\forall", "\\exists", implies, "\\Leftrightarrow", "\\vee", "\\ \\wedge\t", "^{\\asterisk}", "^{+}", "\\neg", rel, fun, mathVars, "", " ", apply, "\\in") x)
where rel r lhs rhs -- TODO: the stuff below is very sloppy. This ought to be derived from the stucture, instead of by this naming convention.
= if isIdent r then lhs++"\\ =\\ "++rhs else
case name r of
"lt" -> lhs++"\\ <\\ "++rhs
"gt" -> lhs++"\\ >\\ "++rhs
"le" -> lhs++"\\ \\leq\\ "++rhs
"leq" -> lhs++"\\ \\leq\\ "++rhs
"ge" -> lhs++"\\ \\geq\\ "++rhs
"geq" -> lhs++"\\ \\geq\\ "++rhs
_ -> lhs++"\\ \\id{"++latexEscShw (name r)++"}\\ "++rhs
fun r e = "\\id{"++latexEscShw (name r)++"}("++e++")"
implies antc cons = antc++" \\Rightarrow "++cons
apply :: Declaration -> String -> String -> String --TODO language afhankelijk maken.
apply decl d c =
case decl of
Sgn{} -> d++"\\ \\id{"++latexEscShw (name decl)++"}\\ "++c
Isn{} -> d++"\\ =\\ "++c
Vs{} -> "V"
mathVars :: String -> [Var] -> String
mathVars q vs
= if null vs then "" else
q++" "++intercalate "; " [intercalate ", " var++"\\coloncolon\\id{"++latexEscShw dType++"}" | (var,dType)<-vss]++":\n"
where
vss = [(map fst varCl,show(snd (head varCl))) |varCl<-eqCl snd vs]
chop :: String -> [[String]]
chop str = (map chops.lins) str
where
lins "" = []
lins ('\n':cs) = "": lins cs
lins (c:cs) = (c:r):rs where r:rs = case lins cs of [] -> [""] ; e -> e
chops cs = let [a,b,c] = take 3 (tabs cs) in [a,b,c]
tabs "" = ["","","",""]
tabs ('\t':cs) = "": tabs cs
tabs (c:cs) = (c:r):rs where r:rs = tabs cs
showRtf :: PredLogic -> String
showRtf p = predLshow (forallP, existsP, impliesP, equivP, orP, andP, k0P, k1P, notP, relP, funP, showVarsP, breakP, spaceP, apply, el)
p
where unicodeSym :: Int -> Char -> Char -> String
unicodeSym fs sym altChar = "{\\fs"++show fs++" \\u"++show (ord sym)++[altChar]++"}"
forallP = unicodeSym 32 '∀' 'A' --"{\\fs36 \\u8704A}"
existsP = unicodeSym 32 '∃' 'E'
impliesP antc cons = antc++" "++unicodeSym 26 '⇒' '?'++" "++cons
equivP = unicodeSym 26 '⇔' '='
orP = unicodeSym 30 '∨' 'v'
andP = unicodeSym 30 '∧' '^'
k0P = "{\\super "++unicodeSym 30 '∗' '*'++"}"
k1P = "{\\super +}"
notP = unicodeSym 26 '¬' '!'
el = unicodeSym 30 '∈' '?'
relP r lhs rhs -- TODO: sloppy code, copied from showLatex
= if isIdent r then lhs++"\\ =\\ "++rhs else
case name r of
"lt" -> lhs++" < "++rhs
"gt" -> lhs++" > "++rhs
"le" -> lhs++" "++unicodeSym 28 '≤' '?'++" "++rhs
"leq" -> lhs++" "++unicodeSym 28 '≤' '?'++" "++rhs
"ge" -> lhs++" "++unicodeSym 28 '≥' '?'++" "++rhs
"geq" -> lhs++" "++unicodeSym 28 '≥' '?'++" "++rhs
_ -> lhs++" "++name r++" "++rhs
funP r e = name r++"("++e++")"
apply :: Declaration -> String -> String -> String
apply decl d c =
case decl of
Sgn{} -> d++" "++name decl++" "++c
Isn{} -> d++" = "++c
Vs{} -> "V"
showVarsP :: String -> [Var] -> String
showVarsP q vs
= if null vs then "" else
q++intercalate "; " [intercalate ", " var++" "++unicodeSym 28 '∷' '?'++" "++dType | (var,dType)<-vss]++":\\par\n"
where
vss = [(map fst varCl,show(snd (head varCl))) |varCl<-eqCl snd vs]
breakP = ""
spaceP = " "
-- natLangOps exists for the purpose of translating a predicate logic expression to natural language.
-- It yields a vector of mostly strings, which are used to assemble a natural language text in one of the natural languages supported by Ampersand.
natLangOps :: Named a => Lang -> (String,
String,
String -> String -> String,
String,
String,
String,
String,
String,
String,
Declaration -> String -> String -> String,
a -> String -> String,
String -> [(String, A_Concept)] -> String,
String,
String,
Declaration -> String -> String -> String,
String)
natLangOps l
= case l of
-- parameternamen: (forallP, existsP, impliesP, equivP, orP, andP, k0P, k1P, notP, relP, funP, showVarsP, breakP, spaceP)
English -> ("For each", "There exists", implies, "is equivalent to", "or", "and", "*", "+", "not", rel, fun, langVars , "\n ", " ", apply, "is element of")
Dutch -> ("Voor elke", "Er is een", implies, "is equivalent met", "of", "en", "*", "+", "niet", rel, fun, langVars , "\n ", " ", apply, "is element van")
where
rel r = apply r
fun r x' = texOnly_Id(name r)++"("++x'++")"
implies antc cons = case l of
English -> "If "++antc++", then "++cons
Dutch -> "Als "++antc++", dan "++cons
apply decl d c =
case decl of
Sgn{} -> if null (prL++prM++prR)
then "$"++d++"$ "++name decl++" $"++c++"$"
else prL++" $"++d++"$ "++prM++" $"++c++"$ "++prR
where prL = decprL decl
prM = decprM decl
prR = decprR decl
Isn{} -> case l of
English -> "$"++d++"$ equals $"++c++"$"
Dutch -> "$"++d++"$ is gelijk aan $"++c++"$"
Vs{} -> case l of
English -> show True
Dutch -> "Waar"
langVars :: String -> [(String, A_Concept)] -> String
langVars q vs
= case l of
English | null vs -> ""
| q=="Exists" ->
intercalate " and "
["there exist"
++(if length vs'==1 then "s a "++dType else ' ':plural English dType)
++" called "
++intercalate ", " ['$':v'++"$" | v'<-vs'] | (vs',dType)<-vss]
| otherwise -> "If "++langVars "Exists" vs++", "
Dutch | null vs -> ""
| q=="Er is" ->
intercalate " en "
["er "
++(if length vs'==1 then "is een "++dType else "zijn "++plural Dutch dType)
++" genaamd "
++intercalate ", " ['$':v'++"$" | v'<-vs'] | (vs',dType)<-vss]
| otherwise -> "Als "++langVars "Er is" vs++", "
where
vss = [(map fst vs',show(snd (head vs'))) |vs'<-eqCl snd vs]
-- predLshow exists for the purpose of translating a predicate logic expression to natural language.
-- It uses a vector of operators (mostly strings) in order to produce text. This vector can be produced by, for example, natLangOps.
-- example: 'predLshow (natLangOps l) e' translates expression 'e'
-- into a string that contains a natural language representation of 'e'.
predLshow :: ( String -- forallP
, String -- existsP
, String -> String -> String -- impliesP
, String -- equivP
, String -- orP
, String -- andP
, String -- kleene *
, String -- kleene +
, String -- notP
, Declaration -> String -> String -> String -- relP
, Declaration -> String -> String -- funP
, String -> [(String, A_Concept)] -> String -- showVarsP
, String -- breakP
, String -- spaceP
, Declaration -> String -> String -> String -- apply
, String -- set element
) -> PredLogic -> String
predLshow (forallP, existsP, impliesP, equivP, orP, andP, k0P, k1P, notP, relP, funP, showVarsP, breakP, spaceP, apply, el)
= charshow 0
where
wrap i j str = if i<=j then str else "("++str++")"
charshow :: Integer -> PredLogic -> String
charshow i predexpr
= case predexpr of
Forall vars restr -> wrap i 1 (showVarsP forallP vars ++ charshow 1 restr)
Exists vars restr -> wrap i 1 (showVarsP existsP vars ++ charshow 1 restr)
Implies antc conseq -> wrap i 2 (breakP++impliesP (charshow 2 antc) (charshow 2 conseq))
Equiv lhs rhs -> wrap i 2 (breakP++charshow 2 lhs++spaceP++equivP++spaceP++ charshow 2 rhs)
Disj rs -> if null rs
then ""
else wrap i 3 (intercalate (spaceP++orP ++spaceP) (map (charshow 3) rs))
Conj rs -> if null rs
then ""
else wrap i 4 (intercalate (spaceP++andP++spaceP) (map (charshow 4) rs))
Funs x ls -> case ls of
[] -> x
r:ms -> if isIdent r then charshow i (Funs x ms) else charshow i (Funs (funP r x) ms)
Dom expr (x,_) -> x++el++funP (makeRel "dom") (showADL expr)
Cod expr (x,_) -> x++el++funP (makeRel "cod") (showADL expr)
R pexpr dec pexpr' -> case (pexpr,pexpr') of
(Funs l [] , Funs r []) -> wrap i 5 (apply dec l r)
{-
(Funs l [f], Funs r []) -> wrap i 5 (if isIdent rel
then apply (makeDeclaration f) l r
else apply (makeDeclaration rel) (funP f l) r)
(Funs l [] , Funs r [f]) -> wrap i 5 (if isIdent rel
then apply (makeDeclaration f) l r
else apply (makeDeclaration rel) l (funP f r))
-}
(lhs,rhs) -> wrap i 5 (relP dec (charshow 5 lhs) (charshow 5 rhs))
Atom atom -> "'"++atom++"'"
PlK0 rs -> wrap i 6 (charshow 6 rs++k0P)
PlK1 rs -> wrap i 7 (charshow 7 rs++k1P)
Not rs -> wrap i 8 (spaceP++notP++charshow 8 rs)
Pred nm v' -> nm++"{"++v'++"}"
makeRel :: String -> Declaration -- This function exists solely for the purpose of dom and cod
makeRel str
= Sgn { decnm = str
, decsgn = fatal 217 "Do not refer to decsgn of this dummy relation"
, decprps = [Uni,Tot]
, decprps_calc = Nothing
, decprL = ""
, decprM = ""
, decprR = ""
, decMean = fatal 223 "Do not refer to decMean of this dummy relation"
, decfpos = OriginUnknown
, decusr = False
, decpat = fatal 228 "Do not refer to decpat of this dummy relation"
, decplug = fatal 229 "Do not refer to decplug of this dummy relation"
}
--objOrShow :: Lang -> PredLogic -> String
--objOrShow l = predLshow ("For all", "Exists", implies, " = ", " = ", "<>", "OR", "AND", "*", "+", "NOT", rel, fun, langVars l, "\n", " ")
-- where rel r lhs rhs = applyM (makeDeclaration r) lhs rhs
-- fun r x = x++"."++name r
-- implies antc cons = "IF "++antc++" THEN "++cons
-- The function 'assemble' translates a rule to predicate logic.
-- In order to remain independent of any representation, it transforms the Haskell data structure Rule
-- into the data structure PredLogic, rather than manipulate with texts.
type Var = (String,A_Concept)
assemble :: Expression -> PredLogic
assemble expr
= case (source expr, target expr) of
(ONE, ONE) -> rc
(_ , ONE) -> Forall [s] rc
(ONE, _) -> Forall [t] rc
(_ , _) -> Forall [s,t] rc
where
[s,t] = mkVar [] [source expr, target expr]
rc = f [s,t] expr (s,t)
f :: [Var] -> Expression -> (Var,Var) -> PredLogic
f exclVars (EEqu (l,r)) (a,b) = Equiv (f exclVars l (a,b)) (f exclVars r (a,b))
f exclVars (EInc (l,r)) (a,b) = Implies (f exclVars l (a,b)) (f exclVars r (a,b))
f exclVars e@EIsc{} (a,b) = Conj [f exclVars e' (a,b) | e'<-exprIsc2list e]
f exclVars e@EUni{} (a,b) = Disj [f exclVars e' (a,b) | e'<-exprUni2list e]
f exclVars (EDif (l,r)) (a,b) = Conj [f exclVars l (a,b), Not (f exclVars r (a,b))]
f exclVars (ELrs (l,r)) (a,b) = Forall [c] (Implies (f eVars r (b,c)) (f eVars l (a,c)))
where [c] = mkVar exclVars [target l]
eVars = exclVars++[c]
f exclVars (ERrs (l,r)) (a,b) = Forall [c] (Implies (f eVars l (c,a)) (f eVars r (c,b)))
where [c] = mkVar exclVars [source l]
eVars = exclVars++[c]
f exclVars (EDia (l,r)) (a,b) = Forall [c] (Equiv (f eVars r (b,c)) (f eVars l (a,c)))
where [c] = mkVar exclVars [target l]
eVars = exclVars++[c]
f exclVars e@ECps{} (a,b) = fECps exclVars e (a,b) -- special treatment, see below
f exclVars e@ERad{} (a,b) = fERad exclVars e (a,b) -- special treatment, see below
f _ (EPrd (l,r)) (a,b) = Conj [Dom l a, Cod r b]
f exclVars (EKl0 e) (a,b) = PlK0 (f exclVars e (a,b))
f exclVars (EKl1 e) (a,b) = PlK1 (f exclVars e (a,b))
f exclVars (ECpl e) (a,b) = Not (f exclVars e (a,b))
f exclVars (EBrk e) (a,b) = f exclVars e (a,b)
f _ e@(EDcD dcl) ((a,sv),(b,tv)) = res
where
res = case denote e of
Flr -> R (Funs a [dcl]) (Isn tv) (Funs b [])
Frl -> R (Funs a []) (Isn sv) (Funs b [dcl])
Rn -> R (Funs a []) (dcl) (Funs b [])
Wrap -> fatal 246 "function res not defined when denote e == Wrap. "
f _ e@(EFlp (EDcD dcl)) ((a,sv),(b,tv)) = res
where
res = case denote e of
Flr -> R (Funs a [dcl]) (Isn tv) (Funs b [])
Frl -> R (Funs a []) (Isn sv) (Funs b [dcl])
Rn -> R (Funs b []) (dcl) (Funs a [])
Wrap -> fatal 253 "function res not defined when denote e == Wrap. "
f exclVars (EFlp e) (a,b) = f exclVars e (b,a)
f _ (EMp1 val _) _ = Atom . showADL $ val
f _ (EDcI _) ((a,_),(b,tv)) = R (Funs a []) (Isn tv) (Funs b [])
f _ (EDcV _) _ = Atom "True"
f _ e _ = fatal 298 ("Non-exhaustive pattern in subexpression "++showADL e++" of assemble (<"++showADL expr++">)")
-- fECps treats the case of a composition. It works as follows:
-- An expression, e.g. r;s;t , is translated to Exists (zip ivs ics) (Conj (frels s t)),
-- in which ivs is a list of variables that are used inside the resulting expression,
-- ics contains their types, and frels s t the subexpressions that
-- are used in the resulting conjuct (at the right of the quantifier).
fECps :: [Var] -> Expression -> (Var,Var) -> PredLogic
fECps exclVars e (a,b)
-- f :: [Var] -> Expression -> (Var,Var) -> PredLogic
| and [isCpl e' | e'<-es] = f exclVars (deMorganECps e) (a,b)
| otherwise = Exists ivs (Conj (frels a b))
where
es :: [Expression]
es = [ x | x<-exprCps2list e, not (isEpsilon x) ]
-- Step 1: split in fragments at those points where an exists-quantifier is needed.
-- Each fragment represents a subexpression with variables
-- at the outside only. Fragments will be reconstructed in a conjunct.
res :: [(Var -> Var -> PredLogic, A_Concept, A_Concept)]
res = pars3 (exclVars++ivs) (split es) -- yields triples (r,s,t): the fragment, its source and target.
-- Step 2: assemble the intermediate variables from at the right spot in each fragment.
frels :: Var -> Var -> [PredLogic]
frels src trg = [r v w | ((r,_,_),v,w)<-zip3 res' (src: ivs) (ivs++[trg]) ]
-- Step 3: compute the intermediate variables and their types
res' :: [(Var -> Var -> PredLogic, A_Concept, A_Concept)]
res' = [triple | triple<-res, not (atomic triple)]
ivs :: [Var]
ivs = mkvar exclVars ics
ics :: [ Either PredLogic A_Concept ] -- each element is either an atom or a concept
ics = concat
[ case (v',w) of
(Left _, Left _ ) -> []
(Left atom, Right _ ) -> [ Left atom ]
(Right _ , Left atom) -> [ Left atom ]
(Right trg, Right _ ) -> [ Right trg ] -- SJ 20131117, was: (if trg==src then [ Right trg ] else [ Right (trg `meet` src) ])
-- This code assumes no ISA's in the A-structure. This works due to the introduction of EEps expressions.
| (v',w)<-zip [ case l ("",src) ("",trg) of
atom@Atom{} -> Left atom
_ -> Right trg
| (l,src,trg)<-init res]
[ case r ("",src) ("",trg) of
atom@Atom{} -> Left atom
_ -> Right src
| (r,src,trg)<-tail res]
]
atomic :: (Var -> Var -> PredLogic, A_Concept, A_Concept) -> Bool
atomic (r,a,b) = case r ("",a) ("",b) of
Atom{} -> True
_ -> False
mkvar :: [Var] -> [ Either PredLogic A_Concept ] -> [Var]
mkvar exclVars (Right z: ics) = let vz = head (mkVar exclVars [z]) in vz: mkvar (exclVars++[vz]) ics
mkvar exclVars (Left _: ics) = mkvar exclVars ics
mkvar _ [] = []
fERad :: [Var] -> Expression -> (Var,Var) -> PredLogic
fERad exclVars e (a,b)
| and[isCpl e' |e'<-es] = f exclVars (deMorganERad e) (a,b) -- e.g. -r!-s!-t
| isCpl (head es) = f exclVars (foldr1 (.:.) antr .\. foldr1 (.!.) conr) (a,b) -- e.g. -r!-s! t antr cannot be empty, because isCpl (head es) is True; conr cannot be empty, because es has an element that is not isCpl.
| isCpl (last es) = f exclVars (foldr1 (.!.) conl ./. foldr1 (.:.) antl) (a,b) -- e.g. r!-s!-t antl cannot be empty, because isCpl (head es) is True; conl cannot be empty, because es has an element that is not isCpl.
| otherwise = Forall ivs (Disj (frels a b)) -- e.g. r!-s! t the condition or [isCpl e' |e'<-es] is true.
{- was:
| otherwise = Forall ivs (Disj alls)
where alls = [f (exclVars++ivs) e' (sv,tv) | (e',(sv,tv))<-zip es (zip (a:ivs) (ivs++[b]))]
-}
where
es = [ x | x<-exprRad2list e, not (isEpsilon x) ] -- The definition of exprRad2list guarantees that length es>=2
res = pars3 (exclVars++ivs) (split es) -- yields triples (r,s,t): the fragment, its source and target.
conr = dropWhile isCpl es -- There is at least one positive term, because conr is used in the second alternative (and the first alternative deals with absence of positive terms).
-- So conr is not empty.
antr = let x = (map notCpl.map flp.reverse.takeWhile isCpl) es in
if null x then fatal 367 ("Entering in an empty foldr1") else x
conl = let x = (reverse.dropWhile isCpl.reverse) es in
if null x then fatal 369 ("Entering in an empty foldr1") else x
antl = let x = (map notCpl.map flp.takeWhile isCpl.reverse) es in
if null x then fatal 371 ("Entering in an empty foldr1") else x
-- Step 2: assemble the intermediate variables from at the right spot in each fragment.
frels :: Var -> Var -> [PredLogic]
frels src trg = [r v w | ((r,_,_),v,w)<-zip3 res' (src: ivs) (ivs++[trg]) ]
-- Step 3: compute the intermediate variables and their types
res' :: [(Var -> Var -> PredLogic, A_Concept, A_Concept)]
res' = [triple | triple<-res, not (atomic triple)]
ivs :: [Var]
ivs = mkvar exclVars ics
ics :: [ Either PredLogic A_Concept ] -- each element is either an atom or a concept
ics = concat
[ case (v',w) of
(Left _, Left _ ) -> []
(Left atom, Right _ ) -> [ Left atom ]
(Right _ , Left atom) -> [ Left atom ]
(Right trg, Right _ ) -> [ Right trg ] -- SJ 20131117, was: (if trg==src then [ Right trg ] else [ Right (trg `meet` src) ])
-- This code assumes no ISA's in the A-structure. This works due to the introduction of EEps expressions.
| (v',w)<-zip [ case l ("",src) ("",trg) of
atom@Atom{} -> Left atom
_ -> Right trg
| (l,src,trg)<-init res]
[ case r ("",src) ("",trg) of
atom@Atom{} -> Left atom
_ -> Right src
| (r,src,trg)<-tail res]
]
relFun :: [Var] -> [Expression] -> Expression -> [Expression] -> Var->Var->PredLogic
relFun exclVars lhs e rhs
= case e of
EDcD dcl -> \sv tv->R (Funs (fst sv) [r | t'<- lhs, r<-relsMentionedIn t']) dcl (Funs (fst tv) [r | t'<-reverse rhs, r<-relsMentionedIn t'])
EFlp (EDcD dcl) -> \sv tv->R (Funs (fst tv) [r | t'<-reverse rhs, r<-relsMentionedIn t']) dcl (Funs (fst sv) [r | t'<- lhs, r<-relsMentionedIn t'])
EMp1 val _ -> \_ _-> Atom . showADL $ val
EFlp EMp1{} -> relFun exclVars lhs e rhs
_ -> \sv tv->f (exclVars++[sv,tv]) e (sv,tv)
pars3 :: [Var] -> [[Expression]] -> [(Var -> Var -> PredLogic, A_Concept, A_Concept)]
pars3 exclVars (lhs: [e]: rhs: ts)
| denotes lhs==Flr && denote e==Rn && denotes rhs==Frl
= ( relFun exclVars lhs e rhs, source (head lhs), target (last rhs)): pars3 exclVars ts
| otherwise = pars2 exclVars (lhs:[e]:rhs:ts)
pars3 exclVars ts = pars2 exclVars ts -- for lists shorter than 3
pars2 :: [Var] -> [[Expression]]-> [(Var -> Var -> PredLogic, A_Concept, A_Concept)]
pars2 exclVars (lhs: [e]: ts)
| denotes lhs==Flr && denote e==Rn
= (relFun exclVars lhs e [], source (head lhs), target e): pars3 exclVars ts
| denotes lhs==Flr && denote e==Frl
= (relFun exclVars lhs (EDcI (source e)) [e], source (head lhs), target e): pars3 exclVars ts
| otherwise = pars1 exclVars (lhs:[e]:ts)
pars2 exclVars ([e]: rhs: ts)
| denotes rhs==Frl && denote e==Rn
= (relFun exclVars [] e rhs, source e, target (last rhs)): pars3 exclVars ts
| denote e==Flr && denotes rhs==Frl
= (relFun exclVars [e] (EDcI (source e)) rhs, source e, target (last rhs)): pars3 exclVars ts
| otherwise = pars1 exclVars ([e]:rhs:ts)
pars2 exclVars (lhs: rhs: ts)
| denotes lhs==Flr && denotes rhs==Frl
= (relFun exclVars lhs (EDcI (source (head rhs))) rhs, source (head lhs), target (last rhs)): pars3 exclVars ts
| otherwise = pars1 exclVars (lhs:rhs:ts)
pars2 exclVars ts = pars1 exclVars ts -- for lists shorter than 2
pars1 :: [Var] -> [[Expression]] -> [(Var -> Var -> PredLogic, A_Concept, A_Concept)]
pars1 exclVars expressions
= case expressions of
[] -> []
(lhs: ts) -> (pars0 exclVars lhs, source (head lhs), target (last lhs)): pars3 exclVars ts
pars0 :: [Var] -> [Expression] -> Var -> Var -> PredLogic
pars0 exclVars lhs
| denotes lhs==Flr = relFun exclVars lhs (EDcI (source (last lhs))) []
| denotes lhs==Frl = relFun exclVars [] (EDcI (target (last lhs))) lhs
| otherwise = relFun exclVars [] (let [r]=lhs in r) []
denote :: Expression -> Notation
denote e = case e of
(EDcD d)
| null([Uni,Inj,Tot,Sur] >- properties d) -> Rn
| isUni d && isTot d -> Flr
| isInj d && isSur d -> Frl
| otherwise -> Rn
_ -> Rn
denotes :: [Expression] -> Notation
denotes = denote . head
split :: [Expression] -> [[Expression]]
split [] = []
split [e] = [[e]]
split (e:e':es)
= --if denote e `eq` Wrap then (e:spl):spls else
if denote e `eq` denote e' then (e:spl):spls else
[e]:spl:spls
where
spl:spls = split (e':es)
Flr `eq` Flr = True
Frl `eq` Frl = True
_ `eq` _ = False
-- mkVar is bedoeld om nieuwe variabelen te genereren, gegeven een set (ex) van reeds vergeven variabelen.
-- mkVar garandeert dat het resultaat niet in ex voorkomt, dus postconditie: not (mkVar ex cs `elem` ex)
-- Dat gebeurt door het toevoegen van apostrofes.
mkVar :: [Var] -> [A_Concept] -> [Var]
mkVar ex cs = mknew (map fst ex) [([(toLower.head.(++"x").name) c],c) |c<-cs]
where
mknew _ [] = []
mknew ex' ((x,c):xs) = if x `elem` ex'
then mknew ex' ((x++"'",c):xs)
else (x,c): mknew (ex'++[x]) xs
|
4ZP6Capstone2015/ampersand
|
src/Database/Design/Ampersand/Output/PredLogic.hs
|
gpl-3.0
| 29,802 | 1 | 19 | 11,686 | 9,253 | 4,892 | 4,361 | 420 | 62 |
{-# OPTIONS_GHC -fno-bang-patterns #-}
-----------------------------------------------------------------------------
-- |
-- Module : Data.Array.Base
-- Copyright : (c) The University of Glasgow 2001
-- License : BSD-style (see the file libraries/base/LICENSE)
--
-- Maintainer : [email protected]
-- Stability : experimental
-- Portability : non-portable (MPTCs, uses Control.Monad.ST)
--
-- Basis for IArray and MArray. Not intended for external consumption;
-- use IArray or MArray instead.
--
-----------------------------------------------------------------------------
-- #hide
module Data.Array.Base where
import Prelude
import Control.Monad.ST.Lazy ( strictToLazyST )
import qualified Control.Monad.ST.Lazy as Lazy (ST)
import Data.Ix ( Ix, range, index, rangeSize )
import Data.Int
import Data.Word
import Foreign.Ptr
import Foreign.StablePtr
import Data.Bits
import Foreign.Storable
import qualified Hugs.Array as Arr
import qualified Hugs.ST as ArrST
import Hugs.Array ( unsafeIndex )
import Hugs.ST ( STArray, ST(..), runST )
import Hugs.ByteArray
import Data.Typeable
-----------------------------------------------------------------------------
-- Class of immutable arrays
{- | Class of immutable array types.
An array type has the form @(a i e)@ where @a@ is the array type
constructor (kind @* -> * -> *@), @i@ is the index type (a member of
the class 'Ix'), and @e@ is the element type. The @IArray@ class is
parameterised over both @a@ and @e@, so that instances specialised to
certain element types can be defined.
-}
class IArray a e where
-- | Extracts the bounds of an immutable array
bounds :: Ix i => a i e -> (i,i)
unsafeArray :: Ix i => (i,i) -> [(Int, e)] -> a i e
unsafeAt :: Ix i => a i e -> Int -> e
unsafeReplace :: Ix i => a i e -> [(Int, e)] -> a i e
unsafeAccum :: Ix i => (e -> e' -> e) -> a i e -> [(Int, e')] -> a i e
unsafeAccumArray :: Ix i => (e -> e' -> e) -> e -> (i,i) -> [(Int, e')] -> a i e
unsafeReplace arr ies = runST (unsafeReplaceST arr ies >>= unsafeFreeze)
unsafeAccum f arr ies = runST (unsafeAccumST f arr ies >>= unsafeFreeze)
unsafeAccumArray f e lu ies = runST (unsafeAccumArrayST f e lu ies >>= unsafeFreeze)
{-# INLINE unsafeReplaceST #-}
unsafeReplaceST :: (IArray a e, Ix i) => a i e -> [(Int, e)] -> ST s (STArray s i e)
unsafeReplaceST arr ies = do
marr <- thaw arr
sequence_ [unsafeWrite marr i e | (i, e) <- ies]
return marr
{-# INLINE unsafeAccumST #-}
unsafeAccumST :: (IArray a e, Ix i) => (e -> e' -> e) -> a i e -> [(Int, e')] -> ST s (STArray s i e)
unsafeAccumST f arr ies = do
marr <- thaw arr
sequence_ [do
old <- unsafeRead marr i
unsafeWrite marr i (f old new)
| (i, new) <- ies]
return marr
{-# INLINE unsafeAccumArrayST #-}
unsafeAccumArrayST :: Ix i => (e -> e' -> e) -> e -> (i,i) -> [(Int, e')] -> ST s (STArray s i e)
unsafeAccumArrayST f e (l,u) ies = do
marr <- newArray (l,u) e
sequence_ [do
old <- unsafeRead marr i
unsafeWrite marr i (f old new)
| (i, new) <- ies]
return marr
{-# INLINE array #-}
{-| Constructs an immutable array from a pair of bounds and a list of
initial associations.
The bounds are specified as a pair of the lowest and highest bounds in
the array respectively. For example, a one-origin vector of length 10
has bounds (1,10), and a one-origin 10 by 10 matrix has bounds
((1,1),(10,10)).
An association is a pair of the form @(i,x)@, which defines the value of
the array at index @i@ to be @x@. The array is undefined if any index
in the list is out of bounds. If any two associations in the list have
the same index, the value at that index is implementation-dependent.
(In GHC, the last value specified for that index is used.
Other implementations will also do this for unboxed arrays, but Haskell
98 requires that for 'Array' the value at such indices is bottom.)
Because the indices must be checked for these errors, 'array' is
strict in the bounds argument and in the indices of the association
list. Whether @array@ is strict or non-strict in the elements depends
on the array type: 'Data.Array.Array' is a non-strict array type, but
all of the 'Data.Array.Unboxed.UArray' arrays are strict. Thus in a
non-strict array, recurrences such as the following are possible:
> a = array (1,100) ((1,1) : [(i, i * a!(i-1)) | i \<- [2..100]])
Not every index within the bounds of the array need appear in the
association list, but the values associated with indices that do not
appear will be undefined.
If, in any dimension, the lower bound is greater than the upper bound,
then the array is legal, but empty. Indexing an empty array always
gives an array-bounds error, but 'bounds' still yields the bounds with
which the array was constructed.
-}
array :: (IArray a e, Ix i)
=> (i,i) -- ^ bounds of the array: (lowest,highest)
-> [(i, e)] -- ^ list of associations
-> a i e
array (l,u) ies = unsafeArray (l,u) [(index (l,u) i, e) | (i, e) <- ies]
-- Since unsafeFreeze is not guaranteed to be only a cast, we will
-- use unsafeArray and zip instead of a specialized loop to implement
-- listArray, unlike Array.listArray, even though it generates some
-- unnecessary heap allocation. Will use the loop only when we have
-- fast unsafeFreeze, namely for Array and UArray (well, they cover
-- almost all cases).
{-# INLINE listArray #-}
-- | Constructs an immutable array from a list of initial elements.
-- The list gives the elements of the array in ascending order
-- beginning with the lowest index.
listArray :: (IArray a e, Ix i) => (i,i) -> [e] -> a i e
listArray (l,u) es = unsafeArray (l,u) (zip [0 .. rangeSize (l,u) - 1] es)
{-# INLINE listArrayST #-}
listArrayST :: Ix i => (i,i) -> [e] -> ST s (STArray s i e)
listArrayST (l,u) es = do
marr <- newArray_ (l,u)
let n = rangeSize (l,u)
let fillFromList i xs | i == n = return ()
| otherwise = case xs of
[] -> return ()
y:ys -> unsafeWrite marr i y >> fillFromList (i+1) ys
fillFromList 0 es
return marr
{-# RULES
"listArray/Array" listArray =
\lu es -> runST (listArrayST lu es >>= ArrST.unsafeFreezeSTArray)
#-}
{-# INLINE listUArrayST #-}
listUArrayST :: (MArray (STUArray s) e (ST s), Ix i)
=> (i,i) -> [e] -> ST s (STUArray s i e)
listUArrayST (l,u) es = do
marr <- newArray_ (l,u)
let n = rangeSize (l,u)
let fillFromList i xs | i == n = return ()
| otherwise = case xs of
[] -> return ()
y:ys -> unsafeWrite marr i y >> fillFromList (i+1) ys
fillFromList 0 es
return marr
-- I don't know how to write a single rule for listUArrayST, because
-- the type looks like constrained over 's', which runST doesn't
-- like. In fact all MArray (STUArray s) instances are polymorphic
-- wrt. 's', but runST can't know that.
--
-- More precisely, we'd like to write this:
-- listUArray :: (forall s. MArray (STUArray s) e (ST s), Ix i)
-- => (i,i) -> [e] -> UArray i e
-- listUArray lu = runST (listUArrayST lu es >>= unsafeFreezeSTUArray)
-- {-# RULES listArray = listUArray
-- Then we could call listUArray at any type 'e' that had a suitable
-- MArray instance. But sadly we can't, because we don't have quantified
-- constraints. Hence the mass of rules below.
-- I would like also to write a rule for listUArrayST (or listArray or
-- whatever) applied to unpackCString#. Unfortunately unpackCString#
-- calls seem to be floated out, then floated back into the middle
-- of listUArrayST, so I was not able to do this.
{-# INLINE (!) #-}
-- | Returns the element of an immutable array at the specified index.
(!) :: (IArray a e, Ix i) => a i e -> i -> e
arr ! i = case bounds arr of (l,u) -> unsafeAt arr (index (l,u) i)
{-# INLINE indices #-}
-- | Returns a list of all the valid indices in an array.
indices :: (IArray a e, Ix i) => a i e -> [i]
indices arr = case bounds arr of (l,u) -> range (l,u)
{-# INLINE elems #-}
-- | Returns a list of all the elements of an array, in the same order
-- as their indices.
elems :: (IArray a e, Ix i) => a i e -> [e]
elems arr = case bounds arr of
(l,u) -> [unsafeAt arr i | i <- [0 .. rangeSize (l,u) - 1]]
{-# INLINE assocs #-}
-- | Returns the contents of an array as a list of associations.
assocs :: (IArray a e, Ix i) => a i e -> [(i, e)]
assocs arr = case bounds arr of
(l,u) -> [(i, unsafeAt arr (unsafeIndex (l,u) i)) | i <- range (l,u)]
{-# INLINE accumArray #-}
{-|
Constructs an immutable array from a list of associations. Unlike
'array', the same index is allowed to occur multiple times in the list
of associations; an /accumulating function/ is used to combine the
values of elements with the same index.
For example, given a list of values of some index type, hist produces
a histogram of the number of occurrences of each index within a
specified range:
> hist :: (Ix a, Num b) => (a,a) -> [a] -> Array a b
> hist bnds is = accumArray (+) 0 bnds [(i, 1) | i\<-is, inRange bnds i]
-}
accumArray :: (IArray a e, Ix i)
=> (e -> e' -> e) -- ^ An accumulating function
-> e -- ^ A default element
-> (i,i) -- ^ The bounds of the array
-> [(i, e')] -- ^ List of associations
-> a i e -- ^ Returns: the array
accumArray f init (l,u) ies =
unsafeAccumArray f init (l,u) [(index (l,u) i, e) | (i, e) <- ies]
{-# INLINE (//) #-}
{-|
Takes an array and a list of pairs and returns an array identical to
the left argument except that it has been updated by the associations
in the right argument. For example, if m is a 1-origin, n by n matrix,
then @m\/\/[((i,i), 0) | i \<- [1..n]]@ is the same matrix, except with
the diagonal zeroed.
As with the 'array' function, if any two associations in the list have
the same index, the value at that index is implementation-dependent.
(In GHC, the last value specified for that index is used.
Other implementations will also do this for unboxed arrays, but Haskell
98 requires that for 'Array' the value at such indices is bottom.)
For most array types, this operation is O(/n/) where /n/ is the size
of the array. However, the 'Data.Array.Diff.DiffArray' type provides
this operation with complexity linear in the number of updates.
-}
(//) :: (IArray a e, Ix i) => a i e -> [(i, e)] -> a i e
arr // ies = case bounds arr of
(l,u) -> unsafeReplace arr [(index (l,u) i, e) | (i, e) <- ies]
{-# INLINE accum #-}
{-|
@accum f@ takes an array and an association list and accumulates pairs
from the list into the array with the accumulating function @f@. Thus
'accumArray' can be defined using 'accum':
> accumArray f z b = accum f (array b [(i, z) | i \<- range b])
-}
accum :: (IArray a e, Ix i) => (e -> e' -> e) -> a i e -> [(i, e')] -> a i e
accum f arr ies = case bounds arr of
(l,u) -> unsafeAccum f arr [(index (l,u) i, e) | (i, e) <- ies]
{-# INLINE amap #-}
-- | Returns a new array derived from the original array by applying a
-- function to each of the elements.
amap :: (IArray a e', IArray a e, Ix i) => (e' -> e) -> a i e' -> a i e
amap f arr = case bounds arr of
(l,u) -> unsafeArray (l,u) [(i, f (unsafeAt arr i)) |
i <- [0 .. rangeSize (l,u) - 1]]
{-# INLINE ixmap #-}
-- | Returns a new array derived from the original array by applying a
-- function to each of the indices.
ixmap :: (IArray a e, Ix i, Ix j) => (i,i) -> (i -> j) -> a j e -> a i e
ixmap (l,u) f arr =
unsafeArray (l,u) [(unsafeIndex (l,u) i, arr ! f i) | i <- range (l,u)]
-----------------------------------------------------------------------------
-- Normal polymorphic arrays
instance IArray Arr.Array e where
{-# INLINE bounds #-}
bounds = Arr.bounds
{-# INLINE unsafeArray #-}
unsafeArray = Arr.unsafeArray
{-# INLINE unsafeAt #-}
unsafeAt = Arr.unsafeAt
{-# INLINE unsafeReplace #-}
unsafeReplace = Arr.unsafeReplace
{-# INLINE unsafeAccum #-}
unsafeAccum = Arr.unsafeAccum
{-# INLINE unsafeAccumArray #-}
unsafeAccumArray = Arr.unsafeAccumArray
-----------------------------------------------------------------------------
-- Flat unboxed arrays
-- | Arrays with unboxed elements. Instances of 'IArray' are provided
-- for 'UArray' with certain element types ('Int', 'Float', 'Char',
-- etc.; see the 'UArray' class for a full list).
--
-- A 'UArray' will generally be more efficient (in terms of both time
-- and space) than the equivalent 'Data.Array.Array' with the same
-- element type. However, 'UArray' is strict in its elements - so
-- don\'t use 'UArray' if you require the non-strictness that
-- 'Data.Array.Array' provides.
--
-- Because the @IArray@ interface provides operations overloaded on
-- the type of the array, it should be possible to just change the
-- array type being used by a program from say @Array@ to @UArray@ to
-- get the benefits of unboxed arrays (don\'t forget to import
-- "Data.Array.Unboxed" instead of "Data.Array").
--
data UArray i e = UArray !i !i !ByteArray
uArrayTc = mkTyCon "UArray"; instance Typeable2 UArray where { typeOf2 _ = mkTyConApp uArrayTc [] }; instance Typeable a => Typeable1 (UArray a) where { typeOf1 = typeOf1Default }; instance (Typeable a, Typeable b) => Typeable (UArray a b) where { typeOf = typeOfDefault }
{-# INLINE unsafeArrayUArray #-}
unsafeArrayUArray :: (MArray (STUArray s) e (ST s), Ix i)
=> (i,i) -> [(Int, e)] -> e -> ST s (UArray i e)
unsafeArrayUArray (l,u) ies default_elem = do
marr <- newArray (l,u) default_elem
sequence_ [unsafeWrite marr i e | (i, e) <- ies]
unsafeFreezeSTUArray marr
unsafeFreezeSTUArray :: STUArray s i e -> ST s (UArray i e)
unsafeFreezeSTUArray (STUArray l u marr) = do
arr <- unsafeFreezeMutableByteArray marr
return (UArray l u arr)
{-# INLINE unsafeReplaceUArray #-}
unsafeReplaceUArray :: (MArray (STUArray s) e (ST s), Ix i)
=> UArray i e -> [(Int, e)] -> ST s (UArray i e)
unsafeReplaceUArray arr ies = do
marr <- thawSTUArray arr
sequence_ [unsafeWrite marr i e | (i, e) <- ies]
unsafeFreezeSTUArray marr
{-# INLINE unsafeAccumUArray #-}
unsafeAccumUArray :: (MArray (STUArray s) e (ST s), Ix i)
=> (e -> e' -> e) -> UArray i e -> [(Int, e')] -> ST s (UArray i e)
unsafeAccumUArray f arr ies = do
marr <- thawSTUArray arr
sequence_ [do
old <- unsafeRead marr i
unsafeWrite marr i (f old new)
| (i, new) <- ies]
unsafeFreezeSTUArray marr
{-# INLINE unsafeAccumArrayUArray #-}
unsafeAccumArrayUArray :: (MArray (STUArray s) e (ST s), Ix i)
=> (e -> e' -> e) -> e -> (i,i) -> [(Int, e')] -> ST s (UArray i e)
unsafeAccumArrayUArray f init (l,u) ies = do
marr <- newArray (l,u) init
sequence_ [do
old <- unsafeRead marr i
unsafeWrite marr i (f old new)
| (i, new) <- ies]
unsafeFreezeSTUArray marr
{-# INLINE eqUArray #-}
eqUArray :: (IArray UArray e, Ix i, Eq e) => UArray i e -> UArray i e -> Bool
eqUArray arr1@(UArray l1 u1 _) arr2@(UArray l2 u2 _) =
if rangeSize (l1,u1) == 0 then rangeSize (l2,u2) == 0 else
l1 == l2 && u1 == u2 &&
and [unsafeAt arr1 i == unsafeAt arr2 i | i <- [0 .. rangeSize (l1,u1) - 1]]
{-# INLINE cmpUArray #-}
cmpUArray :: (IArray UArray e, Ix i, Ord e) => UArray i e -> UArray i e -> Ordering
cmpUArray arr1 arr2 = compare (assocs arr1) (assocs arr2)
{-# INLINE cmpIntUArray #-}
cmpIntUArray :: (IArray UArray e, Ord e) => UArray Int e -> UArray Int e -> Ordering
cmpIntUArray arr1@(UArray l1 u1 _) arr2@(UArray l2 u2 _) =
if rangeSize (l1,u1) == 0 then if rangeSize (l2,u2) == 0 then EQ else LT else
if rangeSize (l2,u2) == 0 then GT else
case compare l1 l2 of
EQ -> foldr cmp (compare u1 u2) [0 .. rangeSize (l1, min u1 u2) - 1]
other -> other
where
cmp i rest = case compare (unsafeAt arr1 i) (unsafeAt arr2 i) of
EQ -> rest
other -> other
{-# RULES "cmpUArray/Int" cmpUArray = cmpIntUArray #-}
-----------------------------------------------------------------------------
-- Showing IArrays
{-# SPECIALISE
showsIArray :: (IArray UArray e, Ix i, Show i, Show e) =>
Int -> UArray i e -> ShowS
#-}
showsIArray :: (IArray a e, Ix i, Show i, Show e) => Int -> a i e -> ShowS
showsIArray p a =
showParen (p > 9) $
showString "array " .
shows (bounds a) .
showChar ' ' .
shows (assocs a)
-----------------------------------------------------------------------------
-- Flat unboxed arrays: instances
unsafeAtBArray :: Storable e => UArray i e -> Int -> e
unsafeAtBArray (UArray _ _ arr) = readByteArray arr
instance IArray UArray Bool where
{-# INLINE bounds #-}
bounds (UArray l u _) = (l,u)
{-# INLINE unsafeArray #-}
unsafeArray lu ies = runST (unsafeArrayUArray lu ies False)
unsafeAt (UArray _ _ arr) i =
testBit (readByteArray arr (bOOL_INDEX i)::BitSet) (bOOL_SUBINDEX i)
{-# INLINE unsafeReplace #-}
unsafeReplace arr ies = runST (unsafeReplaceUArray arr ies)
{-# INLINE unsafeAccum #-}
unsafeAccum f arr ies = runST (unsafeAccumUArray f arr ies)
{-# INLINE unsafeAccumArray #-}
unsafeAccumArray f init lu ies = runST (unsafeAccumArrayUArray f init lu ies)
instance IArray UArray Char where
{-# INLINE bounds #-}
bounds (UArray l u _) = (l,u)
{-# INLINE unsafeArray #-}
unsafeArray lu ies = runST (unsafeArrayUArray lu ies '\0')
{-# INLINE unsafeAt #-}
unsafeAt = unsafeAtBArray
{-# INLINE unsafeReplace #-}
unsafeReplace arr ies = runST (unsafeReplaceUArray arr ies)
{-# INLINE unsafeAccum #-}
unsafeAccum f arr ies = runST (unsafeAccumUArray f arr ies)
{-# INLINE unsafeAccumArray #-}
unsafeAccumArray f init lu ies = runST (unsafeAccumArrayUArray f init lu ies)
instance IArray UArray Int where
{-# INLINE bounds #-}
bounds (UArray l u _) = (l,u)
{-# INLINE unsafeArray #-}
unsafeArray lu ies = runST (unsafeArrayUArray lu ies 0)
unsafeAt = unsafeAtBArray
{-# INLINE unsafeReplace #-}
unsafeReplace arr ies = runST (unsafeReplaceUArray arr ies)
{-# INLINE unsafeAccum #-}
unsafeAccum f arr ies = runST (unsafeAccumUArray f arr ies)
{-# INLINE unsafeAccumArray #-}
unsafeAccumArray f init lu ies = runST (unsafeAccumArrayUArray f init lu ies)
instance IArray UArray Word where
{-# INLINE bounds #-}
bounds (UArray l u _) = (l,u)
{-# INLINE unsafeArray #-}
unsafeArray lu ies = runST (unsafeArrayUArray lu ies 0)
unsafeAt = unsafeAtBArray
{-# INLINE unsafeReplace #-}
unsafeReplace arr ies = runST (unsafeReplaceUArray arr ies)
{-# INLINE unsafeAccum #-}
unsafeAccum f arr ies = runST (unsafeAccumUArray f arr ies)
{-# INLINE unsafeAccumArray #-}
unsafeAccumArray f init lu ies = runST (unsafeAccumArrayUArray f init lu ies)
instance IArray UArray (Ptr a) where
{-# INLINE bounds #-}
bounds (UArray l u _) = (l,u)
{-# INLINE unsafeArray #-}
unsafeArray lu ies = runST (unsafeArrayUArray lu ies nullPtr)
{-# INLINE unsafeAt #-}
unsafeAt = unsafeAtBArray
{-# INLINE unsafeReplace #-}
unsafeReplace arr ies = runST (unsafeReplaceUArray arr ies)
{-# INLINE unsafeAccum #-}
unsafeAccum f arr ies = runST (unsafeAccumUArray f arr ies)
{-# INLINE unsafeAccumArray #-}
unsafeAccumArray f init lu ies = runST (unsafeAccumArrayUArray f init lu ies)
instance IArray UArray (FunPtr a) where
{-# INLINE bounds #-}
bounds (UArray l u _) = (l,u)
{-# INLINE unsafeArray #-}
unsafeArray lu ies = runST (unsafeArrayUArray lu ies nullFunPtr)
unsafeAt = unsafeAtBArray
{-# INLINE unsafeReplace #-}
unsafeReplace arr ies = runST (unsafeReplaceUArray arr ies)
{-# INLINE unsafeAccum #-}
unsafeAccum f arr ies = runST (unsafeAccumUArray f arr ies)
{-# INLINE unsafeAccumArray #-}
unsafeAccumArray f init lu ies = runST (unsafeAccumArrayUArray f init lu ies)
instance IArray UArray Float where
{-# INLINE bounds #-}
bounds (UArray l u _) = (l,u)
{-# INLINE unsafeArray #-}
unsafeArray lu ies = runST (unsafeArrayUArray lu ies 0)
unsafeAt = unsafeAtBArray
{-# INLINE unsafeReplace #-}
unsafeReplace arr ies = runST (unsafeReplaceUArray arr ies)
{-# INLINE unsafeAccum #-}
unsafeAccum f arr ies = runST (unsafeAccumUArray f arr ies)
{-# INLINE unsafeAccumArray #-}
unsafeAccumArray f init lu ies = runST (unsafeAccumArrayUArray f init lu ies)
instance IArray UArray Double where
{-# INLINE bounds #-}
bounds (UArray l u _) = (l,u)
{-# INLINE unsafeArray #-}
unsafeArray lu ies = runST (unsafeArrayUArray lu ies 0)
unsafeAt = unsafeAtBArray
{-# INLINE unsafeReplace #-}
unsafeReplace arr ies = runST (unsafeReplaceUArray arr ies)
{-# INLINE unsafeAccum #-}
unsafeAccum f arr ies = runST (unsafeAccumUArray f arr ies)
{-# INLINE unsafeAccumArray #-}
unsafeAccumArray f init lu ies = runST (unsafeAccumArrayUArray f init lu ies)
instance IArray UArray (StablePtr a) where
{-# INLINE bounds #-}
bounds (UArray l u _) = (l,u)
{-# INLINE unsafeArray #-}
unsafeArray lu ies = runST (unsafeArrayUArray lu ies nullStablePtr)
unsafeAt = unsafeAtBArray
{-# INLINE unsafeReplace #-}
unsafeReplace arr ies = runST (unsafeReplaceUArray arr ies)
{-# INLINE unsafeAccum #-}
unsafeAccum f arr ies = runST (unsafeAccumUArray f arr ies)
{-# INLINE unsafeAccumArray #-}
unsafeAccumArray f init lu ies = runST (unsafeAccumArrayUArray f init lu ies)
-- bogus StablePtr value for initialising a UArray of StablePtr.
nullStablePtr = castPtrToStablePtr nullPtr
instance IArray UArray Int8 where
{-# INLINE bounds #-}
bounds (UArray l u _) = (l,u)
{-# INLINE unsafeArray #-}
unsafeArray lu ies = runST (unsafeArrayUArray lu ies 0)
unsafeAt = unsafeAtBArray
{-# INLINE unsafeReplace #-}
unsafeReplace arr ies = runST (unsafeReplaceUArray arr ies)
{-# INLINE unsafeAccum #-}
unsafeAccum f arr ies = runST (unsafeAccumUArray f arr ies)
{-# INLINE unsafeAccumArray #-}
unsafeAccumArray f init lu ies = runST (unsafeAccumArrayUArray f init lu ies)
instance IArray UArray Int16 where
{-# INLINE bounds #-}
bounds (UArray l u _) = (l,u)
{-# INLINE unsafeArray #-}
unsafeArray lu ies = runST (unsafeArrayUArray lu ies 0)
unsafeAt = unsafeAtBArray
{-# INLINE unsafeReplace #-}
unsafeReplace arr ies = runST (unsafeReplaceUArray arr ies)
{-# INLINE unsafeAccum #-}
unsafeAccum f arr ies = runST (unsafeAccumUArray f arr ies)
{-# INLINE unsafeAccumArray #-}
unsafeAccumArray f init lu ies = runST (unsafeAccumArrayUArray f init lu ies)
instance IArray UArray Int32 where
{-# INLINE bounds #-}
bounds (UArray l u _) = (l,u)
{-# INLINE unsafeArray #-}
unsafeArray lu ies = runST (unsafeArrayUArray lu ies 0)
unsafeAt = unsafeAtBArray
{-# INLINE unsafeReplace #-}
unsafeReplace arr ies = runST (unsafeReplaceUArray arr ies)
{-# INLINE unsafeAccum #-}
unsafeAccum f arr ies = runST (unsafeAccumUArray f arr ies)
{-# INLINE unsafeAccumArray #-}
unsafeAccumArray f init lu ies = runST (unsafeAccumArrayUArray f init lu ies)
instance IArray UArray Int64 where
{-# INLINE bounds #-}
bounds (UArray l u _) = (l,u)
{-# INLINE unsafeArray #-}
unsafeArray lu ies = runST (unsafeArrayUArray lu ies 0)
unsafeAt = unsafeAtBArray
{-# INLINE unsafeReplace #-}
unsafeReplace arr ies = runST (unsafeReplaceUArray arr ies)
{-# INLINE unsafeAccum #-}
unsafeAccum f arr ies = runST (unsafeAccumUArray f arr ies)
{-# INLINE unsafeAccumArray #-}
unsafeAccumArray f init lu ies = runST (unsafeAccumArrayUArray f init lu ies)
instance IArray UArray Word8 where
{-# INLINE bounds #-}
bounds (UArray l u _) = (l,u)
{-# INLINE unsafeArray #-}
unsafeArray lu ies = runST (unsafeArrayUArray lu ies 0)
unsafeAt = unsafeAtBArray
{-# INLINE unsafeReplace #-}
unsafeReplace arr ies = runST (unsafeReplaceUArray arr ies)
{-# INLINE unsafeAccum #-}
unsafeAccum f arr ies = runST (unsafeAccumUArray f arr ies)
{-# INLINE unsafeAccumArray #-}
unsafeAccumArray f init lu ies = runST (unsafeAccumArrayUArray f init lu ies)
instance IArray UArray Word16 where
{-# INLINE bounds #-}
bounds (UArray l u _) = (l,u)
{-# INLINE unsafeArray #-}
unsafeArray lu ies = runST (unsafeArrayUArray lu ies 0)
unsafeAt = unsafeAtBArray
{-# INLINE unsafeReplace #-}
unsafeReplace arr ies = runST (unsafeReplaceUArray arr ies)
{-# INLINE unsafeAccum #-}
unsafeAccum f arr ies = runST (unsafeAccumUArray f arr ies)
{-# INLINE unsafeAccumArray #-}
unsafeAccumArray f init lu ies = runST (unsafeAccumArrayUArray f init lu ies)
instance IArray UArray Word32 where
{-# INLINE bounds #-}
bounds (UArray l u _) = (l,u)
{-# INLINE unsafeArray #-}
unsafeArray lu ies = runST (unsafeArrayUArray lu ies 0)
unsafeAt = unsafeAtBArray
{-# INLINE unsafeReplace #-}
unsafeReplace arr ies = runST (unsafeReplaceUArray arr ies)
{-# INLINE unsafeAccum #-}
unsafeAccum f arr ies = runST (unsafeAccumUArray f arr ies)
{-# INLINE unsafeAccumArray #-}
unsafeAccumArray f init lu ies = runST (unsafeAccumArrayUArray f init lu ies)
instance IArray UArray Word64 where
{-# INLINE bounds #-}
bounds (UArray l u _) = (l,u)
{-# INLINE unsafeArray #-}
unsafeArray lu ies = runST (unsafeArrayUArray lu ies 0)
unsafeAt = unsafeAtBArray
{-# INLINE unsafeReplace #-}
unsafeReplace arr ies = runST (unsafeReplaceUArray arr ies)
{-# INLINE unsafeAccum #-}
unsafeAccum f arr ies = runST (unsafeAccumUArray f arr ies)
{-# INLINE unsafeAccumArray #-}
unsafeAccumArray f init lu ies = runST (unsafeAccumArrayUArray f init lu ies)
instance (Ix ix, Eq e, IArray UArray e) => Eq (UArray ix e) where
(==) = eqUArray
instance (Ix ix, Ord e, IArray UArray e) => Ord (UArray ix e) where
compare = cmpUArray
instance (Ix ix, Show ix, Show e, IArray UArray e) => Show (UArray ix e) where
showsPrec = showsIArray
-----------------------------------------------------------------------------
-- Mutable arrays
{-# NOINLINE arrEleBottom #-}
arrEleBottom :: a
arrEleBottom = error "MArray: undefined array element"
{-| Class of mutable array types.
An array type has the form @(a i e)@ where @a@ is the array type
constructor (kind @* -> * -> *@), @i@ is the index type (a member of
the class 'Ix'), and @e@ is the element type.
The @MArray@ class is parameterised over both @a@ and @e@ (so that
instances specialised to certain element types can be defined, in the
same way as for 'IArray'), and also over the type of the monad, @m@,
in which the mutable array will be manipulated.
-}
class (Monad m) => MArray a e m where
-- | Returns the bounds of the array
getBounds :: Ix i => a i e -> m (i,i)
-- | Builds a new array, with every element initialised to the supplied
-- value.
newArray :: Ix i => (i,i) -> e -> m (a i e)
-- | Builds a new array, with every element initialised to undefined.
newArray_ :: Ix i => (i,i) -> m (a i e)
unsafeRead :: Ix i => a i e -> Int -> m e
unsafeWrite :: Ix i => a i e -> Int -> e -> m ()
{-# INLINE newArray #-}
-- The INLINE is crucial, because until we know at least which monad
-- we are in, the code below allocates like crazy. So inline it,
-- in the hope that the context will know the monad.
newArray (l,u) init = do
marr <- newArray_ (l,u)
sequence_ [unsafeWrite marr i init | i <- [0 .. rangeSize (l,u) - 1]]
return marr
newArray_ (l,u) = newArray (l,u) arrEleBottom
-- newArray takes an initialiser which all elements of
-- the newly created array are initialised to. newArray_ takes
-- no initialiser, it is assumed that the array is initialised with
-- "undefined" values.
-- why not omit newArray_? Because in the unboxed array case we would
-- like to omit the initialisation altogether if possible. We can't do
-- this for boxed arrays, because the elements must all have valid values
-- at all times in case of garbage collection.
-- why not omit newArray? Because in the boxed case, we can omit the
-- default initialisation with undefined values if we *do* know the
-- initial value and it is constant for all elements.
{-# INLINE newListArray #-}
-- | Constructs a mutable array from a list of initial elements.
-- The list gives the elements of the array in ascending order
-- beginning with the lowest index.
newListArray :: (MArray a e m, Ix i) => (i,i) -> [e] -> m (a i e)
newListArray (l,u) es = do
marr <- newArray_ (l,u)
let n = rangeSize (l,u)
let fillFromList i xs | i == n = return ()
| otherwise = case xs of
[] -> return ()
y:ys -> unsafeWrite marr i y >> fillFromList (i+1) ys
fillFromList 0 es
return marr
{-# INLINE readArray #-}
-- | Read an element from a mutable array
readArray :: (MArray a e m, Ix i) => a i e -> i -> m e
readArray marr i = do
(l,u) <- getBounds marr
unsafeRead marr (index (l,u) i)
{-# INLINE writeArray #-}
-- | Write an element in a mutable array
writeArray :: (MArray a e m, Ix i) => a i e -> i -> e -> m ()
writeArray marr i e = do
(l,u) <- getBounds marr
unsafeWrite marr (index (l,u) i) e
{-# INLINE getElems #-}
-- | Return a list of all the elements of a mutable array
getElems :: (MArray a e m, Ix i) => a i e -> m [e]
getElems marr = do
(l,u) <- getBounds marr
sequence [unsafeRead marr i | i <- [0 .. rangeSize (l,u) - 1]]
{-# INLINE getAssocs #-}
-- | Return a list of all the associations of a mutable array, in
-- index order.
getAssocs :: (MArray a e m, Ix i) => a i e -> m [(i, e)]
getAssocs marr = do
(l,u) <- getBounds marr
sequence [ do e <- unsafeRead marr (index (l,u) i); return (i,e)
| i <- range (l,u)]
{-# INLINE mapArray #-}
-- | Constructs a new array derived from the original array by applying a
-- function to each of the elements.
mapArray :: (MArray a e' m, MArray a e m, Ix i) => (e' -> e) -> a i e' -> m (a i e)
mapArray f marr = do
(l,u) <- getBounds marr
marr' <- newArray_ (l,u)
sequence_ [do
e <- unsafeRead marr i
unsafeWrite marr' i (f e)
| i <- [0 .. rangeSize (l,u) - 1]]
return marr'
{-# INLINE mapIndices #-}
-- | Constructs a new array derived from the original array by applying a
-- function to each of the indices.
mapIndices :: (MArray a e m, Ix i, Ix j) => (i,i) -> (i -> j) -> a j e -> m (a i e)
mapIndices (l,u) f marr = do
marr' <- newArray_ (l,u)
sequence_ [do
e <- readArray marr (f i)
unsafeWrite marr' (unsafeIndex (l,u) i) e
| i <- range (l,u)]
return marr'
-----------------------------------------------------------------------------
-- Polymorphic non-strict mutable arrays (ST monad)
instance MArray (STArray s) e (ST s) where
{-# INLINE getBounds #-}
getBounds arr = return $! ArrST.boundsSTArray arr
{-# INLINE newArray #-}
newArray = ArrST.newSTArray
{-# INLINE unsafeRead #-}
unsafeRead = ArrST.unsafeReadSTArray
{-# INLINE unsafeWrite #-}
unsafeWrite = ArrST.unsafeWriteSTArray
instance MArray (STArray s) e (Lazy.ST s) where
{-# INLINE getBounds #-}
getBounds arr = strictToLazyST (return $! ArrST.boundsSTArray arr)
{-# INLINE newArray #-}
newArray (l,u) e = strictToLazyST (ArrST.newSTArray (l,u) e)
{-# INLINE unsafeRead #-}
unsafeRead arr i = strictToLazyST (ArrST.unsafeReadSTArray arr i)
{-# INLINE unsafeWrite #-}
unsafeWrite arr i e = strictToLazyST (ArrST.unsafeWriteSTArray arr i e)
sTArrayTc = mkTyCon "STArray"; instance Typeable3 STArray where { typeOf3 _ = mkTyConApp sTArrayTc [] }; instance Typeable a => Typeable2 (STArray a) where { typeOf2 = typeOf2Default }; instance (Typeable a, Typeable b) => Typeable1 (STArray a b) where { typeOf1 = typeOf1Default }; instance (Typeable a, Typeable b, Typeable c) => Typeable (STArray a b c) where { typeOf = typeOfDefault }
-----------------------------------------------------------------------------
-- Flat unboxed mutable arrays (ST monad)
-- | A mutable array with unboxed elements, that can be manipulated in
-- the 'ST' monad. The type arguments are as follows:
--
-- * @s@: the state variable argument for the 'ST' type
--
-- * @i@: the index type of the array (should be an instance of @Ix@)
--
-- * @e@: the element type of the array. Only certain element types
-- are supported.
--
-- An 'STUArray' will generally be more efficient (in terms of both time
-- and space) than the equivalent boxed version ('STArray') with the same
-- element type. However, 'STUArray' is strict in its elements - so
-- don\'t use 'STUArray' if you require the non-strictness that
-- 'STArray' provides.
data STUArray s i a = STUArray !i !i !(MutableByteArray s)
stUArrayTc = mkTyCon "STUArray"; instance Typeable3 STUArray where { typeOf3 _ = mkTyConApp stUArrayTc [] }; instance Typeable a => Typeable2 (STUArray a) where { typeOf2 = typeOf2Default }; instance (Typeable a, Typeable b) => Typeable1 (STUArray a b) where { typeOf1 = typeOf1Default }; instance (Typeable a, Typeable b, Typeable c) => Typeable (STUArray a b c) where { typeOf = typeOfDefault }
newMBArray_ :: (Ix i, Storable e) => (i,i) -> ST s (STUArray s i e)
newMBArray_ = makeArray undefined
where
makeArray :: (Ix i, Storable e) => e -> (i,i) -> ST s (STUArray s i e)
makeArray dummy (l,u) = do
marr <- newMutableByteArray (rangeSize (l,u) * sizeOf dummy)
return (STUArray l u marr)
unsafeReadMBArray :: Storable e => STUArray s i e -> Int -> ST s e
unsafeReadMBArray (STUArray _ _ marr) = readMutableByteArray marr
unsafeWriteMBArray :: Storable e => STUArray s i e -> Int -> e -> ST s ()
unsafeWriteMBArray (STUArray _ _ marr) = writeMutableByteArray marr
getBoundsMBArray (STUArray l u _) = return (l,u)
instance MArray (STUArray s) Bool (ST s) where
getBounds = getBoundsMBArray
newArray_ (l,u) = do
marr <- newMutableByteArray (bOOL_SCALE (rangeSize (l,u)))
return (STUArray l u marr)
unsafeRead (STUArray _ _ marr) i = do
let ix = bOOL_INDEX i
bit = bOOL_SUBINDEX i
w <- readMutableByteArray marr ix
return (testBit (w::BitSet) bit)
unsafeWrite (STUArray _ _ marr) i e = do
let ix = bOOL_INDEX i
bit = bOOL_SUBINDEX i
w <- readMutableByteArray marr ix
writeMutableByteArray marr ix
(if e then setBit (w::BitSet) bit else clearBit w bit)
instance MArray (STUArray s) Char (ST s) where
getBounds = getBoundsMBArray
newArray_ = newMBArray_
unsafeRead = unsafeReadMBArray
unsafeWrite = unsafeWriteMBArray
instance MArray (STUArray s) Int (ST s) where
getBounds = getBoundsMBArray
newArray_ = newMBArray_
unsafeRead = unsafeReadMBArray
unsafeWrite = unsafeWriteMBArray
instance MArray (STUArray s) Word (ST s) where
getBounds = getBoundsMBArray
newArray_ = newMBArray_
unsafeRead = unsafeReadMBArray
unsafeWrite = unsafeWriteMBArray
instance MArray (STUArray s) (Ptr a) (ST s) where
getBounds = getBoundsMBArray
newArray_ = newMBArray_
unsafeRead = unsafeReadMBArray
unsafeWrite = unsafeWriteMBArray
instance MArray (STUArray s) (FunPtr a) (ST s) where
getBounds = getBoundsMBArray
newArray_ = newMBArray_
unsafeRead = unsafeReadMBArray
unsafeWrite = unsafeWriteMBArray
instance MArray (STUArray s) Float (ST s) where
getBounds = getBoundsMBArray
newArray_ = newMBArray_
unsafeRead = unsafeReadMBArray
unsafeWrite = unsafeWriteMBArray
instance MArray (STUArray s) Double (ST s) where
getBounds = getBoundsMBArray
newArray_ = newMBArray_
unsafeRead = unsafeReadMBArray
unsafeWrite = unsafeWriteMBArray
instance MArray (STUArray s) (StablePtr a) (ST s) where
getBounds = getBoundsMBArray
newArray_ = newMBArray_
unsafeRead = unsafeReadMBArray
unsafeWrite = unsafeWriteMBArray
instance MArray (STUArray s) Int8 (ST s) where
getBounds = getBoundsMBArray
newArray_ = newMBArray_
unsafeRead = unsafeReadMBArray
unsafeWrite = unsafeWriteMBArray
instance MArray (STUArray s) Int16 (ST s) where
getBounds = getBoundsMBArray
newArray_ = newMBArray_
unsafeRead = unsafeReadMBArray
unsafeWrite = unsafeWriteMBArray
instance MArray (STUArray s) Int32 (ST s) where
getBounds = getBoundsMBArray
newArray_ = newMBArray_
unsafeRead = unsafeReadMBArray
unsafeWrite = unsafeWriteMBArray
instance MArray (STUArray s) Int64 (ST s) where
getBounds = getBoundsMBArray
newArray_ = newMBArray_
unsafeRead = unsafeReadMBArray
unsafeWrite = unsafeWriteMBArray
instance MArray (STUArray s) Word8 (ST s) where
getBounds = getBoundsMBArray
newArray_ = newMBArray_
unsafeRead = unsafeReadMBArray
unsafeWrite = unsafeWriteMBArray
instance MArray (STUArray s) Word16 (ST s) where
getBounds = getBoundsMBArray
newArray_ = newMBArray_
unsafeRead = unsafeReadMBArray
unsafeWrite = unsafeWriteMBArray
instance MArray (STUArray s) Word32 (ST s) where
getBounds = getBoundsMBArray
newArray_ = newMBArray_
unsafeRead = unsafeReadMBArray
unsafeWrite = unsafeWriteMBArray
instance MArray (STUArray s) Word64 (ST s) where
getBounds = getBoundsMBArray
newArray_ = newMBArray_
unsafeRead = unsafeReadMBArray
unsafeWrite = unsafeWriteMBArray
type BitSet = Word8
bitSetSize = bitSize (0::BitSet)
bOOL_SCALE :: Int -> Int
bOOL_SCALE n = (n + bitSetSize - 1) `div` bitSetSize
bOOL_INDEX :: Int -> Int
bOOL_INDEX i = i `div` bitSetSize
bOOL_SUBINDEX :: Int -> Int
bOOL_SUBINDEX i = i `mod` bitSetSize
-----------------------------------------------------------------------------
-- Freezing
-- | Converts a mutable array (any instance of 'MArray') to an
-- immutable array (any instance of 'IArray') by taking a complete
-- copy of it.
freeze :: (Ix i, MArray a e m, IArray b e) => a i e -> m (b i e)
freeze marr = do
(l,u) <- getBounds marr
ies <- sequence [do e <- unsafeRead marr i; return (i,e)
| i <- [0 .. rangeSize (l,u) - 1]]
return (unsafeArray (l,u) ies)
-- In-place conversion of mutable arrays to immutable ones places
-- a proof obligation on the user: no other parts of your code can
-- have a reference to the array at the point where you unsafely
-- freeze it (and, subsequently mutate it, I suspect).
{- |
Converts an mutable array into an immutable array. The
implementation may either simply cast the array from
one type to the other without copying the array, or it
may take a full copy of the array.
Note that because the array is possibly not copied, any subsequent
modifications made to the mutable version of the array may be
shared with the immutable version. It is safe to use, therefore, if
the mutable version is never modified after the freeze operation.
The non-copying implementation is supported between certain pairs
of array types only; one constraint is that the array types must
have identical representations. In GHC, The following pairs of
array types have a non-copying O(1) implementation of
'unsafeFreeze'. Because the optimised versions are enabled by
specialisations, you will need to compile with optimisation (-O) to
get them.
* 'Data.Array.IO.IOUArray' -> 'Data.Array.Unboxed.UArray'
* 'Data.Array.ST.STUArray' -> 'Data.Array.Unboxed.UArray'
* 'Data.Array.IO.IOArray' -> 'Data.Array.Array'
* 'Data.Array.ST.STArray' -> 'Data.Array.Array'
-}
{-# INLINE unsafeFreeze #-}
unsafeFreeze :: (Ix i, MArray a e m, IArray b e) => a i e -> m (b i e)
unsafeFreeze = freeze
{-# RULES
"unsafeFreeze/STArray" unsafeFreeze = ArrST.unsafeFreezeSTArray
"unsafeFreeze/STUArray" unsafeFreeze = unsafeFreezeSTUArray
#-}
-----------------------------------------------------------------------------
-- Thawing
-- | Converts an immutable array (any instance of 'IArray') into a
-- mutable array (any instance of 'MArray') by taking a complete copy
-- of it.
thaw :: (Ix i, IArray a e, MArray b e m) => a i e -> m (b i e)
thaw arr = case bounds arr of
(l,u) -> do
marr <- newArray_ (l,u)
sequence_ [unsafeWrite marr i (unsafeAt arr i)
| i <- [0 .. rangeSize (l,u) - 1]]
return marr
thawSTUArray :: Ix i => UArray i e -> ST s (STUArray s i e)
thawSTUArray (UArray l u arr) = do
marr <- thawByteArray arr
return (STUArray l u marr)
-- In-place conversion of immutable arrays to mutable ones places
-- a proof obligation on the user: no other parts of your code can
-- have a reference to the array at the point where you unsafely
-- thaw it (and, subsequently mutate it, I suspect).
{- |
Converts an immutable array into a mutable array. The
implementation may either simply cast the array from
one type to the other without copying the array, or it
may take a full copy of the array.
Note that because the array is possibly not copied, any subsequent
modifications made to the mutable version of the array may be
shared with the immutable version. It is only safe to use,
therefore, if the immutable array is never referenced again in this
thread, and there is no possibility that it can be also referenced
in another thread. If you use an unsafeThaw/write/unsafeFreeze
sequence in a multi-threaded setting, then you must ensure that
this sequence is atomic with respect to other threads, or a garbage
collector crash may result (because the write may be writing to a
frozen array).
The non-copying implementation is supported between certain pairs
of array types only; one constraint is that the array types must
have identical representations. In GHC, The following pairs of
array types have a non-copying O(1) implementation of
'unsafeThaw'. Because the optimised versions are enabled by
specialisations, you will need to compile with optimisation (-O) to
get them.
* 'Data.Array.Unboxed.UArray' -> 'Data.Array.IO.IOUArray'
* 'Data.Array.Unboxed.UArray' -> 'Data.Array.ST.STUArray'
* 'Data.Array.Array' -> 'Data.Array.IO.IOArray'
* 'Data.Array.Array' -> 'Data.Array.ST.STArray'
-}
{-# INLINE unsafeThaw #-}
unsafeThaw :: (Ix i, IArray a e, MArray b e m) => a i e -> m (b i e)
unsafeThaw = thaw
-- | Casts an 'STUArray' with one element type into one with a
-- different element type. All the elements of the resulting array
-- are undefined (unless you know what you\'re doing...).
castSTUArray :: STUArray s ix a -> ST s (STUArray s ix b)
castSTUArray (STUArray l u marr) = return (STUArray l u marr)
|
kaoskorobase/mescaline
|
resources/hugs/packages/base/Data/Array/Base.hs
|
gpl-3.0
| 46,951 | 26 | 17 | 13,510 | 10,730 | 5,647 | 5,083 | -1 | -1 |
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE StandaloneDeriving #-}
module Detector.Type (
module Detector.Type.Common
, module Detector.Type.Identification
, module Detector.Type.PTEtaData
, module Detector.Type.Range
, module Detector.Type.Smearing
, DetectorDescription (..)
, IdentificationDescription (..)
) where
import Data.Functor.Identity
import Data.Text (Text)
--
import YAML.Builder
--
import Detector.Type.Common
import Detector.Type.Identification
import Detector.Type.PTEtaData
import Detector.Type.Range
import Detector.Type.Smearing
--
import Prelude hiding (lines)
data DetectorDescription m =
DetectorDescription { detectorName :: Text
, detectorDescription :: Text
, detectorReference :: Text
, detectorComment :: Text
, detectorValidationInfo :: Text
, detectorRange :: RangeDescription m
, detectorIdentification :: IdentificationDescription m
, detectorSmearing :: SmearingDescription m
}
deriving instance Show (DetectorDescription (Either Import))
deriving instance Show (DetectorDescription Identity)
instance Nameable (DetectorDescription m) where
name = detectorName
instance MakeYaml (DetectorDescription ImportList) where
makeYaml n DetectorDescription {..} =
YObject $ [ ( "Name", mkString (n+defIndent) detectorName )
, ( "Class", mkString (n+defIndent) "TopLevel" )
, ( "Description", mkString (n+defIndent) detectorDescription)
, ( "Reference", mkString (n+defIndent) detectorReference)
, ( "Comment", mkString (n+defIndent) detectorComment )
, ( "ValidationInfo", mkString (n+defIndent) detectorValidationInfo )
, ( "Range", makeYaml (n+defIndent) detectorRange)
, ( "Identification", makeYaml (n+defIndent) detectorIdentification )
, ( "Smearing", makeYaml (n+defIndent) detectorSmearing )
]
instance MakeYaml (DetectorDescription []) where
makeYaml n DetectorDescription {..} =
YObject $ [ ( "Name", mkString (n+defIndent) detectorName )
, ( "Class", mkString (n+defIndent) "TopLevel" )
, ( "Description", mkString (n+defIndent) detectorDescription)
, ( "Reference", mkString (n+defIndent) detectorReference)
, ( "Comment", mkString (n+defIndent) detectorComment )
, ( "ValidationInfo", mkString (n+defIndent) detectorValidationInfo )
, ( "Range", makeYaml (n+defIndent) detectorRange)
, ( "Identification", makeYaml (n+defIndent) detectorIdentification )
, ( "Smearing", makeYaml (n+defIndent) detectorSmearing )
]
|
wavewave/detector-yaml
|
lib/Detector/Type.hs
|
gpl-3.0
| 3,004 | 0 | 11 | 821 | 693 | 406 | 287 | 57 | 0 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-matches #-}
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- |
-- Module : Network.AWS.IAM.ListSSHPublicKeys
-- Copyright : (c) 2013-2015 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Returns information about the SSH public keys associated with the
-- specified IAM user. If there are none, the action returns an empty list.
--
-- The SSH public keys returned by this action are used only for
-- authenticating the IAM user to an AWS CodeCommit repository. For more
-- information about using SSH keys to authenticate to an AWS CodeCommit
-- repository, see
-- <http://docs.aws.amazon.com/codecommit/latest/userguide/setting-up-credentials-ssh.html Set up AWS CodeCommit for SSH Connections>
-- in the /AWS CodeCommit User Guide/.
--
-- Although each user is limited to a small number of keys, you can still
-- paginate the results using the 'MaxItems' and 'Marker' parameters.
--
-- /See:/ <http://docs.aws.amazon.com/IAM/latest/APIReference/API_ListSSHPublicKeys.html AWS API Reference> for ListSSHPublicKeys.
module Network.AWS.IAM.ListSSHPublicKeys
(
-- * Creating a Request
listSSHPublicKeys
, ListSSHPublicKeys
-- * Request Lenses
, lspkUserName
, lspkMarker
, lspkMaxItems
-- * Destructuring the Response
, listSSHPublicKeysResponse
, ListSSHPublicKeysResponse
-- * Response Lenses
, lspkrsSSHPublicKeys
, lspkrsMarker
, lspkrsIsTruncated
, lspkrsResponseStatus
) where
import Network.AWS.IAM.Types
import Network.AWS.IAM.Types.Product
import Network.AWS.Prelude
import Network.AWS.Request
import Network.AWS.Response
-- | /See:/ 'listSSHPublicKeys' smart constructor.
data ListSSHPublicKeys = ListSSHPublicKeys'
{ _lspkUserName :: !(Maybe Text)
, _lspkMarker :: !(Maybe Text)
, _lspkMaxItems :: !(Maybe Nat)
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'ListSSHPublicKeys' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'lspkUserName'
--
-- * 'lspkMarker'
--
-- * 'lspkMaxItems'
listSSHPublicKeys
:: ListSSHPublicKeys
listSSHPublicKeys =
ListSSHPublicKeys'
{ _lspkUserName = Nothing
, _lspkMarker = Nothing
, _lspkMaxItems = Nothing
}
-- | The name of the IAM user to list SSH public keys for. If none is
-- specified, the UserName field is determined implicitly based on the AWS
-- access key used to sign the request.
lspkUserName :: Lens' ListSSHPublicKeys (Maybe Text)
lspkUserName = lens _lspkUserName (\ s a -> s{_lspkUserName = a});
-- | Use this parameter only when paginating results and only after you
-- receive a response indicating that the results are truncated. Set it to
-- the value of the 'Marker' element in the response you received to inform
-- the next call about where to start.
lspkMarker :: Lens' ListSSHPublicKeys (Maybe Text)
lspkMarker = lens _lspkMarker (\ s a -> s{_lspkMarker = a});
-- | Use this only when paginating results to indicate the maximum number of
-- items you want in the response. If there are additional items beyond the
-- maximum you specify, the 'IsTruncated' response element is 'true'.
--
-- This parameter is optional. If you do not include it, it defaults to
-- 100. Note that IAM might return fewer results, even when there are more
-- results available. If this is the case, the 'IsTruncated' response
-- element returns 'true' and 'Marker' contains a value to include in the
-- subsequent call that tells the service where to continue from.
lspkMaxItems :: Lens' ListSSHPublicKeys (Maybe Natural)
lspkMaxItems = lens _lspkMaxItems (\ s a -> s{_lspkMaxItems = a}) . mapping _Nat;
instance AWSRequest ListSSHPublicKeys where
type Rs ListSSHPublicKeys = ListSSHPublicKeysResponse
request = postQuery iAM
response
= receiveXMLWrapper "ListSSHPublicKeysResult"
(\ s h x ->
ListSSHPublicKeysResponse' <$>
(x .@? "SSHPublicKeys" .!@ mempty >>=
may (parseXMLList "member"))
<*> (x .@? "Marker")
<*> (x .@? "IsTruncated")
<*> (pure (fromEnum s)))
instance ToHeaders ListSSHPublicKeys where
toHeaders = const mempty
instance ToPath ListSSHPublicKeys where
toPath = const "/"
instance ToQuery ListSSHPublicKeys where
toQuery ListSSHPublicKeys'{..}
= mconcat
["Action" =: ("ListSSHPublicKeys" :: ByteString),
"Version" =: ("2010-05-08" :: ByteString),
"UserName" =: _lspkUserName, "Marker" =: _lspkMarker,
"MaxItems" =: _lspkMaxItems]
-- | Contains the response to a successful ListSSHPublicKeys request.
--
-- /See:/ 'listSSHPublicKeysResponse' smart constructor.
data ListSSHPublicKeysResponse = ListSSHPublicKeysResponse'
{ _lspkrsSSHPublicKeys :: !(Maybe [SSHPublicKeyMetadata])
, _lspkrsMarker :: !(Maybe Text)
, _lspkrsIsTruncated :: !(Maybe Bool)
, _lspkrsResponseStatus :: !Int
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'ListSSHPublicKeysResponse' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'lspkrsSSHPublicKeys'
--
-- * 'lspkrsMarker'
--
-- * 'lspkrsIsTruncated'
--
-- * 'lspkrsResponseStatus'
listSSHPublicKeysResponse
:: Int -- ^ 'lspkrsResponseStatus'
-> ListSSHPublicKeysResponse
listSSHPublicKeysResponse pResponseStatus_ =
ListSSHPublicKeysResponse'
{ _lspkrsSSHPublicKeys = Nothing
, _lspkrsMarker = Nothing
, _lspkrsIsTruncated = Nothing
, _lspkrsResponseStatus = pResponseStatus_
}
-- | A list of SSH public keys.
lspkrsSSHPublicKeys :: Lens' ListSSHPublicKeysResponse [SSHPublicKeyMetadata]
lspkrsSSHPublicKeys = lens _lspkrsSSHPublicKeys (\ s a -> s{_lspkrsSSHPublicKeys = a}) . _Default . _Coerce;
-- | When 'IsTruncated' is 'true', this element is present and contains the
-- value to use for the 'Marker' parameter in a subsequent pagination
-- request.
lspkrsMarker :: Lens' ListSSHPublicKeysResponse (Maybe Text)
lspkrsMarker = lens _lspkrsMarker (\ s a -> s{_lspkrsMarker = a});
-- | A flag that indicates whether there are more items to return. If your
-- results were truncated, you can make a subsequent pagination request
-- using the 'Marker' request parameter to retrieve more items. Note that
-- IAM might return fewer than the 'MaxItems' number of results even when
-- there are more results available. We recommend that you check
-- 'IsTruncated' after every call to ensure that you receive all of your
-- results.
lspkrsIsTruncated :: Lens' ListSSHPublicKeysResponse (Maybe Bool)
lspkrsIsTruncated = lens _lspkrsIsTruncated (\ s a -> s{_lspkrsIsTruncated = a});
-- | The response status code.
lspkrsResponseStatus :: Lens' ListSSHPublicKeysResponse Int
lspkrsResponseStatus = lens _lspkrsResponseStatus (\ s a -> s{_lspkrsResponseStatus = a});
|
olorin/amazonka
|
amazonka-iam/gen/Network/AWS/IAM/ListSSHPublicKeys.hs
|
mpl-2.0
| 7,562 | 0 | 17 | 1,513 | 935 | 564 | 371 | 104 | 1 |
-- ----------------------------------------------------------------------
-- Copyright 2010-2011 National University of Ireland.
-- ----------------------------------------------------------------------
-- This file is part of DysVunctional Language.
--
-- DysVunctional Language is free software; you can redistribute it and/or modify
-- it under the terms of the GNU Affero General Public License as
-- published by the Free Software Foundation, either version 3 of the
-- License, or (at your option) any later version.
--
-- DysVunctional Language 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 Affero General Public License
-- along with DysVunctional Language. If not, see <http://www.gnu.org/licenses/>.
-- ----------------------------------------------------------------------
{-# LANGUAGE NoImplicitPrelude #-}
module FOL.Language.AlphaRn (alphaRn) where
import FOL.Language.Common
import FOL.Language.Expression
import FOL.Language.Unique
import Control.Monad.State
import Control.Applicative
import Data.List
import Data.Maybe
type AlphaRnT = StateT NameList
type NameList = [Name]
evalAlphaRnT :: Monad m => AlphaRnT m a -> m a
evalAlphaRnT = flip evalStateT []
-- Rename a given name if it occurs in a given list of names.
rename :: NameList -> Name -> Unique Name
rename ns n@(Name name)
| n `elem` ns = uniqueName name
| otherwise = return n
-- Record a given list of names as names already seen.
record :: Monad m => NameList -> AlphaRnT m ()
record names = modify (names `union`)
-- Extend a given environment with new bindings.
extend :: [Name] -> [v] -> [(Name, v)] -> [(Name, v)]
extend xs vs env = zip xs vs ++ env
alphaRnExpr :: [(Name, Name)] -> Expr -> AlphaRnT Unique Expr
alphaRnExpr env (Var x) = return (Var x')
where
x' = fromMaybe x (lookup x env)
alphaRnExpr _ Nil = return Nil
alphaRnExpr _ (Bool b) = return (Bool b)
alphaRnExpr _ (Real r) = return (Real r)
alphaRnExpr env (If p c a)
= liftA3 If (alphaRnExpr env p)
(alphaRnExpr env c)
(alphaRnExpr env a)
alphaRnExpr env (Let (Bindings bs) body)
= do seen_names <- get
xs' <- lift $ mapM (rename seen_names) xs
record xs
es' <- mapM (alphaRnExpr env) es
let env' = extend xs xs' env
body' <- alphaRnExpr env' body
let bs' = zip xs' es'
return (Let (Bindings bs') body')
where
(xs, es) = unzip bs
alphaRnExpr env (LetValues (Bindings bs) body)
= do seen_names <- get
xs' <- lift $ mapM (mapM (rename seen_names)) xs
record (concat xs)
es' <- mapM (alphaRnExpr env) es
let env' = extend (concat xs) (concat xs') env
body' <- alphaRnExpr env' body
let bs' = zip xs' es'
return (LetValues (Bindings bs') body')
where
(xs, es) = unzip bs
alphaRnExpr env (Car e) = Car <$> alphaRnExpr env e
alphaRnExpr env (Cdr e) = Cdr <$> alphaRnExpr env e
alphaRnExpr env (VectorRef e i)
= liftA2 VectorRef (alphaRnExpr env e) (pure i)
alphaRnExpr env (Cons e1 e2)
= liftA2 Cons (alphaRnExpr env e1) (alphaRnExpr env e2)
alphaRnExpr env (Vector es) = Vector <$> mapM (alphaRnExpr env) es
alphaRnExpr env (Values es) = Values <$> mapM (alphaRnExpr env) es
alphaRnExpr env (ProcCall proc args)
= liftA2 ProcCall (pure proc) (mapM (alphaRnExpr env) args)
alphaRnDefn :: [(Name, Name)] -> Defn -> AlphaRnT Unique Defn
alphaRnDefn env (Defn proc args body)
= do seen_names <- get
arg_names' <- lift $ mapM (rename seen_names) arg_names
record (proc_name : arg_names)
let args' = zip arg_names' arg_shapes
env' = extend arg_names arg_names' env
body' <- alphaRnExpr env' body
-- We assume here that procedure names are already unique.
-- Something should check this assumption and signal an
-- error if it is not satisfied.
return (Defn proc args' body')
where
(proc_name, _) = proc
(arg_names, arg_shapes) = unzip args
alphaRnProg :: [(Name, Name)] -> Prog -> AlphaRnT Unique Prog
alphaRnProg env (Prog defns expr)
= liftA2 Prog (mapM (alphaRnDefn env) defns) (alphaRnExpr env expr)
alphaRn :: Prog -> Unique Prog
alphaRn = evalAlphaRnT . alphaRnProg []
|
axch/dysvunctional-language
|
haskell-fol/FOL/Language/AlphaRn.hs
|
agpl-3.0
| 4,505 | 0 | 13 | 1,028 | 1,327 | 669 | 658 | 77 | 1 |
-- brittany { lconfig_columnAlignMode: { tag: ColumnAlignModeDisabled }, lconfig_indentPolicy: IndentPolicyLeft }
func
:: ( ( lkasdlkjalsdjlakjsdlkjasldkjalskdjlkajsd
-> lkasdlkjalsdjlakjsdlkjasldkjalskdjlkajsd
)
)
|
lspitzner/brittany
|
data/Test370.hs
|
agpl-3.0
| 236 | 0 | 7 | 41 | 17 | 10 | 7 | 3 | 0 |
module Main where
import Lib
main :: IO ()
main = go
|
aztecrex/haskell-deleteme
|
app/Main.hs
|
unlicense
| 55 | 0 | 6 | 14 | 22 | 13 | 9 | 4 | 1 |
{-
MainTestSuite.hs
Copyright 2014 Sebastien Soudan
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-}
module Main (
main
) where
import qualified AVLTreeTest
import qualified BSTreeTest
import qualified BatchedQueueTest
import qualified BatchedDequeueTest
import qualified LeftistHeapTest
import qualified BinomialHeapTest
import qualified RDGTest
import Test.Framework
import Test.Framework.Providers.QuickCheck2
import Test.Framework.Options
main :: IO ()
main = defaultMain tests
tests :: [Test]
tests = [
testGroup "AVLTree: simple"
[ testProperty "insert" AVLTreeTest.prop_test
--, testProperty "rotations" prop_rotations
, testProperty "insert - Integer" AVLTreeTest.prop_insert_integer
, testProperty "insert - Float" AVLTreeTest.prop_insert_float
]
, testGroup "AVLTree: complex"
[ testProperty "Height" AVLTreeTest.prop_height
, testProperty "Balance factor" AVLTreeTest.prop_bf
, testProperty "Sort" AVLTreeTest.prop_sort
]
, testGroup "BSTree: simple"
[ testProperty "insert" BSTreeTest.prop_test
, testProperty "insert - Integer" BSTreeTest.prop_insert_integer
, testProperty "insert - Float" BSTreeTest.prop_insert_float
]
, testGroup "BSTree: complex"
[ testProperty "Sort" BSTreeTest.prop_sort
]
, testGroup "BatchedQueue: simple"
[ testProperty "insert" BatchedQueueTest.prop_test
, testProperty "build" BatchedQueueTest.prop_build
, testProperty "empty isEmpty" BatchedQueueTest.prop_empty
, testProperty "head - tail" BatchedQueueTest.prop_head_tail
]
, testGroup "BatchedDequeue: simple"
[ testProperty "insert" BatchedDequeueTest.prop_test
, testProperty "build" BatchedDequeueTest.prop_build
, testProperty "empty isEmpty" BatchedDequeueTest.prop_empty
, testProperty "head - tail" BatchedDequeueTest.prop_head_tail
]
, testGroup "LeftistHeap: simple"
[ testProperty "empty isEmpty" LeftistHeapTest.prop_empty
, testProperty "findMin" (LeftistHeapTest.prop_findMin :: [Int] -> Bool)
, testProperty "merge - findMin" (LeftistHeapTest.prop_merge_findMin :: [Int] -> [Int] -> Bool)
, testProperty "deleteMin" (LeftistHeapTest.prop_deleteMin :: [Int] -> Bool)
, testProperty "insert" (LeftistHeapTest.prop_insert_not_empty :: [Int] -> Bool)
, testProperty "P1" (LeftistHeapTest.prop_P1 :: [Int] -> Bool)
]
, testGroup "SavedMinBinomialHeap: simple"
[ testProperty "empty isEmpty" BinomialHeapTest.prop_empty
, testProperty "findMin" (BinomialHeapTest.prop_findMin :: [Int] -> Bool)
, testProperty "merge - findMin" (BinomialHeapTest.prop_merge_findMin :: [Int] -> [Int] -> Bool)
, testProperty "deleteMin" (BinomialHeapTest.prop_deleteMin :: [Int] -> Bool)
, testProperty "insert" (BinomialHeapTest.prop_insert_not_empty :: [Int] -> Bool)
, testProperty "P1" (BinomialHeapTest.prop_P1 :: [Int] -> Bool)
, testProperty "P2" (BinomialHeapTest.prop_P2 :: [Int] -> Bool)
]
, testGroup "RDG: simple"
[ testProperty "empty graph isEmpty" RDGTest.prop_empty
, testProperty "connectedComp graph works" RDGTest.prop_cc
, testProperty "connectedComp (2) graph works" RDGTest.prop_cc2
]
]
|
ssoudan/hsStruct
|
test/MainTestSuite.hs
|
apache-2.0
| 4,122 | 0 | 12 | 1,049 | 657 | 360 | 297 | 59 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Salesforce.HTTP
( showRequest
, showResponse
) where
import Control.Monad (when, unless)
import Control.Monad.Writer (MonadWriter(..), execWriter)
import Data.ByteString.Lazy (ByteString)
import Data.CaseInsensitive (original)
import qualified Data.ByteString.Char8 as B8
import qualified Data.ByteString.Lazy.Char8 as LB8
import Data.Text (Text)
import qualified Data.Text as T
import qualified Data.Text.Lazy as LT
import qualified Data.Text.Encoding as TE
import qualified Data.Text.Lazy.Encoding as LTE
import Network.HTTP.Client (getUri)
import Network.HTTP.Conduit as HTTP
( Request(..), method, requestHeaders, requestBody
, RequestBody(..)
, Response(..), responseBody
)
import Network.HTTP.Types.Header (Header)
import Network.HTTP.Types.Status (Status(..))
showRequest :: Request -> Text
showRequest x = T.concat . execWriter $ do
tell [ "Request {", TE.decodeUtf8 $ method x, " ", T.pack $ show (getUri x) ]
let headers = requestHeaders x
when (headers /= []) $
tell [ " headers=[", T.intercalate ", " $ map showHeader headers, "]" ]
let body = requestBody x
unless (requestBodyIsEmpty body) $
tell [ " body=", showRequestBody body ]
tell [ "}" ]
where requestBodyIsEmpty :: RequestBody -> Bool
requestBodyIsEmpty (RequestBodyLBS b) = LB8.length b == 0
requestBodyIsEmpty (RequestBodyBS b) = B8.length b == 0
requestBodyIsEmpty (RequestBodyBuilder b _) = b == 0
requestBodyIsEmpty (RequestBodyStream b _) = b == 0
requestBodyIsEmpty _ = False
showRequestBody :: RequestBody -> Text
showRequestBody (RequestBodyLBS b) = LT.toStrict $ LTE.decodeUtf8 b
showRequestBody (RequestBodyBS b) = TE.decodeUtf8 b
showRequestBody (RequestBodyBuilder _ _) = "<builder>"
showRequestBody (RequestBodyStream _ _) = "<stream>"
showRequestBody (RequestBodyStreamChunked _) = "<chunked>"
showResponse :: Response ByteString -> Text
showResponse x = T.concat . execWriter $ do
tell [ "Response {", T.pack . show . statusCode $ responseStatus x ]
let headers = responseHeaders x
when (headers /= []) $
tell [ " headers=[", T.intercalate ", " $ map showHeader headers, "]" ]
let body = responseBody x
when (body /= "") $
tell [ " body=", LT.toStrict $ LTE.decodeUtf8 body ]
tell [ "}" ]
showHeader :: Header -> Text
showHeader h = T.concat [ TE.decodeUtf8 $ original $ fst h, ": ", TE.decodeUtf8 $ snd h ]
|
VictorDenisov/salesforce
|
src/Salesforce/HTTP.hs
|
apache-2.0
| 2,496 | 0 | 13 | 488 | 820 | 443 | 377 | 56 | 9 |
module Commands (commandMap)
where
import Control.Applicative
import qualified Data.Map as Map
import qualified Data.Set as Set
import System.Exit
import System.Directory
import Types
import CSVmail
import Tools
-- Map that list the commands key and the corresponding function. It is the
-- public interface
commandMap :: CommandMap
commandMap = Map.fromList [("help", help)
,("exit", \_ _ -> putStrLn "goodbye" >> exitSuccess)
,("listtags", listtags)
,("load", load)
,("diff", diff)
,("printall", printall)
,("print", printtag)
]
-- Help string. `unlines` add a trailing \n and `init` removes it
help :: EStatus -> [String] -> IO EStatus
help status _ = putStr helpStr >> return status
where helpStr = unlines
["Welcome to `emails_compare`."
,"I guess that you want to know how I work, right?"
,"Available commands:"
," + help: print this help"
," + load tag filename: load all the email addresses from"
," file *name* and attach them to *tag* keyword."
," Existing tags will be silently overwritten."
," + diff tag1 tag2: show the emails that are in *tag1*"
," but not in *tag2*"
," + listtags: list the tags already present"
," + printall: print the full dictionary"
," + print tag: print the content of tag"
," + exit: exit the program"
]
-- Lists the tags in the status dictionary
listtags :: EStatus -> [String] -> IO EStatus
listtags status _ = putStrLn (message keys) >> return status
where keys = unlines $ map (\(n, k) -> (show n) ++ ": " ++ k) numKey
numKey = zip [1 ..] $ Map.keys $ fromEStatus status
message "" = "No tag found"
message xs = "The available tags are:\n" ++ init xs
-- read the input file and store its emails into the status
load :: EStatus -> [String] -> IO EStatus
load status (tag:filename:[]) = loadifFile status tag filename
load status (tag:filename:_) = putStrLn msg >> load status (tag:filename:[])
where msg = unwords ["The command is 'load tag filename'."
,"Anything else is ignored"
]
load status _ = putStrLn "The command is too short. The correct one is 'load tag filename'"
>> return status
-- if the file exists, read it and update the status. Otherwise print a warning
-- and return the original status
loadifFile :: EStatus -> Tag -> FilePath -> IO EStatus
loadifFile s t fn = doesFileExist fn >>= loadIfExist
where loadIfExist b = if b
then loadFile s t fn
else putStrLn ("'" ++ fn ++ "' does not exists")
>> return s
-- Now we are sure that the file exists: go ahead
loadFile :: EStatus -> Tag -> FilePath -> IO EStatus
loadFile s t fn = pure (esInsert t) <*> emails <*> (return s)
where emails = readFile fn >>=
(\s' -> return (csv2eMails s'))
-- get the difference between the sets attached to two tags
diff :: EStatus -> [String] -> IO EStatus
diff status (tag1:tag2:[]) = putStrLn (pureDiff status tag1 tag2) >> return status
diff status (tag1:tag2:_) = putStrLn msg >> diff status (tag1:tag2:[])
where msg = unwords ["The command is 'diff tag1 tag2'."
,"Anything else is ignored"
]
diff status _ = putStrLn "The command is too short. The correct one is 'diff tag1 tag2'"
>> return status
pureDiff :: EStatus -> Tag -> Tag -> String
pureDiff status tag1 tag2 = case doDiff status tag1 tag2 of
Just set -> pplist (Set.toList set) ""
Nothing -> "One of the tags does not exist"
doDiff :: EStatus -> Tag -> Tag -> Maybe (Set.Set EMail)
doDiff status t1 t2 = pure Set.difference <*> mapLookup t1 <*> mapLookup t2
where mapLookup k = Map.lookup k $ fromEStatus status
-- print the whole dictionary
printall :: EStatus -> [String] -> IO EStatus
printall status [] = putStrLn msg >> return status
where ppmsg = ppEStatus status
msg = if null ppmsg
then "No entries found"
else ppmsg
-- print the content of a single tag
printtag :: EStatus -> [String] -> IO EStatus
printtag status (tag:[]) = putStrLn ppstr >> return status
where ppstr = case Map.lookup tag (fromEStatus status) of
Just set -> pplist (Set.toList set) ""
Nothing -> "The tag '" ++ tag ++ "' does not exist"
printtag status (tag:_) = putStrLn msg >> printtag status (tag:[])
where msg = unwords ["The command is 'printtag tag'."
,"Anything else is ignored"
]
printtag status _ = putStrLn "The command is too short. The correct one is 'printtag tag'"
>> return status
|
montefra/email_compare
|
src/Commands.hs
|
bsd-2-clause
| 5,924 | 0 | 14 | 2,476 | 1,221 | 639 | 582 | 86 | 2 |
-- http://www.codewars.com/kata/52f787eb172a8b4ae1000a34
module Zeros where
zeros :: Int -> Int
zeros 0 = 0
zeros n = sum . tail . takeWhile (>0) . iterate (`div`5) $ n
|
Bodigrim/katas
|
src/haskell/5-Number-of-trailing-zeros-of-N.hs
|
bsd-2-clause
| 169 | 0 | 9 | 28 | 62 | 35 | 27 | 4 | 1 |
{-# LANGUAGE TypeSynonymInstances, FlexibleInstances #-}
module Database.Narc.AST.Pretty where
import Database.Narc.AST
import Database.Narc.Pretty
import Database.Narc.Util (mapstrcat)
-- Pretty-printing ------------------------------------------------=====
instance Pretty (Term' a) where
pretty (Unit) = "()"
pretty (Bool b) = show b
pretty (Num n) = show n
pretty (String s) = show s
pretty (PrimApp f args) = f ++ "(" ++ mapstrcat "," pretty args ++ ")"
pretty (Var x) = x
pretty (Abs x n) = "(fun " ++ x ++ " -> " ++ pretty n ++ ")"
pretty (App l m) = pretty l ++ " " ++ pretty m
pretty (Table tbl t) = "(table " ++ tbl ++ " : " ++ show t ++ ")"
pretty (If c a b) =
"(if " ++ pretty c ++ " then " ++ pretty a ++
" else " ++ pretty b ++ " )"
pretty (Singleton m) = "[" ++ pretty m ++ "]"
pretty (Nil) = "[]"
pretty (Union m n) = "(" ++ pretty m ++ " ++ " ++ pretty n ++ ")"
pretty (Record fields) =
"{" ++ mapstrcat "," (\(l,m) -> l ++ "=" ++ pretty m) fields ++ "}"
pretty (Project m l) = "(" ++ pretty m ++ "." ++ l ++ ")"
pretty (Comp x m n) =
"(for (" ++ x ++ " <- " ++ pretty m ++ ") " ++ pretty n ++ ")"
instance Pretty (Term a) where
pretty (m, _anno) = pretty m
|
ezrakilty/narc
|
Database/Narc/AST/Pretty.hs
|
bsd-2-clause
| 1,241 | 0 | 12 | 310 | 551 | 276 | 275 | 28 | 0 |
module Evaluator.Deeds where
import Data.List
import StaticFlags
import Utilities
import Data.Ord (comparing)
-- | Number of unclaimed deeds. Invariant: always greater than or equal to 0
type Unclaimed = Int
-- | A deed supply shared amongst all expressions
type Deeds = Int
-- NB: it is OK if the number of deeds to claim is negative -- that just causes some deeds to be released
claimDeeds :: Deeds -> Int -> Maybe Deeds
claimDeeds deeds want = guard (not dEEDS || deeds >= want) >> return (deeds - want)
-- | Splits up a number evenly across several partitions in proportions to weights given to those partitions.
--
-- > sum (apportion n weights) == n
--
-- Annoyingly, it is important that this works properly if n is negative as well -- these can occur
-- when we have turned off deed checking. I don't care about handling negative weights.
apportion :: Deeds -> [Deeds] -> [Deeds]
apportion _ [] = error "apportion: empty list"
apportion orig_n weighting
| orig_n < 0 = map negate $ apportion (negate orig_n) weighting
| otherwise = result
where
fracs :: [Rational]
fracs = assertRender (text "apportion: must have at least one non-zero weight") (denominator /= 0) $
map (\numerator -> fromIntegral numerator / denominator) weighting
where denominator = fromIntegral (sum weighting)
-- Here is the idea:
-- 1) Do one pass through the list of fractians
-- 2) Start by allocating the floor of the number of "n" that we should allocate to this weight of the fraction
-- 3) Accumulate the fractional pieces and the indexes that generated them
-- 4) Use circular programming to feed the list of fractional pieces that we actually allowed the allocation
-- of back in to the one pass we are doing over the list
((_, remaining, final_deserving), result) = mapAccumL go (0 :: Int, orig_n, []) fracs
go (i, n, deserving) frac = ((i + 1, n - whole, (i, remainder) : deserving),
whole + if i `elem` final_deserving_allowed then 1 else 0)
where (whole, remainder) = properFraction (frac * fromIntegral orig_n)
-- We should prefer to allocate pieces to those bits of the fraction where the error (i.e. the fractional part) is greatest.
-- We cannot allocate more of these "fixup" pieces than we had "n" left at the end of the first pass.
final_deserving_allowed = map fst (take remaining (sortBy (comparing (Down . snd)) final_deserving))
noChange, noGain :: Deeds -> Deeds -> Bool
noChange = (==)
noGain = (>=)
|
osa1/chsc
|
Evaluator/Deeds.hs
|
bsd-3-clause
| 2,553 | 0 | 15 | 565 | 474 | 267 | 207 | 26 | 2 |
{-# LANGUAGE MultiParamTypeClasses #-}
import Control.Monad.Chrono
import Control.Monad.IO.Class
newtype Pos = Pos (Int, Int, Int) deriving Show
data DeltaPos = MoveX Int | MoveY Int | MoveZ Int
instance Keystone Pos DeltaPos where
redo (MoveX n) (Pos (x, y, z)) = Pos (x + n, y, z)
redo (MoveY n) (Pos (x, y, z)) = Pos (x, y + n, z)
redo (MoveZ n) (Pos (x, y, z)) = Pos (x, y, z + n)
undo (MoveX n) = redo $ MoveX $ -n
undo (MoveY n) = redo $ MoveY $ -n
undo (MoveZ n) = redo $ MoveZ $ -n
chronoExample :: ChronoT Pos DeltaPos IO ()
chronoExample = do
step $ MoveX 10
step $ MoveY 9
step $ MoveZ 8
step $ MoveX 2
s1 <- get
rewind 2
s2 <- get
unwind 1
s3 <- get
rewind 1
s4 <- get
put $ Pos (1, 1, 1)
s5 <- get
unwind 2
s6 <- get
liftIO $ print $ "Splices: " ++ show (s1, s2, s3, s4, s5, s6)
main :: IO ()
main = do
out <- execChronoT chronoExample $ Pos (0, 0, 0)
print $ "Output: " ++ show out
|
kvanberendonck/monad-chrono
|
examples/Example.hs
|
bsd-3-clause
| 997 | 0 | 10 | 298 | 514 | 263 | 251 | 34 | 1 |
-- |Load and unload MSF plugins.
module MSF.Plugin
( module Types.Plugin
, plugin_load
, plugin_unload
, plugin_loaded
) where
import MSF.Monad
import Types.Plugin
import qualified RPC.Plugin as RPC
-- | Silent operation.
plugin_load :: (SilentCxt s) => PluginName -> PluginOptions -> MSF s Result
plugin_load name opts = prim $ \ addr auth -> do
RPC.plugin_load addr auth name opts
-- | Unload a plugin, but names are not always compatible with plugin_load. Silent operation.
plugin_unload :: (SilentCxt s) => PluginName -> MSF s Result
plugin_unload name = prim $ \ addr auth -> do
RPC.plugin_unload addr auth name
-- | Enumerate loaded plugins. Silent operation.
plugin_loaded :: (SilentCxt s) => MSF s Plugins
plugin_loaded = prim $ \ addr auth -> do
RPC.plugin_loaded addr auth
|
GaloisInc/msf-haskell
|
src/MSF/Plugin.hs
|
bsd-3-clause
| 804 | 0 | 10 | 147 | 206 | 112 | 94 | 17 | 1 |
{-# LANGUAGE DeriveDataTypeable, DeriveGeneric, FlexibleInstances #-}
{-# LANGUAGE FunctionalDependencies, MultiParamTypeClasses #-}
{-# LANGUAGE NoImplicitPrelude, OverloadedStrings, RecordWildCards #-}
{-# LANGUAGE ScopedTypeVariables, StandaloneDeriving, TemplateHaskell #-}
{-# LANGUAGE TypeFamilies, QuasiQuotes #-}
module FreeAgent.Core.Protocol.Schedule where
import FreeAgent.AgentPrelude
import FreeAgent.Core.Internal.Lenses
import FreeAgent.Core.Protocol
import FreeAgent.Orphans ()
import Control.Error (note)
import Control.Monad.State (StateT)
import Data.Aeson (Result (..),
Value (..),
fromJSON, (.:?))
import qualified Data.Aeson as A
import Data.Aeson.TH (Options (..),
defaultOptions,
deriveJSON)
import Data.Attoparsec.Text (parseOnly)
import Data.Binary (Binary)
import Data.Char as Char (toLower)
import System.Cron
import System.Cron.Parser (cronSchedule)
-- ---------Types-------------
-- Types
-- ---------------------------
data Event
= Event { schedKey :: !Key
, schedRecur :: !ScheduleRecurrence
, schedRetry :: !RetryOption
, schedModified :: !UTCTime
, schedDisabled :: !Bool
} deriving (Show, Eq, Typeable, Generic)
data ScheduleRecurrence
= RecurCron !CronSchedule !Text -- ^ execute when schedule matches
| RecurInterval !Int -- ^ execute every n milliseconds
| OnceAt !UTCTime
deriving (Show, Eq, Typeable, Generic)
cronEvent :: Text -> Either String ScheduleRecurrence
cronEvent format =
case parseOnly cronSchedule format of
Right sched -> Right $ RecurCron sched format
Left msg -> Left msg
instance IsString ScheduleRecurrence where
fromString format =
case cronEvent (convert format) of
Right cron' -> cron'
_ -> error $ "Unable to parse cron formatted literal: "
++ format
instance ToJSON ScheduleRecurrence where
toJSON (RecurCron _ expr) =
A.object ["recurCron" A..= expr]
toJSON (RecurInterval num) =
A.object ["recurInterval" A..= num]
toJSON (OnceAt time') =
A.object ["onceAt" A..= time']
instance FromJSON ScheduleRecurrence where
parseJSON (Object value') =
do cron <- value' .:? "recurCron"
interval <- value' .:? "recurInterval"
once <- value' .:? "onceAt"
case cron of
Just expr ->
case cronEvent expr of
Right recur -> return recur
Left _ -> mzero
Nothing ->
case interval of
Just i -> return (RecurInterval i)
Nothing ->
case once of
Just jtime ->
case fromJSON jtime of
Error _ -> mzero
Success time' -> return (OnceAt time')
Nothing -> mzero
parseJSON _ = mzero
instance Stashable Event where
key = schedKey
instance Ord Event where
compare ev1 ev2 = compare (key ev1) (key ev2)
--TODO: implement retry logic
data RetryOption = Never
-- Retry N times at M interval
| Fixed Int Int
-- Retry N times at exponentially increasing interval
-- starting from M
| Exponential Int Int
deriving (Show, Eq, Typeable, Generic)
data ScheduleFail = SCallFailed CallFail
| EventNotFound Key
| SDBException !Text
deriving (Show, Eq, Typeable, Generic)
-- ---------API---------------
-- API
-- ---------------------------
-- | Helper for 'ScheduleAddEvent'; schedules an Event. Note
-- that for a CronEvent, the event will run at the next matching time
-- beginning one minute from now - e.g. you are scheduling something to run
-- in the future, not right now.
schedule :: MonadAgent agent
=> Key -> ScheduleRecurrence -> RetryOption
-> agent (Either CallFail ())
schedule key' recur retry =
callServ (ScheduleAddEvent key' recur retry)
unschedule :: MonadAgent agent
=> Key
-> agent (Either ScheduleFail ())
unschedule key' = do
efail <- callServ (ScheduleRemoveEvent key')
case efail of
Right result' -> return result'
Left failed -> return $ Left (SCallFailed failed)
lookupEvent :: MonadAgent agent
=> Key -> agent (Either ScheduleFail Event)
lookupEvent key' = do
emevent <- callServ (ScheduleLookupEvent key')
case emevent of
Right mevent -> return $ note (EventNotFound key') mevent
Left failed -> return $ Left (SCallFailed failed)
type ScheduleImplM st rs = StateT st Agent rs
type ScheduleImplE st rs = ScheduleImplM st (Either ScheduleFail rs)
data ScheduleImpl st = ScheduleImpl {
callScheduleAddEvent :: ScheduleAddEvent -> ProtoT ScheduleAddEvent st ()
, callScheduleEventControl :: ScheduleEventControl -> ProtoT ScheduleEventControl st ()
, callScheduleLookupEvent :: ScheduleLookupEvent -> ProtoT ScheduleLookupEvent st (Maybe Event)
, callScheduleQueryEvents :: ScheduleQueryEvents -> ProtoT ScheduleQueryEvents st [Event]
, callScheduleRemoveEvent :: ScheduleRemoveEvent -> ProtoT ScheduleRemoveEvent st (Either ScheduleFail ())
, castScheduleControl :: ScheduleControl -> ProtoT ScheduleControl st ()
}
data ScheduleControl = ScheduleStart | ScheduleStop
deriving (Show, Typeable, Generic)
instance Binary ScheduleControl
instance NFData ScheduleControl where rnf = genericRnf
instance ServerCast ScheduleControl where
type CastProtocol ScheduleControl = ScheduleImpl
castName _ = serverName
handle = castScheduleControl
data ScheduleAddEvent
= ScheduleAddEvent !Key !ScheduleRecurrence !RetryOption
| ScheduleAddEvents [Event]
| ScheduleAddNewerEvent !Key !ScheduleRecurrence !RetryOption !UTCTime
deriving (Show, Typeable, Generic)
instance Binary ScheduleAddEvent
instance NFData ScheduleAddEvent where rnf = genericRnf
instance ServerCall ScheduleAddEvent where
type CallProtocol ScheduleAddEvent = ScheduleImpl
type CallResponse ScheduleAddEvent = ()
callName _ = serverName
respond = callScheduleAddEvent
data ScheduleEventControl
= ScheduleDisableEvents ![Key]
| ScheduleEnableEvents ![Key]
deriving (Show, Typeable, Generic)
instance Binary ScheduleEventControl
instance NFData ScheduleEventControl where rnf = genericRnf
instance ServerCall ScheduleEventControl where
type CallProtocol ScheduleEventControl = ScheduleImpl
type CallResponse ScheduleEventControl = ()
callName _ = serverName
respond = callScheduleEventControl
data ScheduleQueryEvents = ScheduleQueryEvents
deriving (Show, Typeable, Generic)
instance Binary ScheduleQueryEvents
instance NFData ScheduleQueryEvents where rnf = genericRnf
instance ServerCall ScheduleQueryEvents where
type CallProtocol ScheduleQueryEvents = ScheduleImpl
type CallResponse ScheduleQueryEvents = [Event]
callName _ = serverName
respond = callScheduleQueryEvents
data ScheduleLookupEvent = ScheduleLookupEvent Key
deriving (Show, Typeable, Generic)
instance NFData ScheduleLookupEvent where rnf = genericRnf
instance Binary ScheduleLookupEvent
instance ServerCall ScheduleLookupEvent where
type CallProtocol ScheduleLookupEvent = ScheduleImpl
type CallResponse ScheduleLookupEvent = Maybe Event
callName _ = serverName
respond = callScheduleLookupEvent
data ScheduleRemoveEvent = ScheduleRemoveEvent Key
deriving (Show, Typeable, Generic)
instance Binary ScheduleRemoveEvent
instance NFData ScheduleRemoveEvent where rnf = genericRnf
instance ServerCall ScheduleRemoveEvent where
type CallProtocol ScheduleRemoveEvent = ScheduleImpl
type CallResponse ScheduleRemoveEvent = Either ScheduleFail ()
callName _ = serverName
respond = callScheduleRemoveEvent
serverName :: String
serverName = "agent:schedule"
deriveSerializers ''RetryOption
instance Binary ScheduleFail
instance NFData ScheduleFail where rnf = genericRnf
instance Binary ScheduleRecurrence
instance NFData ScheduleRecurrence where rnf = genericRnf
deriveSafeStore ''ScheduleRecurrence
instance Binary Event
instance NFData Event where rnf = genericRnf
-- we want to customize the JSON field names for ShellCommand
-- so it looks nicer in Yaml, which may be very frequently used
deriveJSON (defaultOptions {fieldLabelModifier = \field ->
let (x:xs) = drop 5 field
in Char.toLower x : xs
})
''Event
deriveSafeStore ''Event
|
jeremyjh/free-agent
|
core/src/FreeAgent/Core/Protocol/Schedule.hs
|
bsd-3-clause
| 9,410 | 0 | 22 | 2,775 | 1,954 | 1,019 | 935 | 227 | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.