_id
stringlengths
64
64
repository
stringlengths
6
84
name
stringlengths
4
110
content
stringlengths
0
248k
license
null
download_url
stringlengths
89
454
language
stringclasses
7 values
comments
stringlengths
0
74.6k
code
stringlengths
0
248k
afbeac18cb4ba69c89a9871fe07f5ca10c3d4939462f3c62b957aeaf5ccad794
brendanhay/gogol
ListDocuments.hs
# LANGUAGE DataKinds # # LANGUAGE DeriveGeneric # # LANGUAGE DerivingStrategies # # LANGUAGE DuplicateRecordFields # # LANGUAGE FlexibleInstances # # LANGUAGE GeneralizedNewtypeDeriving # # LANGUAGE LambdaCase # {-# LANGUAGE OverloadedStrings #-} # LANGUAGE PatternSynonyms # # LANGUAGE RecordWildCards # {-# LANGUAGE StrictData #-} # LANGUAGE TypeFamilies # # LANGUAGE TypeOperators # # LANGUAGE NoImplicitPrelude # # OPTIONS_GHC -fno - warn - duplicate - exports # # OPTIONS_GHC -fno - warn - name - shadowing # # OPTIONS_GHC -fno - warn - unused - binds # # OPTIONS_GHC -fno - warn - unused - imports # # OPTIONS_GHC -fno - warn - unused - matches # -- | Module : . FireStore . Projects . Databases . Documents . ListDocuments Copyright : ( c ) 2015 - 2022 License : Mozilla Public License , v. 2.0 . Maintainer : < brendan.g.hay+ > -- Stability : auto-generated Portability : non - portable ( GHC extensions ) -- -- Lists documents. -- -- /See:/ < Cloud Firestore API Reference> for @firestore.projects.databases.documents.listDocuments@. module Gogol.FireStore.Projects.Databases.Documents.ListDocuments ( -- * Resource FireStoreProjectsDatabasesDocumentsListDocumentsResource, -- ** Constructing a Request FireStoreProjectsDatabasesDocumentsListDocuments (..), newFireStoreProjectsDatabasesDocumentsListDocuments, ) where import Gogol.FireStore.Types import qualified Gogol.Prelude as Core | A resource alias for method which the -- 'FireStoreProjectsDatabasesDocumentsListDocuments' request conforms to. type FireStoreProjectsDatabasesDocumentsListDocumentsResource = "v1" Core.:> Core.Capture "parent" Core.Text Core.:> Core.Capture "collectionId" Core.Text Core.:> Core.QueryParam "$.xgafv" Xgafv Core.:> Core.QueryParam "access_token" Core.Text Core.:> Core.QueryParam "callback" Core.Text Core.:> Core.QueryParams "mask.fieldPaths" Core.Text Core.:> Core.QueryParam "orderBy" Core.Text Core.:> Core.QueryParam "pageSize" Core.Int32 Core.:> Core.QueryParam "pageToken" Core.Text Core.:> Core.QueryParam "readTime" Core.DateTime Core.:> Core.QueryParam "showMissing" Core.Bool Core.:> Core.QueryParam "transaction" Core.Base64 Core.:> Core.QueryParam "uploadType" Core.Text Core.:> Core.QueryParam "upload_protocol" Core.Text Core.:> Core.QueryParam "alt" Core.AltJSON Core.:> Core.Get '[Core.JSON] ListDocumentsResponse -- | Lists documents. -- -- /See:/ 'newFireStoreProjectsDatabasesDocumentsListDocuments' smart constructor. data FireStoreProjectsDatabasesDocumentsListDocuments = FireStoreProjectsDatabasesDocumentsListDocuments { -- | V1 error format. xgafv :: (Core.Maybe Xgafv), -- | OAuth access token. accessToken :: (Core.Maybe Core.Text), | JSONP callback :: (Core.Maybe Core.Text), -- | Required. The collection ID, relative to @parent@, to list. For example: @chatrooms@ or @messages@. collectionId :: Core.Text, -- | The list of field paths in the mask. See Document.fields for a field path syntax reference. maskFieldPaths :: (Core.Maybe [Core.Text]), -- | The order to sort results by. For example: @priority desc, name@. orderBy :: (Core.Maybe Core.Text), -- | The maximum number of documents to return. pageSize :: (Core.Maybe Core.Int32), | The @next_page_token@ value returned from a previous List request , if any . pageToken :: (Core.Maybe Core.Text), -- | Required. The parent resource name. In the format: @projects\/{project_id}\/databases\/{database_id}\/documents@ or @projects\/{project_id}\/databases\/{database_id}\/documents\/{document_path}@. For example: @projects\/my-project\/databases\/my-database\/documents@ or @projects\/my-project\/databases\/my-database\/documents\/chatrooms\/my-chatroom@ parent :: Core.Text, -- | Reads documents as they were at the given time. This may not be older than 270 seconds. readTime :: (Core.Maybe Core.DateTime), | If the list should show missing documents . A missing document is a document that does not exist but has sub - documents . These documents will be returned with a key but will not have fields , Document.create/time , or Document.update/time set . Requests with @show_missing@ may not specify @where@ or @order_by@. showMissing :: (Core.Maybe Core.Bool), -- | Reads documents in a transaction. transaction :: (Core.Maybe Core.Base64), | Legacy upload protocol for media ( e.g. \"media\ " , \"multipart\ " ) . uploadType :: (Core.Maybe Core.Text), -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). uploadProtocol :: (Core.Maybe Core.Text) } deriving (Core.Eq, Core.Show, Core.Generic) -- | Creates a value of 'FireStoreProjectsDatabasesDocumentsListDocuments' with the minimum fields required to make a request. newFireStoreProjectsDatabasesDocumentsListDocuments :: -- | Required. The collection ID, relative to @parent@, to list. For example: @chatrooms@ or @messages@. See 'collectionId'. Core.Text -> -- | Required. The parent resource name. In the format: @projects\/{project_id}\/databases\/{database_id}\/documents@ or @projects\/{project_id}\/databases\/{database_id}\/documents\/{document_path}@. For example: @projects\/my-project\/databases\/my-database\/documents@ or @projects\/my-project\/databases\/my-database\/documents\/chatrooms\/my-chatroom@ See 'parent'. Core.Text -> FireStoreProjectsDatabasesDocumentsListDocuments newFireStoreProjectsDatabasesDocumentsListDocuments collectionId parent = FireStoreProjectsDatabasesDocumentsListDocuments { xgafv = Core.Nothing, accessToken = Core.Nothing, callback = Core.Nothing, collectionId = collectionId, maskFieldPaths = Core.Nothing, orderBy = Core.Nothing, pageSize = Core.Nothing, pageToken = Core.Nothing, parent = parent, readTime = Core.Nothing, showMissing = Core.Nothing, transaction = Core.Nothing, uploadType = Core.Nothing, uploadProtocol = Core.Nothing } instance Core.GoogleRequest FireStoreProjectsDatabasesDocumentsListDocuments where type Rs FireStoreProjectsDatabasesDocumentsListDocuments = ListDocumentsResponse type Scopes FireStoreProjectsDatabasesDocumentsListDocuments = '[CloudPlatform'FullControl, Datastore'FullControl] requestClient FireStoreProjectsDatabasesDocumentsListDocuments {..} = go parent collectionId xgafv accessToken callback (maskFieldPaths Core.^. Core._Default) orderBy pageSize pageToken readTime showMissing transaction uploadType uploadProtocol (Core.Just Core.AltJSON) fireStoreService where go = Core.buildClient ( Core.Proxy :: Core.Proxy FireStoreProjectsDatabasesDocumentsListDocumentsResource ) Core.mempty
null
https://raw.githubusercontent.com/brendanhay/gogol/77394c4e0f5bd729e6fe27119701c45f9d5e1e9a/lib/services/gogol-firestore/gen/Gogol/FireStore/Projects/Databases/Documents/ListDocuments.hs
haskell
# LANGUAGE OverloadedStrings # # LANGUAGE StrictData # | Stability : auto-generated Lists documents. /See:/ < Cloud Firestore API Reference> for @firestore.projects.databases.documents.listDocuments@. * Resource ** Constructing a Request 'FireStoreProjectsDatabasesDocumentsListDocuments' request conforms to. | Lists documents. /See:/ 'newFireStoreProjectsDatabasesDocumentsListDocuments' smart constructor. | V1 error format. | OAuth access token. | Required. The collection ID, relative to @parent@, to list. For example: @chatrooms@ or @messages@. | The list of field paths in the mask. See Document.fields for a field path syntax reference. | The order to sort results by. For example: @priority desc, name@. | The maximum number of documents to return. | Required. The parent resource name. In the format: @projects\/{project_id}\/databases\/{database_id}\/documents@ or @projects\/{project_id}\/databases\/{database_id}\/documents\/{document_path}@. For example: @projects\/my-project\/databases\/my-database\/documents@ or @projects\/my-project\/databases\/my-database\/documents\/chatrooms\/my-chatroom@ | Reads documents as they were at the given time. This may not be older than 270 seconds. | Reads documents in a transaction. | Upload protocol for media (e.g. \"raw\", \"multipart\"). | Creates a value of 'FireStoreProjectsDatabasesDocumentsListDocuments' with the minimum fields required to make a request. | Required. The collection ID, relative to @parent@, to list. For example: @chatrooms@ or @messages@. See 'collectionId'. | Required. The parent resource name. In the format: @projects\/{project_id}\/databases\/{database_id}\/documents@ or @projects\/{project_id}\/databases\/{database_id}\/documents\/{document_path}@. For example: @projects\/my-project\/databases\/my-database\/documents@ or @projects\/my-project\/databases\/my-database\/documents\/chatrooms\/my-chatroom@ See 'parent'.
# LANGUAGE DataKinds # # LANGUAGE DeriveGeneric # # LANGUAGE DerivingStrategies # # LANGUAGE DuplicateRecordFields # # LANGUAGE FlexibleInstances # # LANGUAGE GeneralizedNewtypeDeriving # # LANGUAGE LambdaCase # # LANGUAGE PatternSynonyms # # LANGUAGE RecordWildCards # # LANGUAGE TypeFamilies # # LANGUAGE TypeOperators # # LANGUAGE NoImplicitPrelude # # OPTIONS_GHC -fno - warn - duplicate - exports # # OPTIONS_GHC -fno - warn - name - shadowing # # OPTIONS_GHC -fno - warn - unused - binds # # OPTIONS_GHC -fno - warn - unused - imports # # OPTIONS_GHC -fno - warn - unused - matches # Module : . FireStore . Projects . Databases . Documents . ListDocuments Copyright : ( c ) 2015 - 2022 License : Mozilla Public License , v. 2.0 . Maintainer : < brendan.g.hay+ > Portability : non - portable ( GHC extensions ) module Gogol.FireStore.Projects.Databases.Documents.ListDocuments FireStoreProjectsDatabasesDocumentsListDocumentsResource, FireStoreProjectsDatabasesDocumentsListDocuments (..), newFireStoreProjectsDatabasesDocumentsListDocuments, ) where import Gogol.FireStore.Types import qualified Gogol.Prelude as Core | A resource alias for method which the type FireStoreProjectsDatabasesDocumentsListDocumentsResource = "v1" Core.:> Core.Capture "parent" Core.Text Core.:> Core.Capture "collectionId" Core.Text Core.:> Core.QueryParam "$.xgafv" Xgafv Core.:> Core.QueryParam "access_token" Core.Text Core.:> Core.QueryParam "callback" Core.Text Core.:> Core.QueryParams "mask.fieldPaths" Core.Text Core.:> Core.QueryParam "orderBy" Core.Text Core.:> Core.QueryParam "pageSize" Core.Int32 Core.:> Core.QueryParam "pageToken" Core.Text Core.:> Core.QueryParam "readTime" Core.DateTime Core.:> Core.QueryParam "showMissing" Core.Bool Core.:> Core.QueryParam "transaction" Core.Base64 Core.:> Core.QueryParam "uploadType" Core.Text Core.:> Core.QueryParam "upload_protocol" Core.Text Core.:> Core.QueryParam "alt" Core.AltJSON Core.:> Core.Get '[Core.JSON] ListDocumentsResponse data FireStoreProjectsDatabasesDocumentsListDocuments = FireStoreProjectsDatabasesDocumentsListDocuments xgafv :: (Core.Maybe Xgafv), accessToken :: (Core.Maybe Core.Text), | JSONP callback :: (Core.Maybe Core.Text), collectionId :: Core.Text, maskFieldPaths :: (Core.Maybe [Core.Text]), orderBy :: (Core.Maybe Core.Text), pageSize :: (Core.Maybe Core.Int32), | The @next_page_token@ value returned from a previous List request , if any . pageToken :: (Core.Maybe Core.Text), parent :: Core.Text, readTime :: (Core.Maybe Core.DateTime), | If the list should show missing documents . A missing document is a document that does not exist but has sub - documents . These documents will be returned with a key but will not have fields , Document.create/time , or Document.update/time set . Requests with @show_missing@ may not specify @where@ or @order_by@. showMissing :: (Core.Maybe Core.Bool), transaction :: (Core.Maybe Core.Base64), | Legacy upload protocol for media ( e.g. \"media\ " , \"multipart\ " ) . uploadType :: (Core.Maybe Core.Text), uploadProtocol :: (Core.Maybe Core.Text) } deriving (Core.Eq, Core.Show, Core.Generic) newFireStoreProjectsDatabasesDocumentsListDocuments :: Core.Text -> Core.Text -> FireStoreProjectsDatabasesDocumentsListDocuments newFireStoreProjectsDatabasesDocumentsListDocuments collectionId parent = FireStoreProjectsDatabasesDocumentsListDocuments { xgafv = Core.Nothing, accessToken = Core.Nothing, callback = Core.Nothing, collectionId = collectionId, maskFieldPaths = Core.Nothing, orderBy = Core.Nothing, pageSize = Core.Nothing, pageToken = Core.Nothing, parent = parent, readTime = Core.Nothing, showMissing = Core.Nothing, transaction = Core.Nothing, uploadType = Core.Nothing, uploadProtocol = Core.Nothing } instance Core.GoogleRequest FireStoreProjectsDatabasesDocumentsListDocuments where type Rs FireStoreProjectsDatabasesDocumentsListDocuments = ListDocumentsResponse type Scopes FireStoreProjectsDatabasesDocumentsListDocuments = '[CloudPlatform'FullControl, Datastore'FullControl] requestClient FireStoreProjectsDatabasesDocumentsListDocuments {..} = go parent collectionId xgafv accessToken callback (maskFieldPaths Core.^. Core._Default) orderBy pageSize pageToken readTime showMissing transaction uploadType uploadProtocol (Core.Just Core.AltJSON) fireStoreService where go = Core.buildClient ( Core.Proxy :: Core.Proxy FireStoreProjectsDatabasesDocumentsListDocumentsResource ) Core.mempty
4ca4eea1f17a531baf5ed5ad171234f7fc41d0d4dca53f30c3befa5de00adb5b
tanakh/optparse-declarative
Declarative.hs
# LANGUAGE CPP # {-# LANGUAGE DataKinds #-} {-# LANGUAGE DefaultSignatures #-} # LANGUAGE ExistentialQuantification # # LANGUAGE FlexibleContexts # # LANGUAGE FlexibleInstances # {-# LANGUAGE GADTs #-} # LANGUAGE GeneralizedNewtypeDeriving # # LANGUAGE KindSignatures # {-# LANGUAGE MultiWayIf #-} {-# LANGUAGE PolyKinds #-} {-# LANGUAGE RankNTypes #-} # LANGUAGE ScopedTypeVariables # # LANGUAGE TupleSections # # LANGUAGE TypeFamilies # {-# LANGUAGE TypeOperators #-} -- | Declarative options parser module Options.Declarative ( -- * Command type IsCmd, Cmd, logStr, getVerbosity, getLogger, -- * Argument definition tools Option(..), Flag, Arg, -- * Defining argument types ArgRead(..), Def, * Subcommands support Group(..), SubCmd, subCmd, -- * Run a command run, run_, ) where import Control.Applicative import Control.Monad import Control.Monad.Catch import Control.Monad.Reader import Data.List import Data.Maybe import Data.Monoid import Data.Proxy import GHC.TypeLits import System.Console.GetOpt import System.Environment import System.Exit import System.IO import Text.Read #if !MIN_VERSION_base(4,13,0) import Control.Monad.Fail #endif -- | Command line option class Option a where -- | Type of the argument' value type Value a :: * -- | Get the argument' value get :: a -> Value a -- | Named argument newtype Flag (shortNames :: Symbol ) (longNames :: [Symbol]) (placeholder :: Symbol ) (help :: Symbol ) a = Flag { getFlag :: a } -- | Unnamed argument newtype Arg (placeholder :: Symbol) a = Arg { getArg :: a } instance ArgRead a => Option (Flag _a _b _c _d a) where type Value (Flag _a _b _c _d a) = Unwrap a get = unwrap . getFlag instance Option (Arg _a a) where type Value (Arg _a a) = a get = getArg -- | Command line option's annotated types class ArgRead a where -- | Type of the argument type Unwrap a :: * type Unwrap a = a -- | Get the argument's value unwrap :: a -> Unwrap a default unwrap :: a ~ Unwrap a => a -> Unwrap a unwrap = id -- | Argument parser argRead :: [String] -> Maybe a default argRead :: Read a => [String] -> Maybe a argRead ss = getLast $ mconcat $ Last . readMaybe <$> ss -- | Indicate this argument is mandatory needArg :: Proxy a -> Bool needArg _ = True instance ArgRead Int instance ArgRead Integer instance ArgRead Double instance {-# OVERLAPPING #-} ArgRead String where argRead [] = Nothing argRead xs = Just $ last xs instance ArgRead Bool where argRead [] = Just False argRead ["f"] = Just False argRead ["t"] = Just True argRead _ = Nothing needArg _ = False instance ArgRead a => ArgRead (Maybe a) where argRead [] = Just Nothing argRead xs = Just <$> argRead xs instance {-# OVERLAPPABLE #-} ArgRead a => ArgRead [a] where argRead xs = Just $ mapMaybe (argRead . (:[])) xs -- | The argument which has default value newtype Def (defaultValue :: Symbol) a = Def { getDef :: a } instance (KnownSymbol defaultValue, ArgRead a) => ArgRead (Def defaultValue a) where type Unwrap (Def defaultValue a) = Unwrap a unwrap = unwrap . getDef argRead s = let s' = case s of [] -> [symbolVal (Proxy :: Proxy defaultValue)] v -> v in Def <$> argRead s' -- | Command newtype Cmd (help :: Symbol) a = Cmd (ReaderT Int IO a) deriving (Functor, Applicative, Alternative, Monad, MonadIO, MonadFix, MonadPlus, MonadFail, MonadThrow, MonadCatch) | Output string when the verbosity level is greater than or equal to ` logLevel ` logStr :: Int -- ^ Verbosity Level -> String -- ^ Message -> Cmd help () logStr logLevel msg = do l <- getLogger l logLevel msg -- | Return the verbosity level ('--verbosity=n') getVerbosity :: Cmd help Int getVerbosity = Cmd ask -- | Retrieve the logger function getLogger :: MonadIO m => Cmd a (Int -> String -> m ()) getLogger = do verbosity <- getVerbosity return $ \logLevel msg -> when (verbosity >= logLevel) $ liftIO $ putStrLn msg -- | Command group data Group = Group { groupHelp :: String , groupCmds :: [SubCmd] } -- | Sub command data SubCmd = forall c. IsCmd c => SubCmd String c -- | Command class class IsCmd c where getCmdHelp :: c -> String default getCmdHelp :: (c ~ (a -> b), IsCmd b) => c -> String getCmdHelp f = getCmdHelp $ f undefined getOptDescr :: c -> [OptDescr (String, String)] default getOptDescr :: (c ~ (a -> b), IsCmd b) => c -> [OptDescr (String, String)] getOptDescr f = getOptDescr $ f undefined getUsageHeader :: c -> String -> String default getUsageHeader :: (c ~ (a -> b), IsCmd b) => c -> String -> String getUsageHeader f = getUsageHeader $ f undefined getUsageFooter :: c -> String -> String default getUsageFooter :: (c ~ (a -> b), IsCmd b) => c -> String -> String getUsageFooter f = getUsageFooter $ f undefined runCmd :: c -> [String] -- ^ Command name -> Maybe String -- ^ Version -> [(String, String)] -- ^ Options -> [String] -- ^ Non options -> [String] -- ^ Unrecognized options -> IO () class KnownSymbols (s :: [Symbol]) where symbolVals :: Proxy s -> [String] instance KnownSymbols '[] where symbolVals _ = [] instance (KnownSymbol s, KnownSymbols ss) => KnownSymbols (s ': ss) where symbolVals _ = symbolVal (Proxy :: Proxy s) : symbolVals (Proxy :: Proxy ss) instance ( KnownSymbol shortNames , KnownSymbols longNames , KnownSymbol placeholder , KnownSymbol help , ArgRead a , IsCmd c ) => IsCmd (Flag shortNames longNames placeholder help a -> c) where getOptDescr f = let flagName = head $ symbolVals (Proxy :: Proxy longNames) ++ [ [c] | c <- symbolVal (Proxy :: Proxy shortNames) ] in Option (symbolVal (Proxy :: Proxy shortNames)) (symbolVals (Proxy :: Proxy longNames)) (if needArg (Proxy :: Proxy a) then ReqArg (flagName, ) (symbolVal (Proxy :: Proxy placeholder)) else NoArg (flagName, "t")) (symbolVal (Proxy :: Proxy help)) : getOptDescr (f undefined) runCmd f name mbver options nonOptions unrecognized = let flagName = head $ symbolVals (Proxy :: Proxy longNames) ++ [ [c] | c <- symbolVal (Proxy :: Proxy shortNames) ] mbs = map snd $ filter ((== flagName) . fst) options in case (argRead mbs, mbs) of (Nothing, []) -> errorExit name $ "flag must be specified: --" ++ flagName (Nothing, s:_) -> errorExit name $ "bad argument: --" ++ flagName ++ "=" ++ s (Just arg, _) -> runCmd (f $ Flag arg) name mbver options nonOptions unrecognized instance {-# OVERLAPPABLE #-} ( KnownSymbol placeholder, ArgRead a, IsCmd c ) => IsCmd (Arg placeholder a -> c) where getUsageHeader = getUsageHeaderOne (Proxy :: Proxy placeholder) runCmd = runCmdOne instance {-# OVERLAPPING #-} ( KnownSymbol placeholder, IsCmd c ) => IsCmd (Arg placeholder String -> c) where getUsageHeader = getUsageHeaderOne (Proxy :: Proxy placeholder) runCmd = runCmdOne getUsageHeaderOne :: ( KnownSymbol placeholder, ArgRead a, IsCmd c ) => Proxy placeholder -> (Arg placeholder a -> c) -> String -> String getUsageHeaderOne proxy f prog = " " ++ symbolVal proxy ++ getUsageHeader (f undefined) prog runCmdOne f name mbver options nonOptions unrecognized = case nonOptions of [] -> errorExit name "not enough arguments" (opt: rest) -> case argRead [opt] of Nothing -> errorExit name $ "bad argument: " ++ opt Just arg -> runCmd (f $ Arg arg) name mbver options rest unrecognized instance {-# OVERLAPPING #-} ( KnownSymbol placeholder, ArgRead a, IsCmd c ) => IsCmd (Arg placeholder [a] -> c) where getUsageHeader f prog = " " ++ symbolVal (Proxy :: Proxy placeholder) ++ getUsageHeader (f undefined) prog runCmd f name mbver options nonOptions unrecognized = case traverse argRead $ (:[]) <$> nonOptions of Nothing -> errorExit name $ "bad arguments: " ++ unwords nonOptions Just opts -> runCmd (f $ Arg opts) name mbver options [] unrecognized instance KnownSymbol help => IsCmd (Cmd help ()) where getCmdHelp _ = symbolVal (Proxy :: Proxy help) getOptDescr _ = [] getUsageHeader _ _ = "" getUsageFooter _ _ = "" runCmd (Cmd m) name _ options nonOptions unrecognized = case (options, nonOptions, unrecognized) of (_, [], []) -> do let verbosityLevel = fromMaybe 0 $ do s <- lookup "verbose" options if | null s -> return 1 | all (== 'v') s -> return $ length s + 1 | otherwise -> readMaybe s runReaderT m verbosityLevel _ -> do forM_ nonOptions $ \o -> errorExit name $ "unrecognized argument '" ++ o ++ "'" forM_ unrecognized $ \o -> errorExit name $ "unrecognized option '" ++ o ++ "'" exitFailure instance IsCmd Group where getCmdHelp = groupHelp getOptDescr _ = [] getUsageHeader _ _ = " <COMMAND> [ARGS...]" getUsageFooter g _ = unlines $ [ "" , "Commands: " ] ++ [ " " ++ name ++ replicate (12 - length name) ' ' ++ getCmdHelp c | SubCmd name c <- groupCmds g ] runCmd g name mbver _options (cmd: nonOptions) unrecognized = case [ SubCmd subname c | SubCmd subname c <- groupCmds g, subname == cmd ] of [SubCmd subname c] -> run' c (name ++ [subname]) mbver (nonOptions ++ unrecognized) _ -> errorExit name $ "unrecognized command: " ++ cmd runCmd _ name _ _ _ _ = errorExit name "no command given" -- | Make a sub command subCmd :: IsCmd c => String -> c -> SubCmd subCmd = SubCmd -- runner run' :: IsCmd c => c -> [String] -> Maybe String -> [String] -> IO () run' cmd name mbver args = do let optDescr = getOptDescr cmd ++ [ Option "?" ["help"] (NoArg ("help", "t")) "display this help and exit" ] ++ [ Option "V" ["version"] (NoArg ("version", "t")) "output version information and exit" | isJust mbver ] ++ [ Option "v" ["verbose"] (OptArg (\arg -> ("verbose", fromMaybe "" arg)) "n") "set verbosity level" ] prog = unwords name verMsg = prog ++ maybe "" (" version " ++) mbver header = "Usage: " ++ prog ++ " [OPTION...]" ++ getUsageHeader cmd prog ++ "\n" ++ " " ++ getCmdHelp cmd ++ "\n\n" ++ "Options:" usage = usageInfo header optDescr ++ getUsageFooter cmd prog case getOpt' RequireOrder optDescr args of (options, nonOptions, unrecognized, errors) | not $ null errors -> errorExit name $ intercalate ", " errors | isJust (lookup "help" options) -> do putStr usage exitSuccess | isJust (lookup "version" options) -> do putStrLn verMsg exitSuccess | otherwise -> runCmd cmd name mbver options nonOptions unrecognized -- | Run a command with specifying program name and version run :: IsCmd c => String -> Maybe String -> c -> IO () run progName progVer cmd = run' cmd [progName] progVer =<< getArgs -- | Run a command run_ :: IsCmd c => c -> IO () run_ cmd = do progName <- getProgName run progName Nothing cmd errorExit :: [String] -> String -> IO () errorExit name msg = do let prog = unwords name hPutStrLn stderr $ prog ++ ": " ++ msg hPutStrLn stderr $ "Try '" ++ prog ++ " --help' for more information." exitFailure
null
https://raw.githubusercontent.com/tanakh/optparse-declarative/bad96bdfc643cc07cc1bcc455a327efb0c80a4eb/src/Options/Declarative.hs
haskell
# LANGUAGE DataKinds # # LANGUAGE DefaultSignatures # # LANGUAGE GADTs # # LANGUAGE MultiWayIf # # LANGUAGE PolyKinds # # LANGUAGE RankNTypes # # LANGUAGE TypeOperators # | Declarative options parser * Command type * Argument definition tools * Defining argument types * Run a command | Command line option | Type of the argument' value | Get the argument' value | Named argument | Unnamed argument | Command line option's annotated types | Type of the argument | Get the argument's value | Argument parser | Indicate this argument is mandatory # OVERLAPPING # # OVERLAPPABLE # | The argument which has default value | Command ^ Verbosity Level ^ Message | Return the verbosity level ('--verbosity=n') | Retrieve the logger function | Command group | Sub command | Command class ^ Command name ^ Version ^ Options ^ Non options ^ Unrecognized options # OVERLAPPABLE # # OVERLAPPING # # OVERLAPPING # | Make a sub command runner | Run a command with specifying program name and version | Run a command
# LANGUAGE CPP # # LANGUAGE ExistentialQuantification # # LANGUAGE FlexibleContexts # # LANGUAGE FlexibleInstances # # LANGUAGE GeneralizedNewtypeDeriving # # LANGUAGE KindSignatures # # LANGUAGE ScopedTypeVariables # # LANGUAGE TupleSections # # LANGUAGE TypeFamilies # module Options.Declarative ( IsCmd, Cmd, logStr, getVerbosity, getLogger, Option(..), Flag, Arg, ArgRead(..), Def, * Subcommands support Group(..), SubCmd, subCmd, run, run_, ) where import Control.Applicative import Control.Monad import Control.Monad.Catch import Control.Monad.Reader import Data.List import Data.Maybe import Data.Monoid import Data.Proxy import GHC.TypeLits import System.Console.GetOpt import System.Environment import System.Exit import System.IO import Text.Read #if !MIN_VERSION_base(4,13,0) import Control.Monad.Fail #endif class Option a where type Value a :: * get :: a -> Value a newtype Flag (shortNames :: Symbol ) (longNames :: [Symbol]) (placeholder :: Symbol ) (help :: Symbol ) a = Flag { getFlag :: a } newtype Arg (placeholder :: Symbol) a = Arg { getArg :: a } instance ArgRead a => Option (Flag _a _b _c _d a) where type Value (Flag _a _b _c _d a) = Unwrap a get = unwrap . getFlag instance Option (Arg _a a) where type Value (Arg _a a) = a get = getArg class ArgRead a where type Unwrap a :: * type Unwrap a = a unwrap :: a -> Unwrap a default unwrap :: a ~ Unwrap a => a -> Unwrap a unwrap = id argRead :: [String] -> Maybe a default argRead :: Read a => [String] -> Maybe a argRead ss = getLast $ mconcat $ Last . readMaybe <$> ss needArg :: Proxy a -> Bool needArg _ = True instance ArgRead Int instance ArgRead Integer instance ArgRead Double argRead [] = Nothing argRead xs = Just $ last xs instance ArgRead Bool where argRead [] = Just False argRead ["f"] = Just False argRead ["t"] = Just True argRead _ = Nothing needArg _ = False instance ArgRead a => ArgRead (Maybe a) where argRead [] = Just Nothing argRead xs = Just <$> argRead xs argRead xs = Just $ mapMaybe (argRead . (:[])) xs newtype Def (defaultValue :: Symbol) a = Def { getDef :: a } instance (KnownSymbol defaultValue, ArgRead a) => ArgRead (Def defaultValue a) where type Unwrap (Def defaultValue a) = Unwrap a unwrap = unwrap . getDef argRead s = let s' = case s of [] -> [symbolVal (Proxy :: Proxy defaultValue)] v -> v in Def <$> argRead s' newtype Cmd (help :: Symbol) a = Cmd (ReaderT Int IO a) deriving (Functor, Applicative, Alternative, Monad, MonadIO, MonadFix, MonadPlus, MonadFail, MonadThrow, MonadCatch) | Output string when the verbosity level is greater than or equal to ` logLevel ` -> Cmd help () logStr logLevel msg = do l <- getLogger l logLevel msg getVerbosity :: Cmd help Int getVerbosity = Cmd ask getLogger :: MonadIO m => Cmd a (Int -> String -> m ()) getLogger = do verbosity <- getVerbosity return $ \logLevel msg -> when (verbosity >= logLevel) $ liftIO $ putStrLn msg data Group = Group { groupHelp :: String , groupCmds :: [SubCmd] } data SubCmd = forall c. IsCmd c => SubCmd String c class IsCmd c where getCmdHelp :: c -> String default getCmdHelp :: (c ~ (a -> b), IsCmd b) => c -> String getCmdHelp f = getCmdHelp $ f undefined getOptDescr :: c -> [OptDescr (String, String)] default getOptDescr :: (c ~ (a -> b), IsCmd b) => c -> [OptDescr (String, String)] getOptDescr f = getOptDescr $ f undefined getUsageHeader :: c -> String -> String default getUsageHeader :: (c ~ (a -> b), IsCmd b) => c -> String -> String getUsageHeader f = getUsageHeader $ f undefined getUsageFooter :: c -> String -> String default getUsageFooter :: (c ~ (a -> b), IsCmd b) => c -> String -> String getUsageFooter f = getUsageFooter $ f undefined runCmd :: c -> IO () class KnownSymbols (s :: [Symbol]) where symbolVals :: Proxy s -> [String] instance KnownSymbols '[] where symbolVals _ = [] instance (KnownSymbol s, KnownSymbols ss) => KnownSymbols (s ': ss) where symbolVals _ = symbolVal (Proxy :: Proxy s) : symbolVals (Proxy :: Proxy ss) instance ( KnownSymbol shortNames , KnownSymbols longNames , KnownSymbol placeholder , KnownSymbol help , ArgRead a , IsCmd c ) => IsCmd (Flag shortNames longNames placeholder help a -> c) where getOptDescr f = let flagName = head $ symbolVals (Proxy :: Proxy longNames) ++ [ [c] | c <- symbolVal (Proxy :: Proxy shortNames) ] in Option (symbolVal (Proxy :: Proxy shortNames)) (symbolVals (Proxy :: Proxy longNames)) (if needArg (Proxy :: Proxy a) then ReqArg (flagName, ) (symbolVal (Proxy :: Proxy placeholder)) else NoArg (flagName, "t")) (symbolVal (Proxy :: Proxy help)) : getOptDescr (f undefined) runCmd f name mbver options nonOptions unrecognized = let flagName = head $ symbolVals (Proxy :: Proxy longNames) ++ [ [c] | c <- symbolVal (Proxy :: Proxy shortNames) ] mbs = map snd $ filter ((== flagName) . fst) options in case (argRead mbs, mbs) of (Nothing, []) -> errorExit name $ "flag must be specified: --" ++ flagName (Nothing, s:_) -> errorExit name $ "bad argument: --" ++ flagName ++ "=" ++ s (Just arg, _) -> runCmd (f $ Flag arg) name mbver options nonOptions unrecognized ( KnownSymbol placeholder, ArgRead a, IsCmd c ) => IsCmd (Arg placeholder a -> c) where getUsageHeader = getUsageHeaderOne (Proxy :: Proxy placeholder) runCmd = runCmdOne ( KnownSymbol placeholder, IsCmd c ) => IsCmd (Arg placeholder String -> c) where getUsageHeader = getUsageHeaderOne (Proxy :: Proxy placeholder) runCmd = runCmdOne getUsageHeaderOne :: ( KnownSymbol placeholder, ArgRead a, IsCmd c ) => Proxy placeholder -> (Arg placeholder a -> c) -> String -> String getUsageHeaderOne proxy f prog = " " ++ symbolVal proxy ++ getUsageHeader (f undefined) prog runCmdOne f name mbver options nonOptions unrecognized = case nonOptions of [] -> errorExit name "not enough arguments" (opt: rest) -> case argRead [opt] of Nothing -> errorExit name $ "bad argument: " ++ opt Just arg -> runCmd (f $ Arg arg) name mbver options rest unrecognized ( KnownSymbol placeholder, ArgRead a, IsCmd c ) => IsCmd (Arg placeholder [a] -> c) where getUsageHeader f prog = " " ++ symbolVal (Proxy :: Proxy placeholder) ++ getUsageHeader (f undefined) prog runCmd f name mbver options nonOptions unrecognized = case traverse argRead $ (:[]) <$> nonOptions of Nothing -> errorExit name $ "bad arguments: " ++ unwords nonOptions Just opts -> runCmd (f $ Arg opts) name mbver options [] unrecognized instance KnownSymbol help => IsCmd (Cmd help ()) where getCmdHelp _ = symbolVal (Proxy :: Proxy help) getOptDescr _ = [] getUsageHeader _ _ = "" getUsageFooter _ _ = "" runCmd (Cmd m) name _ options nonOptions unrecognized = case (options, nonOptions, unrecognized) of (_, [], []) -> do let verbosityLevel = fromMaybe 0 $ do s <- lookup "verbose" options if | null s -> return 1 | all (== 'v') s -> return $ length s + 1 | otherwise -> readMaybe s runReaderT m verbosityLevel _ -> do forM_ nonOptions $ \o -> errorExit name $ "unrecognized argument '" ++ o ++ "'" forM_ unrecognized $ \o -> errorExit name $ "unrecognized option '" ++ o ++ "'" exitFailure instance IsCmd Group where getCmdHelp = groupHelp getOptDescr _ = [] getUsageHeader _ _ = " <COMMAND> [ARGS...]" getUsageFooter g _ = unlines $ [ "" , "Commands: " ] ++ [ " " ++ name ++ replicate (12 - length name) ' ' ++ getCmdHelp c | SubCmd name c <- groupCmds g ] runCmd g name mbver _options (cmd: nonOptions) unrecognized = case [ SubCmd subname c | SubCmd subname c <- groupCmds g, subname == cmd ] of [SubCmd subname c] -> run' c (name ++ [subname]) mbver (nonOptions ++ unrecognized) _ -> errorExit name $ "unrecognized command: " ++ cmd runCmd _ name _ _ _ _ = errorExit name "no command given" subCmd :: IsCmd c => String -> c -> SubCmd subCmd = SubCmd run' :: IsCmd c => c -> [String] -> Maybe String -> [String] -> IO () run' cmd name mbver args = do let optDescr = getOptDescr cmd ++ [ Option "?" ["help"] (NoArg ("help", "t")) "display this help and exit" ] ++ [ Option "V" ["version"] (NoArg ("version", "t")) "output version information and exit" | isJust mbver ] ++ [ Option "v" ["verbose"] (OptArg (\arg -> ("verbose", fromMaybe "" arg)) "n") "set verbosity level" ] prog = unwords name verMsg = prog ++ maybe "" (" version " ++) mbver header = "Usage: " ++ prog ++ " [OPTION...]" ++ getUsageHeader cmd prog ++ "\n" ++ " " ++ getCmdHelp cmd ++ "\n\n" ++ "Options:" usage = usageInfo header optDescr ++ getUsageFooter cmd prog case getOpt' RequireOrder optDescr args of (options, nonOptions, unrecognized, errors) | not $ null errors -> errorExit name $ intercalate ", " errors | isJust (lookup "help" options) -> do putStr usage exitSuccess | isJust (lookup "version" options) -> do putStrLn verMsg exitSuccess | otherwise -> runCmd cmd name mbver options nonOptions unrecognized run :: IsCmd c => String -> Maybe String -> c -> IO () run progName progVer cmd = run' cmd [progName] progVer =<< getArgs run_ :: IsCmd c => c -> IO () run_ cmd = do progName <- getProgName run progName Nothing cmd errorExit :: [String] -> String -> IO () errorExit name msg = do let prog = unwords name hPutStrLn stderr $ prog ++ ": " ++ msg hPutStrLn stderr $ "Try '" ++ prog ++ " --help' for more information." exitFailure
5307a7823020fdb9c817fd74cb89e6a7ecf03df7fab240365a832272d7ba946d
tomjridge/imp_fs
v3_live_object_cache.ml
* Live object cache . A cache of " live " objects . Expunging an object may take some time . Resurrecting an object may take some time . We use reference counting to prevent objects from being expunged while references remain live . We are maintaining a cache of objects by i d. We can maintain the counter with the object . A kref is an abstract wrapper round the object . Essentially it provides : : kref - > obj . It also includes put : kref - > unit which destroys the kref and reduces the underlying count . Do n't open . A cache of "live" objects. Expunging an object may take some time. Resurrecting an object may take some time. We use reference counting to prevent objects from being expunged while references remain live. We are maintaining a cache of objects by id. We can maintain the counter with the object. A kref is an abstract wrapper round the object. Essentially it provides: kref_to_obj: kref -> obj. It also includes put: kref -> unit which destroys the kref and reduces the underlying count. Don't open. *) let line s = Printf.printf "%s: Reached line %d\n%!" "V3_live_object_cache" s; true * User view of krefs ; the user must call when finished with the object . the object. *) type ('obj,'kref) kref_ops = { kref_to_obj : 'kref -> 'obj; krelease : 'kref -> unit; } module Private_kref_impl = struct type 'a kref = { obj: 'a; * whether this kref is valid counter: int ref; (** backing counter *) } let kref_to_obj: 'a kref -> 'a = fun x -> assert(x.valid); x.obj let create ~counter obj = let kref = {obj; valid=true; counter} in (* Add a finalizer to ensure that the obj is not GC'ed in valid state *) assert( kref |> Gc.finalise (fun x -> if x.valid then Printf.printf "WARNING! kref object GC'ed but valid flag was set\n%!"); true); kref let krelease kref = kref.valid <- false; Stdlib.decr kref.counter let kref_ops = { kref_to_obj; krelease } end type 'a kref = 'a Private_kref_impl.kref let kref_ops = Private_kref_impl.kref_ops module Kref = Private_kref_impl * A cache of live objects is just an LRU of ref counted objects type 'a counted = { count: int ref; obj: 'a } type ('a,'t) entry = [ | `Resurrecting of (unit,'t)m | `Present of 'a counted | `Finalising of (unit,'t)m ] type config = { cache_size: int; trim_delta: int; } type ('lru,'t) cache = { lru : 'lru; config : config; mutable gc_thread : (unit,'t)m; } type ('id,'a,'kref,'cache,'t) cache_ops = { create : config:config -> 'cache; get : 'id -> 'cache -> ('kref,'t)m; put : 'kref -> unit; kref_to_obj : 'kref -> 'a; } module type S = sig type t = lwt type id type a end module type T = sig type t = lwt type id type a type kref type cache (** resurrect: slow operation to resurrect an object from a persistent store; finalise:called when removing objects from the cache; no outstanding references remain; as such, the object should certainly not be locked *) val make_cache_ops: resurrect : (id -> (a,t)m) -> finalise : ( (id*a) list -> (unit,t)m) -> (id,a,kref,cache,t)cache_ops end module Make(S:S) : T with type id = S.id and type a = S.a = struct let dont_log = !V3_util.dont_log include S open Tjr_monad.With_lwt module Tmp = struct module S' = struct type k = id type v = (a,t)entry end module Lru = Tjr_lru.Mutable.Make_with_pervasives(S') end type lru = Tmp.Lru.t let lru_ops : (id,(a,t)entry,lru) Tjr_lru.Mutable.lru_ops = Tmp.Lru.lru_ops module Lru = (val lru_ops) type nonrec kref = a Private_kref_impl.kref type nonrec cache = (lru,lwt)cache exception Exit_early let make_cache_ops ~resurrect ~finalise = let open (struct (* FIXME we want this to run only when necessary, or at least, to run often if there is a lot of pressure, but not often if less pressure *) (** A thread that scans the Lru to remove entries that are no longer referenced *) let rec gc_thread cache = let overflow = Lru.size cache.lru - cache.config.cache_size in match overflow > 0 with | false -> from_lwt (sleep 1.) >>= fun () -> gc_thread cache | true -> let n_to_remove = overflow+cache.config.trim_delta in let to_trim = ref [] in let n_removed = ref 0 in (* number of removed entries *) (* NOTE we modify the lru state as we iterate over it; this is safe with the current mutable lru implementation I believe *) (* a promise to signal the end of finalising *) let (p,signal_p) = Lwt.wait () in begin try cache.lru |> Lru.iter (fun k v -> match !n_removed >= n_to_remove with | true -> raise Exit_early | false -> match v with | `Finalising _ -> () | `Resurrecting _ -> () | `Present counted -> ( match !(counted.count) with | 0 -> ( (* can remove; so replace existing binding *) Lru.add k (`Finalising (from_lwt p)) cache.lru; to_trim := (k,counted.obj) :: !to_trim; incr n_removed; ()) | _ -> ())) with Exit_early -> () end; begin (* Some warnings *) if !n_removed < n_to_remove then Printf.printf "WARNING! Trimmed %d entries, but this is less than %d \ (amount we aim to trim). Possibly too many live entries?\n%!" !n_removed n_to_remove; if Lru.size cache.lru > cache.config.cache_size then Printf.printf "WARNING! The LRU size %d exceeds the capacity %d and we \ were unable to remove more entries\n%!" (Lru.size cache.lru) cache.config.cache_size (* FIXME what is the reasonable thing to do in this situation? maybe timeout??? or block and wait for finds to complete? Or maybe mark cache as full, so that no new entries get added... possibly this is simplest *) end; finalise !to_trim >>= fun () -> (* now remove the finalising entries from the map *) (List.map fst !to_trim) |> List.iter (fun k -> Lru.remove k cache.lru); Lwt.wakeup_later signal_p (); gc_thread cache let create ~config = let lru = Lru.create config.cache_size in let cache = {lru; config; gc_thread=(return ()) } in let gc_thread = gc_thread cache in cache.gc_thread <- gc_thread; cache (* FIXME a bit worried about thrashing eg a thread finds a resurrecting entry, and whilst waiting the entry is resurrected then removed from cache, so the thread has to wait again *) let rec get id cache = assert(dont_log || line __LINE__); match Lru.find id cache.lru with (* If resurrecting or finalising, wait and try again *) | Some(`Resurrecting p) | Some (`Finalising p) -> assert(dont_log || line __LINE__); Lru.promote id cache.lru; (With_lwt.yield () |> from_lwt) >>= fun () -> p >>= fun _ -> get id cache If in the cache , return a new kref | Some(`Present x) -> assert(dont_log || line __LINE__); incr x.count; Lru.promote id cache.lru; return (Kref.create ~counter:x.count x.obj) If not in the cache , resurrect ( and mark resurrecting ) , then place in cache and return kref place in cache and return kref *) | None -> assert(dont_log || line __LINE__); NOTE nasty bug where p was unguarded , ran immediately , returned immediately , then had ` Present overridden by ` Resurrecting ! returned immediately, then had `Present overridden by `Resurrecting! *) let (p,r) = Lwt.wait () in Lru.add id (`Resurrecting (p|>from_lwt)) cache.lru; (* resurrect the object, and replace entry in the cache; then try again *) resurrect id >>= fun obj -> Lru.add id (`Present {count=ref 0;obj}) cache.lru; assert(Lru.find id cache.lru |> function | Some (`Present _) -> true | _ -> false); assert(dont_log || line __LINE__); (Lwt.wakeup_later r ()); assert(dont_log || line __LINE__); get id cache let _ : i d - > ( lru , lwt ) cache - > ( kref , lwt ) m = get let put kref = kref_ops.krelease kref let kref_to_obj = kref_ops.kref_to_obj let cache_ops : (id,a,kref,cache,t)cache_ops = {create;get;put;kref_to_obj} end) in cache_ops let _ = make_cache_ops end
null
https://raw.githubusercontent.com/tomjridge/imp_fs/39314764df2277f4d3fa76b06a2054aac8fcdbcf/src_v3/v3_live_object_cache.ml
ocaml
* backing counter Add a finalizer to ensure that the obj is not GC'ed in valid state * resurrect: slow operation to resurrect an object from a persistent store; finalise:called when removing objects from the cache; no outstanding references remain; as such, the object should certainly not be locked FIXME we want this to run only when necessary, or at least, to run often if there is a lot of pressure, but not often if less pressure * A thread that scans the Lru to remove entries that are no longer referenced number of removed entries NOTE we modify the lru state as we iterate over it; this is safe with the current mutable lru implementation I believe a promise to signal the end of finalising can remove; so replace existing binding Some warnings FIXME what is the reasonable thing to do in this situation? maybe timeout??? or block and wait for finds to complete? Or maybe mark cache as full, so that no new entries get added... possibly this is simplest now remove the finalising entries from the map FIXME a bit worried about thrashing eg a thread finds a resurrecting entry, and whilst waiting the entry is resurrected then removed from cache, so the thread has to wait again If resurrecting or finalising, wait and try again resurrect the object, and replace entry in the cache; then try again
* Live object cache . A cache of " live " objects . Expunging an object may take some time . Resurrecting an object may take some time . We use reference counting to prevent objects from being expunged while references remain live . We are maintaining a cache of objects by i d. We can maintain the counter with the object . A kref is an abstract wrapper round the object . Essentially it provides : : kref - > obj . It also includes put : kref - > unit which destroys the kref and reduces the underlying count . Do n't open . A cache of "live" objects. Expunging an object may take some time. Resurrecting an object may take some time. We use reference counting to prevent objects from being expunged while references remain live. We are maintaining a cache of objects by id. We can maintain the counter with the object. A kref is an abstract wrapper round the object. Essentially it provides: kref_to_obj: kref -> obj. It also includes put: kref -> unit which destroys the kref and reduces the underlying count. Don't open. *) let line s = Printf.printf "%s: Reached line %d\n%!" "V3_live_object_cache" s; true * User view of krefs ; the user must call when finished with the object . the object. *) type ('obj,'kref) kref_ops = { kref_to_obj : 'kref -> 'obj; krelease : 'kref -> unit; } module Private_kref_impl = struct type 'a kref = { obj: 'a; * whether this kref is valid } let kref_to_obj: 'a kref -> 'a = fun x -> assert(x.valid); x.obj let create ~counter obj = let kref = {obj; valid=true; counter} in assert( kref |> Gc.finalise (fun x -> if x.valid then Printf.printf "WARNING! kref object GC'ed but valid flag was set\n%!"); true); kref let krelease kref = kref.valid <- false; Stdlib.decr kref.counter let kref_ops = { kref_to_obj; krelease } end type 'a kref = 'a Private_kref_impl.kref let kref_ops = Private_kref_impl.kref_ops module Kref = Private_kref_impl * A cache of live objects is just an LRU of ref counted objects type 'a counted = { count: int ref; obj: 'a } type ('a,'t) entry = [ | `Resurrecting of (unit,'t)m | `Present of 'a counted | `Finalising of (unit,'t)m ] type config = { cache_size: int; trim_delta: int; } type ('lru,'t) cache = { lru : 'lru; config : config; mutable gc_thread : (unit,'t)m; } type ('id,'a,'kref,'cache,'t) cache_ops = { create : config:config -> 'cache; get : 'id -> 'cache -> ('kref,'t)m; put : 'kref -> unit; kref_to_obj : 'kref -> 'a; } module type S = sig type t = lwt type id type a end module type T = sig type t = lwt type id type a type kref type cache val make_cache_ops: resurrect : (id -> (a,t)m) -> finalise : ( (id*a) list -> (unit,t)m) -> (id,a,kref,cache,t)cache_ops end module Make(S:S) : T with type id = S.id and type a = S.a = struct let dont_log = !V3_util.dont_log include S open Tjr_monad.With_lwt module Tmp = struct module S' = struct type k = id type v = (a,t)entry end module Lru = Tjr_lru.Mutable.Make_with_pervasives(S') end type lru = Tmp.Lru.t let lru_ops : (id,(a,t)entry,lru) Tjr_lru.Mutable.lru_ops = Tmp.Lru.lru_ops module Lru = (val lru_ops) type nonrec kref = a Private_kref_impl.kref type nonrec cache = (lru,lwt)cache exception Exit_early let make_cache_ops ~resurrect ~finalise = let open (struct let rec gc_thread cache = let overflow = Lru.size cache.lru - cache.config.cache_size in match overflow > 0 with | false -> from_lwt (sleep 1.) >>= fun () -> gc_thread cache | true -> let n_to_remove = overflow+cache.config.trim_delta in let to_trim = ref [] in let (p,signal_p) = Lwt.wait () in begin try cache.lru |> Lru.iter (fun k v -> match !n_removed >= n_to_remove with | true -> raise Exit_early | false -> match v with | `Finalising _ -> () | `Resurrecting _ -> () | `Present counted -> ( match !(counted.count) with | 0 -> ( Lru.add k (`Finalising (from_lwt p)) cache.lru; to_trim := (k,counted.obj) :: !to_trim; incr n_removed; ()) | _ -> ())) with Exit_early -> () end; begin if !n_removed < n_to_remove then Printf.printf "WARNING! Trimmed %d entries, but this is less than %d \ (amount we aim to trim). Possibly too many live entries?\n%!" !n_removed n_to_remove; if Lru.size cache.lru > cache.config.cache_size then Printf.printf "WARNING! The LRU size %d exceeds the capacity %d and we \ were unable to remove more entries\n%!" (Lru.size cache.lru) cache.config.cache_size end; finalise !to_trim >>= fun () -> (List.map fst !to_trim) |> List.iter (fun k -> Lru.remove k cache.lru); Lwt.wakeup_later signal_p (); gc_thread cache let create ~config = let lru = Lru.create config.cache_size in let cache = {lru; config; gc_thread=(return ()) } in let gc_thread = gc_thread cache in cache.gc_thread <- gc_thread; cache let rec get id cache = assert(dont_log || line __LINE__); match Lru.find id cache.lru with | Some(`Resurrecting p) | Some (`Finalising p) -> assert(dont_log || line __LINE__); Lru.promote id cache.lru; (With_lwt.yield () |> from_lwt) >>= fun () -> p >>= fun _ -> get id cache If in the cache , return a new kref | Some(`Present x) -> assert(dont_log || line __LINE__); incr x.count; Lru.promote id cache.lru; return (Kref.create ~counter:x.count x.obj) If not in the cache , resurrect ( and mark resurrecting ) , then place in cache and return kref place in cache and return kref *) | None -> assert(dont_log || line __LINE__); NOTE nasty bug where p was unguarded , ran immediately , returned immediately , then had ` Present overridden by ` Resurrecting ! returned immediately, then had `Present overridden by `Resurrecting! *) let (p,r) = Lwt.wait () in Lru.add id (`Resurrecting (p|>from_lwt)) cache.lru; resurrect id >>= fun obj -> Lru.add id (`Present {count=ref 0;obj}) cache.lru; assert(Lru.find id cache.lru |> function | Some (`Present _) -> true | _ -> false); assert(dont_log || line __LINE__); (Lwt.wakeup_later r ()); assert(dont_log || line __LINE__); get id cache let _ : i d - > ( lru , lwt ) cache - > ( kref , lwt ) m = get let put kref = kref_ops.krelease kref let kref_to_obj = kref_ops.kref_to_obj let cache_ops : (id,a,kref,cache,t)cache_ops = {create;get;put;kref_to_obj} end) in cache_ops let _ = make_cache_ops end
a869b56f5222d3ecc681b6a214056a9c8e677e92342f35e2f85c10dea5f5522c
inaka/elvis_core
pass_max_function_arity_elvis_attr.erl
-module(pass_max_function_arity_elvis_attr). -export([f/10]). -elvis([{elvis_style, max_function_arity, #{ max_arity => 10 }}]). f(X1, X2, X3, X4, X5, X6, X7, X8, X9, X0) -> {X1, X2, X3, X4, X5, X6, X7, X8, X9, X0}.
null
https://raw.githubusercontent.com/inaka/elvis_core/96a461f399545065524907d6f53d432fbe0ce16b/test/examples/pass_max_function_arity_elvis_attr.erl
erlang
-module(pass_max_function_arity_elvis_attr). -export([f/10]). -elvis([{elvis_style, max_function_arity, #{ max_arity => 10 }}]). f(X1, X2, X3, X4, X5, X6, X7, X8, X9, X0) -> {X1, X2, X3, X4, X5, X6, X7, X8, X9, X0}.
b1c870059d400a02300eba18fe37b64a3f90bba3dac7ab4e06ac8297fc71bb6d
bennn/forth
exit.rkt
#lang forth 2 2 2 + 2 EXIT + +
null
https://raw.githubusercontent.com/bennn/forth/2e9247b1b8c28402d0eecfc3fb97e805e3074255/examples/exit.rkt
racket
#lang forth 2 2 2 + 2 EXIT + +
39d20789d072b694a7823c9a20df911c1899c12427fd8c861f077e8877a4bafb
FreeProving/free-compiler
Queue.hs
module Queue.WithPatternMatching.Queue where import Queue.WithPatternMatching.Util type Queue a = [a] empty :: Queue a empty = [] isEmpty :: Queue a -> Bool isEmpty q = null q front :: Queue a -> a front (x : q) = x add :: a -> Queue a -> Queue a add x q = q `append` [x]
null
https://raw.githubusercontent.com/FreeProving/free-compiler/6931b9ca652a185a92dd824373f092823aea4ea9/example/Queue/WithPatternMatching/Queue.hs
haskell
module Queue.WithPatternMatching.Queue where import Queue.WithPatternMatching.Util type Queue a = [a] empty :: Queue a empty = [] isEmpty :: Queue a -> Bool isEmpty q = null q front :: Queue a -> a front (x : q) = x add :: a -> Queue a -> Queue a add x q = q `append` [x]
985ff076dd7d40f0071a5ff8eaa560c03ee93c8d750003b4fa63c91790857ecf
emqx/emqx
emqx_persistent_session_gc.erl
%%-------------------------------------------------------------------- Copyright ( c ) 2021 - 2023 EMQ Technologies Co. , Ltd. All Rights Reserved . %% Licensed under the Apache License , Version 2.0 ( the " License " ) ; %% you may not use this file except in compliance with the License. %% You may obtain a copy of the License at %% %% -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(emqx_persistent_session_gc). -behaviour(gen_server). -include("emqx_persistent_session.hrl"). %% API -export([start_link/0]). %% gen_server callbacks -export([ init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2 ]). -ifdef(TEST). -export([ session_gc_worker/2, message_gc_worker/0 ]). -endif. -define(SERVER, ?MODULE). %% TODO: Maybe these should be configurable? -define(MARKER_GRACE_PERIOD, 60000000). -define(ABANDONED_GRACE_PERIOD, 300000000). %%-------------------------------------------------------------------- %% API %%-------------------------------------------------------------------- start_link() -> gen_server:start_link({local, ?SERVER}, ?MODULE, [], []). %%-------------------------------------------------------------------- %% gen_server callbacks %%-------------------------------------------------------------------- init([]) -> process_flag(trap_exit, true), {ok, start_message_gc_timer(start_session_gc_timer(#{}))}. handle_call(_Request, _From, State) -> Reply = ok, {reply, Reply, State}. handle_cast(_Request, State) -> {noreply, State}. handle_info({timeout, Ref, session_gc_timeout}, State) -> State1 = session_gc_timeout(Ref, State), {noreply, State1}; handle_info({timeout, Ref, message_gc_timeout}, State) -> State1 = message_gc_timeout(Ref, State), {noreply, State1}; handle_info(_Info, State) -> {noreply, State}. terminate(_Reason, _State) -> ok. %%-------------------------------------------------------------------- Internal functions %%-------------------------------------------------------------------- %%-------------------------------------------------------------------- Session messages GC %%-------------------------------------------------------------------- start_session_gc_timer(State) -> Interval = emqx_config:get([persistent_session_store, session_message_gc_interval]), State#{session_gc_timer => erlang:start_timer(Interval, self(), session_gc_timeout)}. session_gc_timeout(Ref, #{session_gc_timer := R} = State) when R =:= Ref -> %% Prevent overlapping processes. GCPid = maps:get(session_gc_pid, State, undefined), case GCPid =/= undefined andalso erlang:is_process_alive(GCPid) of true -> start_session_gc_timer(State); false -> start_session_gc_timer(State#{ session_gc_pid => proc_lib:spawn_link(fun session_gc_worker/0) }) end; session_gc_timeout(_Ref, State) -> State. session_gc_worker() -> ok = emqx_persistent_session:gc_session_messages(fun session_gc_worker/2). session_gc_worker(delete, Key) -> emqx_persistent_session:delete_session_message(Key); session_gc_worker(marker, Key) -> TS = emqx_persistent_session:session_message_info(timestamp, Key), case TS + ?MARKER_GRACE_PERIOD < erlang:system_time(microsecond) of true -> emqx_persistent_session:delete_session_message(Key); false -> ok end; session_gc_worker(abandoned, Key) -> TS = emqx_persistent_session:session_message_info(timestamp, Key), case TS + ?ABANDONED_GRACE_PERIOD < erlang:system_time(microsecond) of true -> emqx_persistent_session:delete_session_message(Key); false -> ok end. %%-------------------------------------------------------------------- Message GC %% -------------------------------------------------------------------- The message GC simply removes all messages older than the retain period . A more exact GC would either involve treating the session %% message table as root set, or some kind of reference counting. %% We sacrifice space for simplicity at this point. start_message_gc_timer(State) -> Interval = emqx_config:get([persistent_session_store, session_message_gc_interval]), State#{message_gc_timer => erlang:start_timer(Interval, self(), message_gc_timeout)}. message_gc_timeout(Ref, #{message_gc_timer := R} = State) when R =:= Ref -> %% Prevent overlapping processes. GCPid = maps:get(message_gc_pid, State, undefined), case GCPid =/= undefined andalso erlang:is_process_alive(GCPid) of true -> start_message_gc_timer(State); false -> start_message_gc_timer(State#{ message_gc_pid => proc_lib:spawn_link(fun message_gc_worker/0) }) end; message_gc_timeout(_Ref, State) -> State. message_gc_worker() -> HighWaterMark = erlang:system_time(microsecond) - emqx_config:get(?msg_retain) * 1000, message_gc_worker(emqx_persistent_session:first_message_id(), HighWaterMark). message_gc_worker('$end_of_table', _HighWaterMark) -> ok; message_gc_worker(MsgId, HighWaterMark) -> case emqx_guid:timestamp(MsgId) < HighWaterMark of true -> emqx_persistent_session:delete_message(MsgId), message_gc_worker(emqx_persistent_session:next_message_id(MsgId), HighWaterMark); false -> ok end.
null
https://raw.githubusercontent.com/emqx/emqx/dbc10c2eed3df314586c7b9ac6292083204f1f68/apps/emqx/src/persistent_session/emqx_persistent_session_gc.erl
erlang
-------------------------------------------------------------------- you may not use this file except in compliance with the License. You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing, software 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. -------------------------------------------------------------------- API gen_server callbacks TODO: Maybe these should be configurable? -------------------------------------------------------------------- API -------------------------------------------------------------------- -------------------------------------------------------------------- gen_server callbacks -------------------------------------------------------------------- -------------------------------------------------------------------- -------------------------------------------------------------------- -------------------------------------------------------------------- -------------------------------------------------------------------- Prevent overlapping processes. -------------------------------------------------------------------- -------------------------------------------------------------------- message table as root set, or some kind of reference counting. We sacrifice space for simplicity at this point. Prevent overlapping processes.
Copyright ( c ) 2021 - 2023 EMQ Technologies Co. , Ltd. All Rights Reserved . Licensed under the Apache License , Version 2.0 ( the " License " ) ; distributed under the License is distributed on an " AS IS " BASIS , -module(emqx_persistent_session_gc). -behaviour(gen_server). -include("emqx_persistent_session.hrl"). -export([start_link/0]). -export([ init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2 ]). -ifdef(TEST). -export([ session_gc_worker/2, message_gc_worker/0 ]). -endif. -define(SERVER, ?MODULE). -define(MARKER_GRACE_PERIOD, 60000000). -define(ABANDONED_GRACE_PERIOD, 300000000). start_link() -> gen_server:start_link({local, ?SERVER}, ?MODULE, [], []). init([]) -> process_flag(trap_exit, true), {ok, start_message_gc_timer(start_session_gc_timer(#{}))}. handle_call(_Request, _From, State) -> Reply = ok, {reply, Reply, State}. handle_cast(_Request, State) -> {noreply, State}. handle_info({timeout, Ref, session_gc_timeout}, State) -> State1 = session_gc_timeout(Ref, State), {noreply, State1}; handle_info({timeout, Ref, message_gc_timeout}, State) -> State1 = message_gc_timeout(Ref, State), {noreply, State1}; handle_info(_Info, State) -> {noreply, State}. terminate(_Reason, _State) -> ok. Internal functions Session messages GC start_session_gc_timer(State) -> Interval = emqx_config:get([persistent_session_store, session_message_gc_interval]), State#{session_gc_timer => erlang:start_timer(Interval, self(), session_gc_timeout)}. session_gc_timeout(Ref, #{session_gc_timer := R} = State) when R =:= Ref -> GCPid = maps:get(session_gc_pid, State, undefined), case GCPid =/= undefined andalso erlang:is_process_alive(GCPid) of true -> start_session_gc_timer(State); false -> start_session_gc_timer(State#{ session_gc_pid => proc_lib:spawn_link(fun session_gc_worker/0) }) end; session_gc_timeout(_Ref, State) -> State. session_gc_worker() -> ok = emqx_persistent_session:gc_session_messages(fun session_gc_worker/2). session_gc_worker(delete, Key) -> emqx_persistent_session:delete_session_message(Key); session_gc_worker(marker, Key) -> TS = emqx_persistent_session:session_message_info(timestamp, Key), case TS + ?MARKER_GRACE_PERIOD < erlang:system_time(microsecond) of true -> emqx_persistent_session:delete_session_message(Key); false -> ok end; session_gc_worker(abandoned, Key) -> TS = emqx_persistent_session:session_message_info(timestamp, Key), case TS + ?ABANDONED_GRACE_PERIOD < erlang:system_time(microsecond) of true -> emqx_persistent_session:delete_session_message(Key); false -> ok end. Message GC The message GC simply removes all messages older than the retain period . A more exact GC would either involve treating the session start_message_gc_timer(State) -> Interval = emqx_config:get([persistent_session_store, session_message_gc_interval]), State#{message_gc_timer => erlang:start_timer(Interval, self(), message_gc_timeout)}. message_gc_timeout(Ref, #{message_gc_timer := R} = State) when R =:= Ref -> GCPid = maps:get(message_gc_pid, State, undefined), case GCPid =/= undefined andalso erlang:is_process_alive(GCPid) of true -> start_message_gc_timer(State); false -> start_message_gc_timer(State#{ message_gc_pid => proc_lib:spawn_link(fun message_gc_worker/0) }) end; message_gc_timeout(_Ref, State) -> State. message_gc_worker() -> HighWaterMark = erlang:system_time(microsecond) - emqx_config:get(?msg_retain) * 1000, message_gc_worker(emqx_persistent_session:first_message_id(), HighWaterMark). message_gc_worker('$end_of_table', _HighWaterMark) -> ok; message_gc_worker(MsgId, HighWaterMark) -> case emqx_guid:timestamp(MsgId) < HighWaterMark of true -> emqx_persistent_session:delete_message(MsgId), message_gc_worker(emqx_persistent_session:next_message_id(MsgId), HighWaterMark); false -> ok end.
dd2616839cce2b7f785b7e6a9286fd89cf512a7f60083428e503ef0bde704780
zkincaid/duet
core.ml
* Core contains the core type definitions and conversion functions used by our internal representations , including the type [ ap ] of access paths and [ expr ] of expressions . Further operations on expr can be found in [ ] . our internal representations, including the type [ap] of access paths and [expr] of expressions. Further operations on expr can be found in [AExpr]. *) open Srk open BatPervasives (** Record containing the information of enumeration *) type enuminfo = { enname : string; mutable enitems : (string * int) list } [@@deriving ord] (** Concrete type (any type that is not a named type *) type ctyp = | Void | Lock | Int of int | Float of int | Pointer of typ | Array of typ * (int * int) option | Record of recordinfo | Enum of enuminfo | Func of typ * typ list (** A function type consists of a return type and a list of parameter types. *) | Union of recordinfo | Dynamic (** A default type for values that cannot be assigned a static type, or whose static type is misleading or uninformative *) and typ = | Named of string * ctyp ref (** A named type consists of a name and a reference to its underlying concrete type *) | Concrete of ctyp [@@deriving ord] and field = { finame : string; fityp : typ; fioffset : int; } and recordinfo = { rname : string; rfields : field list; rkey : int; (* key required for duplicate structs etc.*) } (** Unary operations *) type unop = | Neg | BNot [@@deriving ord] (** Binary operations *) type binop = | Add | Minus | Mult | Div | Mod | ShiftL | ShiftR | BXor | BAnd | BOr [@@deriving ord] type pred = | Lt | Le | Eq | Ne [@@deriving ord] type visibility = | VzGlobal (** Global variable *) | VzLocal (** Local variable *) | VzThreadLocal (** Thread local variable (per-thread variable with global scope) *) let vz_is_shared = function | VzGlobal -> true | VzLocal | VzThreadLocal -> false let vz_is_global = function | VzGlobal | VzThreadLocal -> true | VzLocal -> false type varinfo = { mutable vname : string; mutable vid : int; mutable vsubscript : int; (** Variable subscript *) mutable vtyp : typ; mutable vviz : visibility; mutable vaddr_taken: bool; } let compare_varinfo x y = compare (x.vid, x.vsubscript) (y.vid, y.vsubscript) let pp_varinfo formatter x = if x.vsubscript = 0 then Format.pp_print_string formatter x.vname else Format.fprintf formatter "%s<%d>" x.vname x.vsubscript let show_varinfo = SrkUtil.mk_show pp_varinfo module Varinfo = struct include Putil.MakeCoreType(struct type t = varinfo [@@deriving show,ord] let hash x = Hashtbl.hash (x.vid, x.vsubscript) end) let get_visibility v = v.vviz let is_global = vz_is_global % get_visibility let is_shared = vz_is_shared % get_visibility let addr_taken v = v.vaddr_taken let get_type v = v.vtyp let set_global v = v.vviz <- VzGlobal let subscript v ss = { v with vsubscript = ss } let get_subscript v = v.vsubscript let max_var_id = ref 0 (** mk_global_var should not be called directly. Prefer {!Ast.mk_local_var}, {!Ast.mk_global_var}, {!CfgIr.mk_local_var}, and {!CfgIr.mk_global_var} *) let mk_global name typ = let id = !max_var_id in max_var_id := id + 1; { vname = name; vid = id; vsubscript = 0; vtyp = typ; vviz = VzGlobal; vaddr_taken = false } let mk_local name typ = let v = mk_global name typ in v.vviz <- VzLocal; v let mk_thread_local name typ = let v = mk_global name typ in v.vviz <- VzThreadLocal; v let clone v = let clone = mk_global v.vname v.vtyp in clone.vviz <- v.vviz; clone end type offset = | OffsetFixed of int | OffsetUnknown | OffsetNone [@@deriving ord] module Offset = struct include Putil.MakeCoreType(struct type t = offset [@@deriving ord] let pp fmt = function | OffsetFixed x -> Format.pp_print_int fmt x | OffsetUnknown -> Format.pp_print_string fmt "Top" | OffsetNone -> () let hash = Hashtbl.hash end) let add x y = match x,y with | (OffsetFixed x, OffsetFixed y) -> OffsetFixed (x + y) | (OffsetNone, OffsetNone) -> OffsetNone | (OffsetNone, OffsetFixed k) | (OffsetFixed k, OffsetNone) -> OffsetFixed k | _ -> OffsetUnknown end type var = varinfo * offset [@@deriving ord] (** Constants *) type constant = | CInt of int * int | CString of string | CChar of char | CFloat of float * int [@@deriving ord] (** Access paths *) type ap = | Variable of var | Deref of aexpr (** Boolean expressions (in negation normal form) *) and bexpr = | Atom of (pred * aexpr * aexpr) | And of (bexpr * bexpr) | Or of (bexpr * bexpr) (** Expressions *) and aexpr = | Havoc of typ | Constant of constant | Cast of typ * aexpr | BinaryOp of aexpr * binop * aexpr * typ | UnaryOp of unop * aexpr * typ | AccessPath of ap | BoolExpr of bexpr | AddrOf of ap [@@deriving ord] type alloc_target = | AllocHeap | AllocStack * Builtin definitions type builtin = | Alloc of (var * aexpr * alloc_target) | Free of aexpr | Fork of (var option * aexpr * aexpr list) | Acquire of aexpr | Release of aexpr | AtomicBegin | AtomicEnd | Exit (** Definition kind *) and defkind = | Assign of (var * aexpr) | Store of (ap * aexpr) | Call of (var option * aexpr * aexpr list) | Assume of bexpr | Initial | Assert of bexpr * string | AssertMemSafe of aexpr * string | Return of aexpr option | Builtin of builtin and def = { did : int; mutable dkind : defkind } let compare_def x y = compare x.did y.did (** Open types for folding *) type ('a, 'b, 'c) open_aexpr = | OHavoc of typ | OConstant of constant | OCast of typ * 'a | OBinaryOp of 'a * binop * 'a * typ | OUnaryOp of unop * 'a * typ | OAccessPath of 'c | OBoolExpr of 'b | OAddrOf of 'c type ('a, 'b) open_bexpr = | OAtom of (pred * 'a * 'a) | OAnd of ('b * 'b) | OOr of ('b * 'b) type ('a, 'b, 'c) aexpr_algebra = ('a, 'b, 'c) open_aexpr -> 'a type ('a, 'b) bexpr_algebra = ('a, 'b) open_bexpr -> 'b let cil_typ_width t = match Cil.constFold true (Cil.SizeOf t) with | Cil.Const Cil.CInt64 (i, _, _) -> Int64.to_int i | _ -> assert false (* If the width of a float/integer type cannot be determined, use unknown_width *) let _ = Cil.initCIL () let unknown_width = 0 let char_width = 1 let bool_width = 1 let machine_int_width = cil_typ_width (Cil.TInt (Cil.IInt, [])) let pointer_width = cil_typ_width (Cil.TPtr (Cil.TInt (Cil.IInt, []), [])) let typ_string = Concrete (Pointer (Concrete (Int char_width))) (* ========================================================================== *) (* Functions on types *) let resolve_type = function | Named (_, ctyp) -> !ctyp | Concrete ctyp -> ctyp let rec typ_width typ = match resolve_type typ with | Int k -> k | Float k -> k | Void -> 0 | Record record -> List.fold_left (+) 0 (List.map field_width record.rfields) | Union record -> List.fold_left (max) 0 (List.map field_width record.rfields) | Lock -> 2 * machine_int_width | Func (_, _) -> pointer_width | Pointer _ -> pointer_width | Array (_, None) -> unknown_width | Array (_, Some (_, size)) -> size | Dynamic -> unknown_width | Enum _ -> machine_int_width and field_width fi = typ_width fi.fityp let text = Format.pp_print_string let rec pp_ctyp formatter = function | Void -> text formatter "void" | Lock -> text formatter "lock" | Int 0 -> text formatter "int<??>" | Int 1 -> text formatter "char" | Int 4 -> text formatter "int32" | Int 8 -> text formatter "int64" | Int k -> Format.fprintf formatter "int<%d>" k | Float 0 -> text formatter "float<??>" | Float k -> Format.fprintf formatter "float<%d>" k | Pointer t -> Format.fprintf formatter "@[<hov 0>*%a@]" pp_typ t | Array (t, Some (nb, _)) -> Format.fprintf formatter "%a[%d]" pp_typ t nb | Array (t, None) -> Format.fprintf formatter "%a[]" pp_typ t | Record r -> text formatter ("Record " ^ r.rname) | Enum e -> text formatter ("Enum " ^ e.enname) | Func (ret, args) -> Format.fprintf formatter "fun (%a) -> %a" (SrkUtil.pp_print_list pp_typ) args pp_typ ret | Union r -> text formatter ("Union " ^ r.rname) | Dynamic -> text formatter "dynamic" and pp_typ formatter = function | Named (name, _) -> text formatter ("`" ^ name ^ "`") | Concrete ctyp -> pp_ctyp formatter ctyp (** Try to resolve an offset to a sequence of field accesses. *) let rec resolve_offset typ offset = match resolve_type typ, offset with | (_, OffsetNone) -> Some [] | (Record ri, OffsetFixed offset) -> let found x = let new_offset = OffsetFixed (offset - x.fioffset) in match resolve_offset x.fityp new_offset with | Some fs -> Some (x::fs) | None -> None in let rec go = function | (x::_) when x.fioffset = offset -> found x | [x] -> found x | (x::y::_) when offset < y.fioffset -> found x | (_::y::zs) -> go (y::zs) | [] -> None in go ri.rfields | (Union _, _) -> None (* not unique!*) | (_, OffsetFixed 0) -> Some [] | _ -> None let opt_equiv f x y = match (x,y) with | (Some x, Some y) -> f x y | (None, None) -> true | _ -> false let list_equiv p xs ys = (List.length xs) = (List.length ys) && List.for_all2 p xs ys (** Types are equivalent if they agree on everything but record keys *) let rec ctyp_equiv s t = match (s,t) with | (Void, Void) -> true | (Lock, Lock) -> true | (Int sk, Int tk) -> sk = tk | (Float sk, Float tk) -> sk = tk | (Pointer s, Pointer t) -> typ_equiv s t | (Array (s, s_size), Array (t, t_size)) -> typ_equiv s t && opt_equiv (=) s_size t_size | (Record s_ri, Record t_ri) -> record_equiv s_ri t_ri | (Enum s_ei, Enum t_ei) -> enum_equiv s_ei t_ei | (Func (s_ret, s_args), Func (t_ret, t_args)) -> typ_equiv s_ret t_ret && (list_equiv typ_equiv s_args t_args) | (Union s_ri, Union t_ri) -> record_equiv s_ri t_ri | (Dynamic, Dynamic) -> true | _ -> false and typ_equiv s t = match s,t with | (Named (s, _), Named (t, _)) -> s = t | _ -> ctyp_equiv (resolve_type s) (resolve_type t) and record_equiv s t = s.rname = t.rname && list_equiv field_equiv s.rfields t.rfields and field_equiv f g = f.finame = g.finame && typ_equiv f.fityp g.fityp and enum_equiv s t = s.enname = t.enname && list_equiv (=) s.enitems t.enitems let is_pointer_type x = match resolve_type x with | Array _ -> true | Pointer _ -> true | Func _ -> true | _ -> false let is_numeric_type x = match resolve_type x with | Int _ | Float _ | Enum _ -> true | _ -> false let rec typ_get_offsets typ = match resolve_type typ with | Record ri -> let f rest fi = Offset.Set.union (Offset.Set.map (Offset.add (OffsetFixed fi.fioffset)) (typ_get_offsets fi.fityp)) rest in List.fold_left f Offset.Set.empty ri.rfields | Union ri -> let f rest fi = Offset.Set.union (typ_get_offsets fi.fityp) rest in List.fold_left f Offset.Set.empty ri.rfields | _ -> Offset.Set.singleton OffsetNone module Var = struct include Putil.MakeCoreType(struct type t = var [@@deriving ord] let hash (x, y) = Hashtbl.hash (Varinfo.hash x, y) let pp formatter (var, offset) = match resolve_offset var.vtyp offset with | Some [] -> Varinfo.pp formatter var | Some xs -> let pp_elt formatter f = Format.pp_print_string formatter f.finame in Format.fprintf formatter "%a.%a" Varinfo.pp var (SrkUtil.pp_print_enum ~pp_sep:(fun formatter () -> Format.pp_print_string formatter ".") pp_elt) (BatList.enum xs) | None -> Format.fprintf formatter "%a.%a" Varinfo.pp var Offset.pp offset end) let get_type (v, offset) = match resolve_offset v.vtyp offset with | Some [] -> v.vtyp | Some xs -> (BatList.last xs).fityp | None -> Concrete Dynamic let get_visibility (v, _) = Varinfo.get_visibility v let is_global = vz_is_global % get_visibility let is_shared = vz_is_shared % get_visibility let subscript (v,offset) ss = ({ v with vsubscript = ss }, offset) let unsubscript var = subscript var 0 let get_subscript v = (fst v).vsubscript let mk varinfo = (varinfo, OffsetNone) end (* Functions on expressions ***************************************************) let rec fold_aexpr_only f = function | Havoc typ -> f (OHavoc typ) | Constant c -> f (OConstant c) | Cast (typ, aexpr) -> f (OCast (typ, fold_aexpr_only f aexpr)) | BinaryOp (a, op, b, typ) -> f (OBinaryOp (fold_aexpr_only f a, op, fold_aexpr_only f b, typ)) | UnaryOp (op, a, typ) -> f (OUnaryOp (op, fold_aexpr_only f a, typ)) | AccessPath ap -> f (OAccessPath ap) | BoolExpr bexpr -> f (OBoolExpr bexpr) | AddrOf ap -> f (OAddrOf ap) let rec fold_bexpr_only f = function | And (x, y) -> f (OAnd (fold_bexpr_only f x, fold_bexpr_only f y)) | Or (x, y) -> f (OOr (fold_bexpr_only f x, fold_bexpr_only f y)) | Atom (p, x, y) -> f (OAtom (p, x, y)) let rec fold_aexpr f g = let h = function | OBoolExpr bexpr -> f (OBoolExpr (fold_bexpr f g bexpr)) | OHavoc typ -> f (OHavoc typ) | OConstant c -> f (OConstant c) | OCast (typ, aexpr) -> f (OCast (typ, aexpr)) | OBinaryOp (a, op, b, typ) -> f (OBinaryOp (a, op, b, typ)) | OUnaryOp (op, a, typ) -> f (OUnaryOp (op, a, typ)) | OAccessPath ap -> f (OAccessPath ap) | OAddrOf ap -> f (OAddrOf ap) in fold_aexpr_only h and fold_bexpr f g = let h = function | OAtom (pred, left, right) -> g (OAtom (pred, fold_aexpr f g left, fold_aexpr f g right)) | OAnd (x, y) -> g (OAnd (x, y)) | OOr (x, y) -> g (OOr (x, y)) in fold_bexpr_only h let aexpr_of_offset = function | OffsetUnknown -> Havoc (Concrete (Int unknown_width)) | OffsetFixed n -> Constant (CInt (n, unknown_width)) | OffsetNone -> Constant (CInt (0, unknown_width)) let rec aexpr_type = function | Havoc typ -> typ | Constant (CInt (_, ik)) -> Concrete (Int ik) | Constant (CString _) -> Concrete (Pointer (Concrete (Int 1))) | Constant (CChar _) -> Concrete (Int 1) | Constant (CFloat (_, fk)) -> Concrete (Float fk) | Cast (typ, _) -> typ | BinaryOp (_, _, _, typ) -> typ | UnaryOp (_, _, typ) -> typ | AccessPath ap -> ap_type ap | BoolExpr _ -> Concrete (Int 1) | AddrOf ap -> Concrete (Pointer (ap_type ap)) and ap_type ap = let deref_type x = match resolve_type x with | Array (typ, _) -> typ | Pointer typ -> typ | Func _ -> x (* todo *) | Dynamic -> Concrete Dynamic | _ -> Concrete (Pointer (Concrete Dynamic)) in match ap with | Variable v -> Var.get_type v | Deref (BinaryOp (_, Add, Constant (CInt (off, _)), Concrete (Pointer typ))) -> begin match resolve_offset typ (OffsetFixed off) with | None -> Concrete Dynamic | Some [] -> typ | Some xs -> (BatList.last xs).fityp end | Deref (AccessPath ap) -> deref_type (ap_type ap) | Deref _ -> Concrete Dynamic (* Try to rewrite an expression as ptr + constant offset. This could be made significantly more general. *) let to_pointer_offset = function | BinaryOp (ptr, Add, Constant (CInt (off, _)), _) | BinaryOp (Constant (CInt (off, _)), Add, ptr, _) -> begin match resolve_type (aexpr_type ptr) with | Pointer _ -> Some (ptr, off) | _ -> None end | _ -> None let rec pp_aexpr formatter = function | Havoc _ -> Format.pp_print_string formatter "*" | Cast (typ, ex) -> Format.fprintf formatter "(%a)%a" pp_typ typ pp_aexpr ex | BinaryOp (ex1, b, ex2, _) -> let op = match b with | Add -> "+" | Minus -> "-" | Mult -> "*" | Div -> "/" | Mod -> "%" | ShiftL -> "<<" | ShiftR -> ">>" | BXor -> "^" | BAnd -> "&" | BOr -> "|" in Format.fprintf formatter "@[<hov 0>(%a%s%a)@]" pp_aexpr ex1 op pp_aexpr ex2 | UnaryOp (u, ex, _) -> let op = match u with | Neg -> "-" | BNot -> "~" in Format.fprintf formatter "%s%a" op pp_aexpr ex | Constant (CInt (i, _)) -> Format.pp_print_int formatter i | Constant (CString s) -> Format.fprintf formatter "\"%s\"" s | Constant (CChar c) -> Format.pp_print_char formatter c | Constant (CFloat (flt,_)) -> Format.pp_print_float formatter flt | AccessPath ap -> pp_ap formatter ap | BoolExpr b -> pp_bexpr formatter b | AddrOf ap -> Format.fprintf formatter "&%a" pp_ap ap and pp_bexpr formatter = function | And (left, right) -> Format.fprintf formatter "%a&&%a" pp_bexpr left pp_bexpr right | Or (left, right) -> Format.fprintf formatter "%a||%a" pp_bexpr left pp_bexpr right | Atom (pred, left, right) -> let pred = match pred with | Lt -> "<" | Le -> "<=" | Eq -> "==" | Ne -> "!=" in Format.fprintf formatter "%a%s%a" pp_aexpr left pred pp_aexpr right and pp_ap formatter = function | Variable v -> Var.pp formatter v | Deref aexpr -> match to_pointer_offset aexpr with | Some (ptr, offset) -> begin match resolve_type (aexpr_type aexpr) with | Pointer typ -> begin match resolve_offset typ (OffsetFixed offset) with | Some [] | None -> Format.fprintf formatter "(*%a)" pp_aexpr aexpr | Some xs -> Format.fprintf formatter "(%a)->%s" pp_aexpr ptr (String.concat "." (List.map (fun f -> f.finame) xs)) end | _ -> Format.fprintf formatter "(*%a)" pp_aexpr aexpr end | None -> Format.fprintf formatter "(*%a)" pp_aexpr aexpr let show_aexpr = SrkUtil.mk_show pp_aexpr let show_bexpr = SrkUtil.mk_show pp_bexpr let hash_aexpr_alg hash_ap = function | OAccessPath a -> hash_ap a lsl 2 | OAddrOf a -> hash_ap a lsl 2 + 1 | x -> Hashtbl.hash x lsl 2 + 2 let hash_bexpr_alg = Hashtbl.hash let rec ap_hash = function | Variable v -> Var.hash v lsl 1 | Deref aexpr -> (aexpr_hash aexpr) lsl 1 + 1 and aexpr_hash aexpr = fold_aexpr (hash_aexpr_alg ap_hash) hash_bexpr_alg aexpr and bexpr_hash bexpr = fold_bexpr (hash_aexpr_alg ap_hash) hash_bexpr_alg bexpr let rec strip_all_casts_ap = function | Variable v -> Variable v | Deref aexpr -> Deref (strip_all_casts_aexpr aexpr) and strip_all_casts_aexpr aexpr = let f = function | OHavoc typ -> Havoc typ | OConstant const -> Constant const | OCast (_, aexpr) -> aexpr | OBinaryOp (a, op, b, typ) -> BinaryOp (a, op, b, typ) | OUnaryOp (op, a, typ) -> UnaryOp (op, a, typ) | OAccessPath ap -> AccessPath (strip_all_casts_ap ap) | OBoolExpr b -> BoolExpr (strip_all_casts_bexpr b) | OAddrOf ap -> AccessPath (strip_all_casts_ap ap) in fold_aexpr_only f aexpr and strip_all_casts_bexpr bexpr = let f = function | OAnd (a, b) -> And (a, b) | OOr (a, b) -> Or (a, b) | OAtom (pred, a, b) -> Atom (pred, strip_all_casts_aexpr a, strip_all_casts_aexpr b) in fold_bexpr_only f bexpr (* Functions on variables *****************************************************) let get_offsets v = let f offset set = Var.Set.add (v, offset) set in Offset.Set.fold f (typ_get_offsets v.vtyp) Var.Set.empty (* Functions on definitions ***************************************************) let pp_builtin formatter = function | Alloc (lhs, size, AllocHeap) -> Format.fprintf formatter "%a = malloc(%a)" Var.pp lhs pp_aexpr size | Alloc (lhs, size, AllocStack) -> Format.fprintf formatter "%a = alloca(%a)" Var.pp lhs pp_aexpr size | Free (aexpr) -> Format.fprintf formatter "free(%a)" pp_aexpr aexpr | Fork (lhs, func, args) -> begin match lhs with | Some v -> Format.fprintf formatter "%a = " Var.pp v | None -> () end; Format.fprintf formatter "fork(@[%a" pp_aexpr func; if args != [] then Format.fprintf formatter ",@ %a" (SrkUtil.pp_print_enum pp_aexpr) (BatList.enum args); Format.fprintf formatter "@])" | Acquire lock -> Format.fprintf formatter "acquire(%a)" pp_aexpr lock | Release lock -> Format.fprintf formatter "release(%a)" pp_aexpr lock | AtomicBegin -> Format.pp_print_string formatter "atomic_begin" | AtomicEnd -> Format.pp_print_string formatter "atomic_end" | Exit -> Format.pp_print_string formatter "exit" (** Pretty printing for definitions (needs to be rewritten) *) let pp_dk formatter = function | Assign (var, aexpr) -> Format.fprintf formatter "%a=%a" Var.pp var pp_aexpr aexpr | Store (ap, aexpr) -> Format.fprintf formatter "%a=%a" pp_ap ap pp_aexpr aexpr | Call (None, func, args) -> Format.fprintf formatter "%a(%a)" pp_aexpr func (SrkUtil.pp_print_enum pp_aexpr) (BatList.enum args) | Call (Some lhs, func, args) -> Format.fprintf formatter "%a=%a(%a)" Var.pp lhs pp_aexpr func (SrkUtil.pp_print_enum pp_aexpr) (BatList.enum args) | Assume aexpr -> Format.fprintf formatter "assume(%a)" pp_bexpr aexpr | Initial -> Format.pp_print_string formatter "initial" | Assert (e,msg) -> Format.fprintf formatter "assert(%a) : %s" pp_bexpr e msg | AssertMemSafe (e,msg) -> Format.fprintf formatter "memsafe(%a) : %s" pp_aexpr e msg | Return None -> Format.pp_print_string formatter "return" | Return (Some e) -> Format.fprintf formatter "return %a" pp_aexpr e | Builtin b -> pp_builtin formatter b let pp_def formatter def = Format.fprintf formatter "%d : %a" def.did pp_dk def.dkind let eval_binop op i j = match op with | Add -> i + j | Minus -> i - j | Mult -> i * j | Div -> i / j | Mod -> i mod j | ShiftL -> i lsl j | ShiftR -> i lsr j | BXor -> i lxor j | BAnd -> i land j | BOr -> i lor j (******************************************************************************) let aexpr_apply apply_ap f = function | OHavoc typ -> f (Havoc typ) | OConstant c -> f (Constant c) | OCast (typ, aexpr) -> f (Cast (typ, aexpr)) | OBinaryOp (a, op, b, typ) -> f (BinaryOp (a, op, b, typ)) | OUnaryOp (op, a, typ) -> f (UnaryOp (op, a, typ)) | OBoolExpr b -> f (BoolExpr b) | OAccessPath ap -> f (AccessPath (apply_ap ap)) | OAddrOf ap -> f (AddrOf (apply_ap ap)) let aexpr_identity f_ap = function | OHavoc typ -> Havoc typ | OConstant c -> Constant c | OCast (typ, aexpr) -> Cast (typ, aexpr) | OBinaryOp (a, op, b, typ) -> BinaryOp (a, op, b, typ) | OUnaryOp (op, a, typ) -> UnaryOp (op, a, typ) | OBoolExpr b -> BoolExpr b | OAccessPath ap -> AccessPath (f_ap ap) | OAddrOf ap -> AddrOf (f_ap ap) let bexpr_identity = function | OAtom (pred, a, b) -> Atom (pred, a, b) | OAnd (a, b) -> And (a, b) | OOr (a, b) -> Or (a, b) let aexpr_partial_identity f_ap = function | OHavoc typ -> Some (Havoc typ) | OConstant c -> Some (Constant c) | OCast (typ, Some aexpr) -> Some (Cast (typ, aexpr)) | OCast (_, _) -> None | OBinaryOp (Some left, op, Some right, typ) -> Some (BinaryOp (left, op, right, typ)) | OBinaryOp (_, _, _, _) -> None | OUnaryOp (op, Some a, typ) -> Some (UnaryOp (op, a, typ)) | OUnaryOp (_, _, _) -> None | OBoolExpr (Some bexpr) -> Some (BoolExpr bexpr) | OBoolExpr None -> None | OAccessPath ap -> begin match f_ap ap with | Some ap -> Some (AccessPath ap) | None -> None end | OAddrOf ap -> begin match f_ap ap with | Some ap -> Some (AddrOf ap) | None -> None end let bexpr_partial_identity = function | OAtom (pred, Some left, Some right) -> Some (Atom (pred, left, right)) | OAtom (_, _, _) -> None | OAnd (Some left, Some right) -> Some (And (left, right)) | OAnd (_, _) -> None | OOr (Some left, Some right) -> Some (Or (left, right)) | OOr (_, _) -> None (* A variable is free in an expression if it occurs in that expression. *) let free_vars_aexpr_alg free_vars_ap = function | OHavoc _ | OConstant _ -> Var.Set.empty | OAddrOf ap | OAccessPath ap -> free_vars_ap ap | OUnaryOp (_, uses, _) | OCast (_, uses) | OBoolExpr uses -> uses | OBinaryOp (use1, _, use2, _) -> Var.Set.union use1 use2 let free_vars_bexpr_alg = function | OAtom (_, left, right) | OAnd (left, right) | OOr (left, right) -> Var.Set.union left right let rec free_vars_aexpr aexpr = fold_aexpr (free_vars_aexpr_alg free_vars_ap) free_vars_bexpr_alg aexpr and free_vars_bexpr bexpr = fold_bexpr (free_vars_aexpr_alg free_vars_ap) free_vars_bexpr_alg bexpr and free_vars_ap = function | Variable v -> Var.Set.singleton v | Deref aexpr -> free_vars_aexpr aexpr module CoreAP = Putil.MakeCoreType(struct type t = ap [@@deriving show,ord] let hash = ap_hash end) (* An access path is used by an expression if it is read, but is not a subexpression of another access path. If a value is provided for every used access path, then that expression can be evaluated. *) let uses_aexpr_alg aexpr_uses = function | OAccessPath x -> CoreAP.Set.singleton x | OAddrOf (Deref x) -> aexpr_uses x | OHavoc _ | OConstant _ | OAddrOf _ -> CoreAP.Set.empty | OUnaryOp (_, uses, _) | OCast (_, uses) | OBoolExpr uses -> uses | OBinaryOp (use1, _, use2, _) -> CoreAP.Set.union use1 use2 let uses_bexpr_alg = function | OAtom (_, left, right) | OAnd (left, right) | OOr (left, right) -> CoreAP.Set.union left right let rec get_uses_aexpr aexpr = fold_aexpr (uses_aexpr_alg get_uses_aexpr) uses_bexpr_alg aexpr let get_uses_bexpr = fold_bexpr (uses_aexpr_alg get_uses_aexpr) uses_bexpr_alg (* An access path is accessed by an expression if it is read in the concrete execution of that expression. *) let rec accessed_aexpr = function | Havoc _ | Constant _ -> CoreAP.Set.empty | Cast (_, aexpr) -> accessed_aexpr aexpr | BinaryOp (left, _, right, _) -> CoreAP.Set.union (accessed_aexpr left) (accessed_aexpr right) | UnaryOp (_, aexpr, _) -> accessed_aexpr aexpr | AccessPath ap -> CoreAP.Set.add ap (accessed_ap ap) | BoolExpr bexpr -> accessed_bexpr bexpr | AddrOf (Deref aexpr) -> accessed_aexpr aexpr | AddrOf (Variable _) -> CoreAP.Set.empty and accessed_bexpr = function | Atom (_, left, right) -> CoreAP.Set.union (accessed_aexpr left) (accessed_aexpr right) | And (left, right) | Or (left, right) -> CoreAP.Set.union (accessed_bexpr left) (accessed_bexpr right) and accessed_ap ap = CoreAP.Set.add ap (match ap with | Deref aexpr -> accessed_aexpr aexpr | Variable _ -> CoreAP.Set.empty) (** Substitute an access path within an expression *) let rec subst_ap_aexpr f = fold_aexpr (aexpr_identity (subst_ap_ap f)) bexpr_identity * Substitute an access path within a Boolean expression and subst_ap_bexpr f = fold_bexpr (aexpr_identity (subst_ap_ap f)) bexpr_identity (** Substitute an access path within an access path *) and subst_ap_ap f = function | Variable _ as var -> f var | Deref aexpr -> f (Deref (subst_ap_aexpr f aexpr)) (** Substitute an expression within an expression *) let rec subst_aexpr_aexpr f = fold_aexpr (aexpr_apply (subst_aexpr_ap f) f) bexpr_identity * Substitute an expression within a Boolean expression and subst_aexpr_bexpr f = fold_bexpr (aexpr_apply (subst_aexpr_ap f) f) bexpr_identity (** Substitute an expression within an access path *) and subst_aexpr_ap f = function | Deref aexpr -> Deref (subst_aexpr_aexpr f aexpr) | Variable _ as var -> var let rec subst_var_aexpr f = fold_aexpr (aexpr_identity (subst_var_ap f)) bexpr_identity * Substitute a variable within a Boolean expression and subst_var_bexpr f = fold_bexpr (aexpr_identity (subst_var_ap f)) bexpr_identity (** Substitute a variable within an access path *) and subst_var_ap f = function | Variable var -> Variable (f var) | Deref aexpr -> Deref (subst_var_aexpr f aexpr) let rec psubst_var_aexpr f = fold_aexpr (aexpr_partial_identity (psubst_var_ap f)) bexpr_partial_identity * Partial substitution of a variable within a Boolean expression and psubst_var_bexpr f = fold_bexpr (aexpr_partial_identity (psubst_var_ap f)) bexpr_partial_identity (** Partial substitution of a variable within an access path *) and psubst_var_ap f = function | Variable var -> begin match f var with | Some var -> Some (Variable var) | None -> None end | Deref aexpr -> begin match psubst_var_aexpr f aexpr with | Some aexpr -> Some (Deref aexpr) | None -> None end type bexpr_val = BTrue | BFalse | BHavoc | BNone let aexpr_zero = Constant (CInt (0, unknown_width)) let aexpr_one = Constant (CInt (1, unknown_width)) let bexpr_true = Atom (Ne, aexpr_one, aexpr_zero) let bexpr_false = Atom (Eq, aexpr_one, aexpr_zero) let bexpr_havoc = Atom (Ne, (Havoc (Concrete (Int 1))), aexpr_zero) let bexpr_equal x y = compare_bexpr x y = 0 let (simplify_expr, simplify_bexpr) = let constant_bexpr bexpr = if bexpr_equal bexpr bexpr_true then BTrue else if bexpr_equal bexpr bexpr_false then BFalse else if bexpr_equal bexpr bexpr_havoc then BHavoc else BNone in let f = function | OConstant (CInt (i, ik)) -> Constant (CInt (i, ik)) | OConstant x -> Constant x | OCast (typ, e) -> Cast (typ, e) | OBinaryOp (Constant (CInt (i, ik)), op, Constant (CInt (j, _)), _) -> (match op with | Add -> Constant (CInt (i + j, ik)) | Minus -> Constant (CInt (i - j, ik)) | Mult -> Constant (CInt (i * j, ik)) | Div -> Constant (CInt (i / j, ik)) | Mod -> Constant (CInt (i mod j, ik)) | ShiftL -> Constant (CInt (i lsl j, ik)) | ShiftR -> Constant (CInt (i lsr j, ik)) | BXor -> Constant (CInt (i lxor j, ik)) | BAnd -> Constant (CInt (i land j, ik)) | BOr -> Constant (CInt (i lor j, ik))) | OBinaryOp (left, op, right, typ) -> BinaryOp (left, op, right, typ) | OUnaryOp (op, Constant (CInt (i, ik)), _) -> (match op with | Neg -> Constant (CInt (0 - i, ik)) | BNot -> Constant (CInt (lnot i, ik))) | OUnaryOp (op, aexpr, typ) -> UnaryOp (op, aexpr, typ) | OAccessPath ap -> AccessPath ap | OBoolExpr expr -> (match constant_bexpr expr with | BTrue -> Constant (CInt (1, bool_width)) | BFalse -> Constant (CInt (0, bool_width)) | BHavoc -> Havoc (Concrete (Int bool_width)) | BNone -> BoolExpr expr) | OHavoc typ -> Havoc typ | OAddrOf ap -> AddrOf ap in let g = function | OOr (a, b) -> (match (constant_bexpr a, constant_bexpr b) with | (BTrue, _) -> bexpr_true | (_, BTrue) -> bexpr_true | (BFalse, _) -> b | (_, BFalse) -> a | _ -> if bexpr_equal a b then a else Or (a, b)) | OAnd (a, b) -> (match (constant_bexpr a, constant_bexpr b) with | (BFalse, _) -> bexpr_false | (_, BFalse) -> bexpr_false | (BTrue, _) -> b | (_, BTrue) -> a | _ -> if bexpr_equal a b then a else And (a, b)) | OAtom (Eq, Havoc _, _) -> bexpr_havoc | OAtom (Eq, _, Havoc _) -> bexpr_havoc | OAtom (Ne, Havoc _, _) -> bexpr_havoc | OAtom (Ne, _, Havoc _) -> bexpr_havoc | OAtom (pred, Constant (CInt (i, _)), Constant (CInt (j, _))) -> let tr_bool b = if b then bexpr_true else bexpr_false in (match pred with | Lt -> tr_bool (i < j) | Le -> tr_bool (i <= j) | Eq -> tr_bool (i = j) | Ne -> tr_bool (i != j)) | OAtom (pred, a, b) -> Atom (pred, a, b) in (fold_aexpr f g, fold_bexpr f g) (******************************************************************************) (** Access paths *) module AP = struct include CoreAP let get_type = ap_type let get_ctype ap = resolve_type (get_type ap) let addr_of = function | Deref aexpr -> aexpr | var -> AddrOf var let get_visibility = function | Deref _ -> VzGlobal | Variable v -> Var.get_visibility v let is_global = vz_is_global % get_visibility let is_shared = vz_is_shared % get_visibility let subscript n ap = subst_var_ap (fun v -> Var.subscript v n) ap let unsubscript ap = subst_var_ap Var.unsubscript ap let subst_var = subst_var_ap let psubst_var = psubst_var_ap let subst_ap = subst_ap_ap let subst_aexpr = subst_aexpr_ap let free_vars = free_vars_ap let accessed = accessed_ap let strip_all_casts = strip_all_casts_ap (** Access an offset of an access path *) let offset ap offset = match ap with | Deref aexpr -> Deref (BinaryOp (aexpr, Add, aexpr_of_offset offset, aexpr_type aexpr)) | Variable (v, vof) -> Variable (v, Offset.add vof offset) end (******************************************************************************) (** Expressions *) module Aexpr = struct include Putil.MakeCoreType(struct type t = aexpr [@@deriving show,ord] let hash = aexpr_hash end) (* todo: conversion rules *) let add x y = BinaryOp (x, Add, y, Concrete Dynamic) let sub x y = BinaryOp (x, Minus, y, Concrete Dynamic) let mul x y = BinaryOp (x, Mult, y, Concrete Dynamic) let div x y = BinaryOp (x, Div, y, Concrete Dynamic) let modulo x y = BinaryOp (x, Mod, y, Concrete Dynamic) let neg x = UnaryOp (Neg, x, Concrete Dynamic) let addr_of ap = match ap with | Deref aexpr -> aexpr | Variable v -> begin (fst v).vaddr_taken <- true; AddrOf ap end let const_int x = Constant (CInt (x, unknown_width)) let zero = const_int 0 let one = const_int 1 let null typ = Cast (typ, zero) let subst_var = subst_var_aexpr let psubst_var = psubst_var_aexpr let subst_ap = subst_ap_aexpr let subst_aexpr = subst_aexpr_aexpr let free_vars = free_vars_aexpr let accessed = accessed_aexpr let get_uses = get_uses_aexpr let simplify = simplify_expr let rec strip_casts exp = match exp with | Cast (_, exp) -> strip_casts exp | _ -> exp let strip_all_casts = strip_all_casts_aexpr let get_type = aexpr_type let fold = fold_aexpr_only let deep_fold = fold_aexpr end (******************************************************************************) (** Boolean expressions *) module Bexpr = struct include Putil.MakeCoreType(struct type t = bexpr [@@deriving show,ord] let hash = bexpr_hash end) let rec negate = function | And (left, right) -> Or (negate left, negate right) | Or (left, right) -> And (negate left, negate right) | Atom (Lt, left, right) -> Atom (Le, right, left) | Atom (Le, left, right) -> Atom (Lt, right, left) | Atom (Eq, left, right) -> Atom (Ne, left, right) | Atom (Ne, left, right) -> Atom (Eq, left, right) let implies x y = Or (y, negate x) let gt left right = Atom (Lt, right, left) let ge left right = Atom (Le, right, left) let of_aexpr = function | BoolExpr b -> b | aexpr -> Atom (Ne, aexpr, Aexpr.zero) let ktrue = Atom (Le, Aexpr.zero, Aexpr.zero) let kfalse = negate ktrue let havoc = of_aexpr (Havoc (Concrete (Int 1))) let subst_var = subst_var_bexpr let psubst_var = psubst_var_bexpr let subst_ap = subst_ap_bexpr let subst_aexpr = subst_aexpr_bexpr let free_vars = free_vars_bexpr let accessed = accessed_bexpr let get_uses = get_uses_bexpr let eval bexpr = let bexpr = simplify_bexpr bexpr in if bexpr_equal bexpr bexpr_true then Some true else if bexpr_equal bexpr bexpr_false then Some false else None let dnf bexpr = let f = function | OAnd (x, y) -> SrkUtil.cartesian_product (BatList.enum x) (BatList.enum y) |> BatEnum.fold (fun r (x, y) -> (x @ y)::r) [] | OOr (x, y) -> x@y | OAtom (p, a, b) -> [[Atom (p,a,b)]] in let dnf_list = fold_bexpr_only f bexpr in let construct_minterm = BatList.reduce (fun x y -> And (x, y)) in let minterms = List.map construct_minterm dnf_list in BatList.reduce (fun x y -> Or (x, y)) minterms let simplify = simplify_bexpr let strip_all_casts = strip_all_casts_bexpr let fold = fold_bexpr_only let deep_fold = fold_bexpr end (******************************************************************************) (** Definitions *) let dk_get_defs defkind = match defkind with | Assign (lhs, _) -> AP.Set.singleton (Variable lhs) | Store (lhs, _) -> AP.Set.singleton lhs | Call (Some lhs, _, _) -> AP.Set.singleton (Variable lhs) | Call (None, _, _) -> AP.Set.empty | Assume expr -> Bexpr.get_uses expr | Assert (expr, _) -> Bexpr.get_uses expr | AssertMemSafe (expr, _) -> Aexpr.get_uses expr | Initial -> AP.Set.empty | Return _ -> AP.Set.empty | Builtin (Alloc (lhs, _, _)) -> AP.Set.singleton (Variable lhs) | Builtin (Fork (Some lhs, _, _)) -> AP.Set.singleton (Variable lhs) | Builtin (Fork (None, _, _)) -> AP.Set.empty | Builtin (Free _) -> AP.Set.empty | Builtin (Acquire _) | Builtin (Release _) -> AP.Set.empty | Builtin AtomicBegin | Builtin AtomicEnd -> AP.Set.empty | Builtin Exit -> AP.Set.empty let dk_assigned_var = function | Assign (v, _) | Store (Variable v, _) | Call (Some v, _, _) | Builtin (Alloc (v, _, _)) | Builtin (Fork (Some v, _, _)) -> Some v | Store _ | Assume _ | Assert _ | Initial | Return _ | Call (_, _, _) | AssertMemSafe _ | Builtin (Free _) | Builtin (Fork (None, _, _)) | Builtin (Acquire _) | Builtin (Release _) | Builtin AtomicBegin | Builtin AtomicEnd | Builtin Exit -> None let lhs_accessed = function | Variable _ -> AP.Set.empty | Deref aexpr -> Aexpr.accessed aexpr let dk_get_accessed = function | Assign (_, rhs) -> Aexpr.accessed rhs | Store (ap, rhs) -> AP.Set.union (lhs_accessed ap) (Aexpr.accessed rhs) | Call (_, callee, args) | Builtin (Fork (_, callee, args)) -> let f rest expr = AP.Set.union (Aexpr.accessed expr) rest in List.fold_left f (Aexpr.accessed callee) args | Assume bexpr | Assert (bexpr, _) -> Bexpr.accessed bexpr | AssertMemSafe (expr, _) -> Aexpr.accessed expr | Initial -> AP.Set.empty | Return (Some expr) -> Aexpr.accessed expr | Return None -> AP.Set.empty | Builtin (Alloc (_, expr, _)) -> Aexpr.accessed expr | Builtin (Free expr) -> Aexpr.accessed expr | Builtin (Acquire expr) | Builtin (Release expr) -> Aexpr.accessed expr | Builtin AtomicBegin | Builtin AtomicEnd -> AP.Set.empty | Builtin Exit -> AP.Set.empty let lhs_free_vars = function | Variable v -> Var.Set.singleton v | ap -> AP.free_vars ap let dk_free_vars = function | Assign (var, rhs) -> Var.Set.add var (Aexpr.free_vars rhs) | Store (ap, rhs) -> Var.Set.union (lhs_free_vars ap) (Aexpr.free_vars rhs) | Call (lhs, callee, args) -> let f rest exp = Var.Set.union (Aexpr.free_vars exp) rest in let accessed = List.fold_left f (Aexpr.free_vars callee) args in begin match lhs with | Some v -> Var.Set.add v accessed | None -> accessed end | Assume bexpr | Assert (bexpr, _) -> Bexpr.free_vars bexpr | AssertMemSafe (expr, _) -> Aexpr.free_vars expr | Initial -> Var.Set.empty | Return (Some expr) -> Aexpr.free_vars expr | Return None -> Var.Set.empty | Builtin (Alloc (lhs, expr, _)) -> Var.Set.add lhs (Aexpr.free_vars expr) | Builtin (Fork (Some lhs, _, _)) -> Var.Set.singleton lhs | Builtin (Fork (None, _, _)) -> Var.Set.empty | Builtin (Free expr) -> Aexpr.free_vars expr | Builtin (Acquire expr) | Builtin (Release expr) -> Aexpr.free_vars expr | Builtin AtomicBegin | Builtin AtomicEnd -> Var.Set.empty | Builtin Exit -> Var.Set.empty let exprlist_uses = let f l e = AP.Set.union (Aexpr.get_uses e) l in List.fold_left f AP.Set.empty let dk_get_uses = function | Assign (_, expr) -> Aexpr.get_uses expr | Store (_, expr) -> Aexpr.get_uses expr | Call (_, func, args) -> exprlist_uses (func::args) | Assume expr -> Bexpr.get_uses expr | Initial -> AP.Set.empty | Assert (expr, _) -> Bexpr.get_uses expr | AssertMemSafe (expr, _) -> Aexpr.get_uses expr | Return None -> AP.Set.empty | Return (Some expr) -> Aexpr.get_uses expr | Builtin (Alloc (_, expr, _)) -> Aexpr.get_uses expr | Builtin (Free expr) -> Aexpr.get_uses expr | Builtin (Fork (_, func, args)) -> exprlist_uses (func::args) | Builtin (Acquire expr) -> Aexpr.get_uses expr | Builtin (Release expr) -> Aexpr.get_uses expr | Builtin AtomicBegin | Builtin AtomicEnd -> AP.Set.empty | Builtin Exit -> AP.Set.empty module Def = struct include Putil.MakeCoreType(struct type t = def [@@deriving show,ord] let hash x = Hashtbl.hash x.did end) (* To keep track of the max_id of the definition hash table *) let def_max_id = ref 0 let def_increase_id () = def_max_id := !(def_max_id) + 1; !def_max_id;; let location_map = Hashtbl.create 991 let mk ?(loc=Cil.locUnknown) dk = let id = def_increase_id () in Hashtbl.add location_map id loc; { did = id; dkind = dk } let get_location def = try Hashtbl.find location_map def.did with Not_found -> Cil.locUnknown let clone def = mk ~loc:(get_location def) def.dkind let initial = mk Initial let get_defs def = dk_get_defs def.dkind let get_uses def = dk_get_uses def.dkind let get_accessed def = dk_get_accessed def.dkind let free_vars def = dk_free_vars def.dkind let assigned_var def = dk_assigned_var def.dkind end let pp_var = Var.pp let show_var = Var.show let show_ap = AP.show
null
https://raw.githubusercontent.com/zkincaid/duet/eb3dbfe6c51d5e1a11cb39ab8f70584aaaa309f9/duet/core.ml
ocaml
* Record containing the information of enumeration * Concrete type (any type that is not a named type * A function type consists of a return type and a list of parameter types. * A default type for values that cannot be assigned a static type, or whose static type is misleading or uninformative * A named type consists of a name and a reference to its underlying concrete type key required for duplicate structs etc. * Unary operations * Binary operations * Global variable * Local variable * Thread local variable (per-thread variable with global scope) * Variable subscript * mk_global_var should not be called directly. Prefer {!Ast.mk_local_var}, {!Ast.mk_global_var}, {!CfgIr.mk_local_var}, and {!CfgIr.mk_global_var} * Constants * Access paths * Boolean expressions (in negation normal form) * Expressions * Definition kind * Open types for folding If the width of a float/integer type cannot be determined, use unknown_width ========================================================================== Functions on types * Try to resolve an offset to a sequence of field accesses. not unique! * Types are equivalent if they agree on everything but record keys Functions on expressions ************************************************** todo Try to rewrite an expression as ptr + constant offset. This could be made significantly more general. Functions on variables **************************************************** Functions on definitions ************************************************** * Pretty printing for definitions (needs to be rewritten) **************************************************************************** A variable is free in an expression if it occurs in that expression. An access path is used by an expression if it is read, but is not a subexpression of another access path. If a value is provided for every used access path, then that expression can be evaluated. An access path is accessed by an expression if it is read in the concrete execution of that expression. * Substitute an access path within an expression * Substitute an access path within an access path * Substitute an expression within an expression * Substitute an expression within an access path * Substitute a variable within an access path * Partial substitution of a variable within an access path **************************************************************************** * Access paths * Access an offset of an access path **************************************************************************** * Expressions todo: conversion rules **************************************************************************** * Boolean expressions **************************************************************************** * Definitions To keep track of the max_id of the definition hash table
* Core contains the core type definitions and conversion functions used by our internal representations , including the type [ ap ] of access paths and [ expr ] of expressions . Further operations on expr can be found in [ ] . our internal representations, including the type [ap] of access paths and [expr] of expressions. Further operations on expr can be found in [AExpr]. *) open Srk open BatPervasives type enuminfo = { enname : string; mutable enitems : (string * int) list } [@@deriving ord] type ctyp = | Void | Lock | Int of int | Float of int | Pointer of typ | Array of typ * (int * int) option | Record of recordinfo | Enum of enuminfo | Union of recordinfo and typ = | Concrete of ctyp [@@deriving ord] and field = { finame : string; fityp : typ; fioffset : int; } and recordinfo = { rname : string; rfields : field list; } type unop = | Neg | BNot [@@deriving ord] type binop = | Add | Minus | Mult | Div | Mod | ShiftL | ShiftR | BXor | BAnd | BOr [@@deriving ord] type pred = | Lt | Le | Eq | Ne [@@deriving ord] type visibility = let vz_is_shared = function | VzGlobal -> true | VzLocal | VzThreadLocal -> false let vz_is_global = function | VzGlobal | VzThreadLocal -> true | VzLocal -> false type varinfo = { mutable vname : string; mutable vid : int; mutable vtyp : typ; mutable vviz : visibility; mutable vaddr_taken: bool; } let compare_varinfo x y = compare (x.vid, x.vsubscript) (y.vid, y.vsubscript) let pp_varinfo formatter x = if x.vsubscript = 0 then Format.pp_print_string formatter x.vname else Format.fprintf formatter "%s<%d>" x.vname x.vsubscript let show_varinfo = SrkUtil.mk_show pp_varinfo module Varinfo = struct include Putil.MakeCoreType(struct type t = varinfo [@@deriving show,ord] let hash x = Hashtbl.hash (x.vid, x.vsubscript) end) let get_visibility v = v.vviz let is_global = vz_is_global % get_visibility let is_shared = vz_is_shared % get_visibility let addr_taken v = v.vaddr_taken let get_type v = v.vtyp let set_global v = v.vviz <- VzGlobal let subscript v ss = { v with vsubscript = ss } let get_subscript v = v.vsubscript let max_var_id = ref 0 let mk_global name typ = let id = !max_var_id in max_var_id := id + 1; { vname = name; vid = id; vsubscript = 0; vtyp = typ; vviz = VzGlobal; vaddr_taken = false } let mk_local name typ = let v = mk_global name typ in v.vviz <- VzLocal; v let mk_thread_local name typ = let v = mk_global name typ in v.vviz <- VzThreadLocal; v let clone v = let clone = mk_global v.vname v.vtyp in clone.vviz <- v.vviz; clone end type offset = | OffsetFixed of int | OffsetUnknown | OffsetNone [@@deriving ord] module Offset = struct include Putil.MakeCoreType(struct type t = offset [@@deriving ord] let pp fmt = function | OffsetFixed x -> Format.pp_print_int fmt x | OffsetUnknown -> Format.pp_print_string fmt "Top" | OffsetNone -> () let hash = Hashtbl.hash end) let add x y = match x,y with | (OffsetFixed x, OffsetFixed y) -> OffsetFixed (x + y) | (OffsetNone, OffsetNone) -> OffsetNone | (OffsetNone, OffsetFixed k) | (OffsetFixed k, OffsetNone) -> OffsetFixed k | _ -> OffsetUnknown end type var = varinfo * offset [@@deriving ord] type constant = | CInt of int * int | CString of string | CChar of char | CFloat of float * int [@@deriving ord] type ap = | Variable of var | Deref of aexpr and bexpr = | Atom of (pred * aexpr * aexpr) | And of (bexpr * bexpr) | Or of (bexpr * bexpr) and aexpr = | Havoc of typ | Constant of constant | Cast of typ * aexpr | BinaryOp of aexpr * binop * aexpr * typ | UnaryOp of unop * aexpr * typ | AccessPath of ap | BoolExpr of bexpr | AddrOf of ap [@@deriving ord] type alloc_target = | AllocHeap | AllocStack * Builtin definitions type builtin = | Alloc of (var * aexpr * alloc_target) | Free of aexpr | Fork of (var option * aexpr * aexpr list) | Acquire of aexpr | Release of aexpr | AtomicBegin | AtomicEnd | Exit and defkind = | Assign of (var * aexpr) | Store of (ap * aexpr) | Call of (var option * aexpr * aexpr list) | Assume of bexpr | Initial | Assert of bexpr * string | AssertMemSafe of aexpr * string | Return of aexpr option | Builtin of builtin and def = { did : int; mutable dkind : defkind } let compare_def x y = compare x.did y.did type ('a, 'b, 'c) open_aexpr = | OHavoc of typ | OConstant of constant | OCast of typ * 'a | OBinaryOp of 'a * binop * 'a * typ | OUnaryOp of unop * 'a * typ | OAccessPath of 'c | OBoolExpr of 'b | OAddrOf of 'c type ('a, 'b) open_bexpr = | OAtom of (pred * 'a * 'a) | OAnd of ('b * 'b) | OOr of ('b * 'b) type ('a, 'b, 'c) aexpr_algebra = ('a, 'b, 'c) open_aexpr -> 'a type ('a, 'b) bexpr_algebra = ('a, 'b) open_bexpr -> 'b let cil_typ_width t = match Cil.constFold true (Cil.SizeOf t) with | Cil.Const Cil.CInt64 (i, _, _) -> Int64.to_int i | _ -> assert false let _ = Cil.initCIL () let unknown_width = 0 let char_width = 1 let bool_width = 1 let machine_int_width = cil_typ_width (Cil.TInt (Cil.IInt, [])) let pointer_width = cil_typ_width (Cil.TPtr (Cil.TInt (Cil.IInt, []), [])) let typ_string = Concrete (Pointer (Concrete (Int char_width))) let resolve_type = function | Named (_, ctyp) -> !ctyp | Concrete ctyp -> ctyp let rec typ_width typ = match resolve_type typ with | Int k -> k | Float k -> k | Void -> 0 | Record record -> List.fold_left (+) 0 (List.map field_width record.rfields) | Union record -> List.fold_left (max) 0 (List.map field_width record.rfields) | Lock -> 2 * machine_int_width | Func (_, _) -> pointer_width | Pointer _ -> pointer_width | Array (_, None) -> unknown_width | Array (_, Some (_, size)) -> size | Dynamic -> unknown_width | Enum _ -> machine_int_width and field_width fi = typ_width fi.fityp let text = Format.pp_print_string let rec pp_ctyp formatter = function | Void -> text formatter "void" | Lock -> text formatter "lock" | Int 0 -> text formatter "int<??>" | Int 1 -> text formatter "char" | Int 4 -> text formatter "int32" | Int 8 -> text formatter "int64" | Int k -> Format.fprintf formatter "int<%d>" k | Float 0 -> text formatter "float<??>" | Float k -> Format.fprintf formatter "float<%d>" k | Pointer t -> Format.fprintf formatter "@[<hov 0>*%a@]" pp_typ t | Array (t, Some (nb, _)) -> Format.fprintf formatter "%a[%d]" pp_typ t nb | Array (t, None) -> Format.fprintf formatter "%a[]" pp_typ t | Record r -> text formatter ("Record " ^ r.rname) | Enum e -> text formatter ("Enum " ^ e.enname) | Func (ret, args) -> Format.fprintf formatter "fun (%a) -> %a" (SrkUtil.pp_print_list pp_typ) args pp_typ ret | Union r -> text formatter ("Union " ^ r.rname) | Dynamic -> text formatter "dynamic" and pp_typ formatter = function | Named (name, _) -> text formatter ("`" ^ name ^ "`") | Concrete ctyp -> pp_ctyp formatter ctyp let rec resolve_offset typ offset = match resolve_type typ, offset with | (_, OffsetNone) -> Some [] | (Record ri, OffsetFixed offset) -> let found x = let new_offset = OffsetFixed (offset - x.fioffset) in match resolve_offset x.fityp new_offset with | Some fs -> Some (x::fs) | None -> None in let rec go = function | (x::_) when x.fioffset = offset -> found x | [x] -> found x | (x::y::_) when offset < y.fioffset -> found x | (_::y::zs) -> go (y::zs) | [] -> None in go ri.rfields | (_, OffsetFixed 0) -> Some [] | _ -> None let opt_equiv f x y = match (x,y) with | (Some x, Some y) -> f x y | (None, None) -> true | _ -> false let list_equiv p xs ys = (List.length xs) = (List.length ys) && List.for_all2 p xs ys let rec ctyp_equiv s t = match (s,t) with | (Void, Void) -> true | (Lock, Lock) -> true | (Int sk, Int tk) -> sk = tk | (Float sk, Float tk) -> sk = tk | (Pointer s, Pointer t) -> typ_equiv s t | (Array (s, s_size), Array (t, t_size)) -> typ_equiv s t && opt_equiv (=) s_size t_size | (Record s_ri, Record t_ri) -> record_equiv s_ri t_ri | (Enum s_ei, Enum t_ei) -> enum_equiv s_ei t_ei | (Func (s_ret, s_args), Func (t_ret, t_args)) -> typ_equiv s_ret t_ret && (list_equiv typ_equiv s_args t_args) | (Union s_ri, Union t_ri) -> record_equiv s_ri t_ri | (Dynamic, Dynamic) -> true | _ -> false and typ_equiv s t = match s,t with | (Named (s, _), Named (t, _)) -> s = t | _ -> ctyp_equiv (resolve_type s) (resolve_type t) and record_equiv s t = s.rname = t.rname && list_equiv field_equiv s.rfields t.rfields and field_equiv f g = f.finame = g.finame && typ_equiv f.fityp g.fityp and enum_equiv s t = s.enname = t.enname && list_equiv (=) s.enitems t.enitems let is_pointer_type x = match resolve_type x with | Array _ -> true | Pointer _ -> true | Func _ -> true | _ -> false let is_numeric_type x = match resolve_type x with | Int _ | Float _ | Enum _ -> true | _ -> false let rec typ_get_offsets typ = match resolve_type typ with | Record ri -> let f rest fi = Offset.Set.union (Offset.Set.map (Offset.add (OffsetFixed fi.fioffset)) (typ_get_offsets fi.fityp)) rest in List.fold_left f Offset.Set.empty ri.rfields | Union ri -> let f rest fi = Offset.Set.union (typ_get_offsets fi.fityp) rest in List.fold_left f Offset.Set.empty ri.rfields | _ -> Offset.Set.singleton OffsetNone module Var = struct include Putil.MakeCoreType(struct type t = var [@@deriving ord] let hash (x, y) = Hashtbl.hash (Varinfo.hash x, y) let pp formatter (var, offset) = match resolve_offset var.vtyp offset with | Some [] -> Varinfo.pp formatter var | Some xs -> let pp_elt formatter f = Format.pp_print_string formatter f.finame in Format.fprintf formatter "%a.%a" Varinfo.pp var (SrkUtil.pp_print_enum ~pp_sep:(fun formatter () -> Format.pp_print_string formatter ".") pp_elt) (BatList.enum xs) | None -> Format.fprintf formatter "%a.%a" Varinfo.pp var Offset.pp offset end) let get_type (v, offset) = match resolve_offset v.vtyp offset with | Some [] -> v.vtyp | Some xs -> (BatList.last xs).fityp | None -> Concrete Dynamic let get_visibility (v, _) = Varinfo.get_visibility v let is_global = vz_is_global % get_visibility let is_shared = vz_is_shared % get_visibility let subscript (v,offset) ss = ({ v with vsubscript = ss }, offset) let unsubscript var = subscript var 0 let get_subscript v = (fst v).vsubscript let mk varinfo = (varinfo, OffsetNone) end let rec fold_aexpr_only f = function | Havoc typ -> f (OHavoc typ) | Constant c -> f (OConstant c) | Cast (typ, aexpr) -> f (OCast (typ, fold_aexpr_only f aexpr)) | BinaryOp (a, op, b, typ) -> f (OBinaryOp (fold_aexpr_only f a, op, fold_aexpr_only f b, typ)) | UnaryOp (op, a, typ) -> f (OUnaryOp (op, fold_aexpr_only f a, typ)) | AccessPath ap -> f (OAccessPath ap) | BoolExpr bexpr -> f (OBoolExpr bexpr) | AddrOf ap -> f (OAddrOf ap) let rec fold_bexpr_only f = function | And (x, y) -> f (OAnd (fold_bexpr_only f x, fold_bexpr_only f y)) | Or (x, y) -> f (OOr (fold_bexpr_only f x, fold_bexpr_only f y)) | Atom (p, x, y) -> f (OAtom (p, x, y)) let rec fold_aexpr f g = let h = function | OBoolExpr bexpr -> f (OBoolExpr (fold_bexpr f g bexpr)) | OHavoc typ -> f (OHavoc typ) | OConstant c -> f (OConstant c) | OCast (typ, aexpr) -> f (OCast (typ, aexpr)) | OBinaryOp (a, op, b, typ) -> f (OBinaryOp (a, op, b, typ)) | OUnaryOp (op, a, typ) -> f (OUnaryOp (op, a, typ)) | OAccessPath ap -> f (OAccessPath ap) | OAddrOf ap -> f (OAddrOf ap) in fold_aexpr_only h and fold_bexpr f g = let h = function | OAtom (pred, left, right) -> g (OAtom (pred, fold_aexpr f g left, fold_aexpr f g right)) | OAnd (x, y) -> g (OAnd (x, y)) | OOr (x, y) -> g (OOr (x, y)) in fold_bexpr_only h let aexpr_of_offset = function | OffsetUnknown -> Havoc (Concrete (Int unknown_width)) | OffsetFixed n -> Constant (CInt (n, unknown_width)) | OffsetNone -> Constant (CInt (0, unknown_width)) let rec aexpr_type = function | Havoc typ -> typ | Constant (CInt (_, ik)) -> Concrete (Int ik) | Constant (CString _) -> Concrete (Pointer (Concrete (Int 1))) | Constant (CChar _) -> Concrete (Int 1) | Constant (CFloat (_, fk)) -> Concrete (Float fk) | Cast (typ, _) -> typ | BinaryOp (_, _, _, typ) -> typ | UnaryOp (_, _, typ) -> typ | AccessPath ap -> ap_type ap | BoolExpr _ -> Concrete (Int 1) | AddrOf ap -> Concrete (Pointer (ap_type ap)) and ap_type ap = let deref_type x = match resolve_type x with | Array (typ, _) -> typ | Pointer typ -> typ | Dynamic -> Concrete Dynamic | _ -> Concrete (Pointer (Concrete Dynamic)) in match ap with | Variable v -> Var.get_type v | Deref (BinaryOp (_, Add, Constant (CInt (off, _)), Concrete (Pointer typ))) -> begin match resolve_offset typ (OffsetFixed off) with | None -> Concrete Dynamic | Some [] -> typ | Some xs -> (BatList.last xs).fityp end | Deref (AccessPath ap) -> deref_type (ap_type ap) | Deref _ -> Concrete Dynamic let to_pointer_offset = function | BinaryOp (ptr, Add, Constant (CInt (off, _)), _) | BinaryOp (Constant (CInt (off, _)), Add, ptr, _) -> begin match resolve_type (aexpr_type ptr) with | Pointer _ -> Some (ptr, off) | _ -> None end | _ -> None let rec pp_aexpr formatter = function | Havoc _ -> Format.pp_print_string formatter "*" | Cast (typ, ex) -> Format.fprintf formatter "(%a)%a" pp_typ typ pp_aexpr ex | BinaryOp (ex1, b, ex2, _) -> let op = match b with | Add -> "+" | Minus -> "-" | Mult -> "*" | Div -> "/" | Mod -> "%" | ShiftL -> "<<" | ShiftR -> ">>" | BXor -> "^" | BAnd -> "&" | BOr -> "|" in Format.fprintf formatter "@[<hov 0>(%a%s%a)@]" pp_aexpr ex1 op pp_aexpr ex2 | UnaryOp (u, ex, _) -> let op = match u with | Neg -> "-" | BNot -> "~" in Format.fprintf formatter "%s%a" op pp_aexpr ex | Constant (CInt (i, _)) -> Format.pp_print_int formatter i | Constant (CString s) -> Format.fprintf formatter "\"%s\"" s | Constant (CChar c) -> Format.pp_print_char formatter c | Constant (CFloat (flt,_)) -> Format.pp_print_float formatter flt | AccessPath ap -> pp_ap formatter ap | BoolExpr b -> pp_bexpr formatter b | AddrOf ap -> Format.fprintf formatter "&%a" pp_ap ap and pp_bexpr formatter = function | And (left, right) -> Format.fprintf formatter "%a&&%a" pp_bexpr left pp_bexpr right | Or (left, right) -> Format.fprintf formatter "%a||%a" pp_bexpr left pp_bexpr right | Atom (pred, left, right) -> let pred = match pred with | Lt -> "<" | Le -> "<=" | Eq -> "==" | Ne -> "!=" in Format.fprintf formatter "%a%s%a" pp_aexpr left pred pp_aexpr right and pp_ap formatter = function | Variable v -> Var.pp formatter v | Deref aexpr -> match to_pointer_offset aexpr with | Some (ptr, offset) -> begin match resolve_type (aexpr_type aexpr) with | Pointer typ -> begin match resolve_offset typ (OffsetFixed offset) with | Some [] | None -> Format.fprintf formatter "(*%a)" pp_aexpr aexpr | Some xs -> Format.fprintf formatter "(%a)->%s" pp_aexpr ptr (String.concat "." (List.map (fun f -> f.finame) xs)) end | _ -> Format.fprintf formatter "(*%a)" pp_aexpr aexpr end | None -> Format.fprintf formatter "(*%a)" pp_aexpr aexpr let show_aexpr = SrkUtil.mk_show pp_aexpr let show_bexpr = SrkUtil.mk_show pp_bexpr let hash_aexpr_alg hash_ap = function | OAccessPath a -> hash_ap a lsl 2 | OAddrOf a -> hash_ap a lsl 2 + 1 | x -> Hashtbl.hash x lsl 2 + 2 let hash_bexpr_alg = Hashtbl.hash let rec ap_hash = function | Variable v -> Var.hash v lsl 1 | Deref aexpr -> (aexpr_hash aexpr) lsl 1 + 1 and aexpr_hash aexpr = fold_aexpr (hash_aexpr_alg ap_hash) hash_bexpr_alg aexpr and bexpr_hash bexpr = fold_bexpr (hash_aexpr_alg ap_hash) hash_bexpr_alg bexpr let rec strip_all_casts_ap = function | Variable v -> Variable v | Deref aexpr -> Deref (strip_all_casts_aexpr aexpr) and strip_all_casts_aexpr aexpr = let f = function | OHavoc typ -> Havoc typ | OConstant const -> Constant const | OCast (_, aexpr) -> aexpr | OBinaryOp (a, op, b, typ) -> BinaryOp (a, op, b, typ) | OUnaryOp (op, a, typ) -> UnaryOp (op, a, typ) | OAccessPath ap -> AccessPath (strip_all_casts_ap ap) | OBoolExpr b -> BoolExpr (strip_all_casts_bexpr b) | OAddrOf ap -> AccessPath (strip_all_casts_ap ap) in fold_aexpr_only f aexpr and strip_all_casts_bexpr bexpr = let f = function | OAnd (a, b) -> And (a, b) | OOr (a, b) -> Or (a, b) | OAtom (pred, a, b) -> Atom (pred, strip_all_casts_aexpr a, strip_all_casts_aexpr b) in fold_bexpr_only f bexpr let get_offsets v = let f offset set = Var.Set.add (v, offset) set in Offset.Set.fold f (typ_get_offsets v.vtyp) Var.Set.empty let pp_builtin formatter = function | Alloc (lhs, size, AllocHeap) -> Format.fprintf formatter "%a = malloc(%a)" Var.pp lhs pp_aexpr size | Alloc (lhs, size, AllocStack) -> Format.fprintf formatter "%a = alloca(%a)" Var.pp lhs pp_aexpr size | Free (aexpr) -> Format.fprintf formatter "free(%a)" pp_aexpr aexpr | Fork (lhs, func, args) -> begin match lhs with | Some v -> Format.fprintf formatter "%a = " Var.pp v | None -> () end; Format.fprintf formatter "fork(@[%a" pp_aexpr func; if args != [] then Format.fprintf formatter ",@ %a" (SrkUtil.pp_print_enum pp_aexpr) (BatList.enum args); Format.fprintf formatter "@])" | Acquire lock -> Format.fprintf formatter "acquire(%a)" pp_aexpr lock | Release lock -> Format.fprintf formatter "release(%a)" pp_aexpr lock | AtomicBegin -> Format.pp_print_string formatter "atomic_begin" | AtomicEnd -> Format.pp_print_string formatter "atomic_end" | Exit -> Format.pp_print_string formatter "exit" let pp_dk formatter = function | Assign (var, aexpr) -> Format.fprintf formatter "%a=%a" Var.pp var pp_aexpr aexpr | Store (ap, aexpr) -> Format.fprintf formatter "%a=%a" pp_ap ap pp_aexpr aexpr | Call (None, func, args) -> Format.fprintf formatter "%a(%a)" pp_aexpr func (SrkUtil.pp_print_enum pp_aexpr) (BatList.enum args) | Call (Some lhs, func, args) -> Format.fprintf formatter "%a=%a(%a)" Var.pp lhs pp_aexpr func (SrkUtil.pp_print_enum pp_aexpr) (BatList.enum args) | Assume aexpr -> Format.fprintf formatter "assume(%a)" pp_bexpr aexpr | Initial -> Format.pp_print_string formatter "initial" | Assert (e,msg) -> Format.fprintf formatter "assert(%a) : %s" pp_bexpr e msg | AssertMemSafe (e,msg) -> Format.fprintf formatter "memsafe(%a) : %s" pp_aexpr e msg | Return None -> Format.pp_print_string formatter "return" | Return (Some e) -> Format.fprintf formatter "return %a" pp_aexpr e | Builtin b -> pp_builtin formatter b let pp_def formatter def = Format.fprintf formatter "%d : %a" def.did pp_dk def.dkind let eval_binop op i j = match op with | Add -> i + j | Minus -> i - j | Mult -> i * j | Div -> i / j | Mod -> i mod j | ShiftL -> i lsl j | ShiftR -> i lsr j | BXor -> i lxor j | BAnd -> i land j | BOr -> i lor j let aexpr_apply apply_ap f = function | OHavoc typ -> f (Havoc typ) | OConstant c -> f (Constant c) | OCast (typ, aexpr) -> f (Cast (typ, aexpr)) | OBinaryOp (a, op, b, typ) -> f (BinaryOp (a, op, b, typ)) | OUnaryOp (op, a, typ) -> f (UnaryOp (op, a, typ)) | OBoolExpr b -> f (BoolExpr b) | OAccessPath ap -> f (AccessPath (apply_ap ap)) | OAddrOf ap -> f (AddrOf (apply_ap ap)) let aexpr_identity f_ap = function | OHavoc typ -> Havoc typ | OConstant c -> Constant c | OCast (typ, aexpr) -> Cast (typ, aexpr) | OBinaryOp (a, op, b, typ) -> BinaryOp (a, op, b, typ) | OUnaryOp (op, a, typ) -> UnaryOp (op, a, typ) | OBoolExpr b -> BoolExpr b | OAccessPath ap -> AccessPath (f_ap ap) | OAddrOf ap -> AddrOf (f_ap ap) let bexpr_identity = function | OAtom (pred, a, b) -> Atom (pred, a, b) | OAnd (a, b) -> And (a, b) | OOr (a, b) -> Or (a, b) let aexpr_partial_identity f_ap = function | OHavoc typ -> Some (Havoc typ) | OConstant c -> Some (Constant c) | OCast (typ, Some aexpr) -> Some (Cast (typ, aexpr)) | OCast (_, _) -> None | OBinaryOp (Some left, op, Some right, typ) -> Some (BinaryOp (left, op, right, typ)) | OBinaryOp (_, _, _, _) -> None | OUnaryOp (op, Some a, typ) -> Some (UnaryOp (op, a, typ)) | OUnaryOp (_, _, _) -> None | OBoolExpr (Some bexpr) -> Some (BoolExpr bexpr) | OBoolExpr None -> None | OAccessPath ap -> begin match f_ap ap with | Some ap -> Some (AccessPath ap) | None -> None end | OAddrOf ap -> begin match f_ap ap with | Some ap -> Some (AddrOf ap) | None -> None end let bexpr_partial_identity = function | OAtom (pred, Some left, Some right) -> Some (Atom (pred, left, right)) | OAtom (_, _, _) -> None | OAnd (Some left, Some right) -> Some (And (left, right)) | OAnd (_, _) -> None | OOr (Some left, Some right) -> Some (Or (left, right)) | OOr (_, _) -> None let free_vars_aexpr_alg free_vars_ap = function | OHavoc _ | OConstant _ -> Var.Set.empty | OAddrOf ap | OAccessPath ap -> free_vars_ap ap | OUnaryOp (_, uses, _) | OCast (_, uses) | OBoolExpr uses -> uses | OBinaryOp (use1, _, use2, _) -> Var.Set.union use1 use2 let free_vars_bexpr_alg = function | OAtom (_, left, right) | OAnd (left, right) | OOr (left, right) -> Var.Set.union left right let rec free_vars_aexpr aexpr = fold_aexpr (free_vars_aexpr_alg free_vars_ap) free_vars_bexpr_alg aexpr and free_vars_bexpr bexpr = fold_bexpr (free_vars_aexpr_alg free_vars_ap) free_vars_bexpr_alg bexpr and free_vars_ap = function | Variable v -> Var.Set.singleton v | Deref aexpr -> free_vars_aexpr aexpr module CoreAP = Putil.MakeCoreType(struct type t = ap [@@deriving show,ord] let hash = ap_hash end) let uses_aexpr_alg aexpr_uses = function | OAccessPath x -> CoreAP.Set.singleton x | OAddrOf (Deref x) -> aexpr_uses x | OHavoc _ | OConstant _ | OAddrOf _ -> CoreAP.Set.empty | OUnaryOp (_, uses, _) | OCast (_, uses) | OBoolExpr uses -> uses | OBinaryOp (use1, _, use2, _) -> CoreAP.Set.union use1 use2 let uses_bexpr_alg = function | OAtom (_, left, right) | OAnd (left, right) | OOr (left, right) -> CoreAP.Set.union left right let rec get_uses_aexpr aexpr = fold_aexpr (uses_aexpr_alg get_uses_aexpr) uses_bexpr_alg aexpr let get_uses_bexpr = fold_bexpr (uses_aexpr_alg get_uses_aexpr) uses_bexpr_alg let rec accessed_aexpr = function | Havoc _ | Constant _ -> CoreAP.Set.empty | Cast (_, aexpr) -> accessed_aexpr aexpr | BinaryOp (left, _, right, _) -> CoreAP.Set.union (accessed_aexpr left) (accessed_aexpr right) | UnaryOp (_, aexpr, _) -> accessed_aexpr aexpr | AccessPath ap -> CoreAP.Set.add ap (accessed_ap ap) | BoolExpr bexpr -> accessed_bexpr bexpr | AddrOf (Deref aexpr) -> accessed_aexpr aexpr | AddrOf (Variable _) -> CoreAP.Set.empty and accessed_bexpr = function | Atom (_, left, right) -> CoreAP.Set.union (accessed_aexpr left) (accessed_aexpr right) | And (left, right) | Or (left, right) -> CoreAP.Set.union (accessed_bexpr left) (accessed_bexpr right) and accessed_ap ap = CoreAP.Set.add ap (match ap with | Deref aexpr -> accessed_aexpr aexpr | Variable _ -> CoreAP.Set.empty) let rec subst_ap_aexpr f = fold_aexpr (aexpr_identity (subst_ap_ap f)) bexpr_identity * Substitute an access path within a Boolean expression and subst_ap_bexpr f = fold_bexpr (aexpr_identity (subst_ap_ap f)) bexpr_identity and subst_ap_ap f = function | Variable _ as var -> f var | Deref aexpr -> f (Deref (subst_ap_aexpr f aexpr)) let rec subst_aexpr_aexpr f = fold_aexpr (aexpr_apply (subst_aexpr_ap f) f) bexpr_identity * Substitute an expression within a Boolean expression and subst_aexpr_bexpr f = fold_bexpr (aexpr_apply (subst_aexpr_ap f) f) bexpr_identity and subst_aexpr_ap f = function | Deref aexpr -> Deref (subst_aexpr_aexpr f aexpr) | Variable _ as var -> var let rec subst_var_aexpr f = fold_aexpr (aexpr_identity (subst_var_ap f)) bexpr_identity * Substitute a variable within a Boolean expression and subst_var_bexpr f = fold_bexpr (aexpr_identity (subst_var_ap f)) bexpr_identity and subst_var_ap f = function | Variable var -> Variable (f var) | Deref aexpr -> Deref (subst_var_aexpr f aexpr) let rec psubst_var_aexpr f = fold_aexpr (aexpr_partial_identity (psubst_var_ap f)) bexpr_partial_identity * Partial substitution of a variable within a Boolean expression and psubst_var_bexpr f = fold_bexpr (aexpr_partial_identity (psubst_var_ap f)) bexpr_partial_identity and psubst_var_ap f = function | Variable var -> begin match f var with | Some var -> Some (Variable var) | None -> None end | Deref aexpr -> begin match psubst_var_aexpr f aexpr with | Some aexpr -> Some (Deref aexpr) | None -> None end type bexpr_val = BTrue | BFalse | BHavoc | BNone let aexpr_zero = Constant (CInt (0, unknown_width)) let aexpr_one = Constant (CInt (1, unknown_width)) let bexpr_true = Atom (Ne, aexpr_one, aexpr_zero) let bexpr_false = Atom (Eq, aexpr_one, aexpr_zero) let bexpr_havoc = Atom (Ne, (Havoc (Concrete (Int 1))), aexpr_zero) let bexpr_equal x y = compare_bexpr x y = 0 let (simplify_expr, simplify_bexpr) = let constant_bexpr bexpr = if bexpr_equal bexpr bexpr_true then BTrue else if bexpr_equal bexpr bexpr_false then BFalse else if bexpr_equal bexpr bexpr_havoc then BHavoc else BNone in let f = function | OConstant (CInt (i, ik)) -> Constant (CInt (i, ik)) | OConstant x -> Constant x | OCast (typ, e) -> Cast (typ, e) | OBinaryOp (Constant (CInt (i, ik)), op, Constant (CInt (j, _)), _) -> (match op with | Add -> Constant (CInt (i + j, ik)) | Minus -> Constant (CInt (i - j, ik)) | Mult -> Constant (CInt (i * j, ik)) | Div -> Constant (CInt (i / j, ik)) | Mod -> Constant (CInt (i mod j, ik)) | ShiftL -> Constant (CInt (i lsl j, ik)) | ShiftR -> Constant (CInt (i lsr j, ik)) | BXor -> Constant (CInt (i lxor j, ik)) | BAnd -> Constant (CInt (i land j, ik)) | BOr -> Constant (CInt (i lor j, ik))) | OBinaryOp (left, op, right, typ) -> BinaryOp (left, op, right, typ) | OUnaryOp (op, Constant (CInt (i, ik)), _) -> (match op with | Neg -> Constant (CInt (0 - i, ik)) | BNot -> Constant (CInt (lnot i, ik))) | OUnaryOp (op, aexpr, typ) -> UnaryOp (op, aexpr, typ) | OAccessPath ap -> AccessPath ap | OBoolExpr expr -> (match constant_bexpr expr with | BTrue -> Constant (CInt (1, bool_width)) | BFalse -> Constant (CInt (0, bool_width)) | BHavoc -> Havoc (Concrete (Int bool_width)) | BNone -> BoolExpr expr) | OHavoc typ -> Havoc typ | OAddrOf ap -> AddrOf ap in let g = function | OOr (a, b) -> (match (constant_bexpr a, constant_bexpr b) with | (BTrue, _) -> bexpr_true | (_, BTrue) -> bexpr_true | (BFalse, _) -> b | (_, BFalse) -> a | _ -> if bexpr_equal a b then a else Or (a, b)) | OAnd (a, b) -> (match (constant_bexpr a, constant_bexpr b) with | (BFalse, _) -> bexpr_false | (_, BFalse) -> bexpr_false | (BTrue, _) -> b | (_, BTrue) -> a | _ -> if bexpr_equal a b then a else And (a, b)) | OAtom (Eq, Havoc _, _) -> bexpr_havoc | OAtom (Eq, _, Havoc _) -> bexpr_havoc | OAtom (Ne, Havoc _, _) -> bexpr_havoc | OAtom (Ne, _, Havoc _) -> bexpr_havoc | OAtom (pred, Constant (CInt (i, _)), Constant (CInt (j, _))) -> let tr_bool b = if b then bexpr_true else bexpr_false in (match pred with | Lt -> tr_bool (i < j) | Le -> tr_bool (i <= j) | Eq -> tr_bool (i = j) | Ne -> tr_bool (i != j)) | OAtom (pred, a, b) -> Atom (pred, a, b) in (fold_aexpr f g, fold_bexpr f g) module AP = struct include CoreAP let get_type = ap_type let get_ctype ap = resolve_type (get_type ap) let addr_of = function | Deref aexpr -> aexpr | var -> AddrOf var let get_visibility = function | Deref _ -> VzGlobal | Variable v -> Var.get_visibility v let is_global = vz_is_global % get_visibility let is_shared = vz_is_shared % get_visibility let subscript n ap = subst_var_ap (fun v -> Var.subscript v n) ap let unsubscript ap = subst_var_ap Var.unsubscript ap let subst_var = subst_var_ap let psubst_var = psubst_var_ap let subst_ap = subst_ap_ap let subst_aexpr = subst_aexpr_ap let free_vars = free_vars_ap let accessed = accessed_ap let strip_all_casts = strip_all_casts_ap let offset ap offset = match ap with | Deref aexpr -> Deref (BinaryOp (aexpr, Add, aexpr_of_offset offset, aexpr_type aexpr)) | Variable (v, vof) -> Variable (v, Offset.add vof offset) end module Aexpr = struct include Putil.MakeCoreType(struct type t = aexpr [@@deriving show,ord] let hash = aexpr_hash end) let add x y = BinaryOp (x, Add, y, Concrete Dynamic) let sub x y = BinaryOp (x, Minus, y, Concrete Dynamic) let mul x y = BinaryOp (x, Mult, y, Concrete Dynamic) let div x y = BinaryOp (x, Div, y, Concrete Dynamic) let modulo x y = BinaryOp (x, Mod, y, Concrete Dynamic) let neg x = UnaryOp (Neg, x, Concrete Dynamic) let addr_of ap = match ap with | Deref aexpr -> aexpr | Variable v -> begin (fst v).vaddr_taken <- true; AddrOf ap end let const_int x = Constant (CInt (x, unknown_width)) let zero = const_int 0 let one = const_int 1 let null typ = Cast (typ, zero) let subst_var = subst_var_aexpr let psubst_var = psubst_var_aexpr let subst_ap = subst_ap_aexpr let subst_aexpr = subst_aexpr_aexpr let free_vars = free_vars_aexpr let accessed = accessed_aexpr let get_uses = get_uses_aexpr let simplify = simplify_expr let rec strip_casts exp = match exp with | Cast (_, exp) -> strip_casts exp | _ -> exp let strip_all_casts = strip_all_casts_aexpr let get_type = aexpr_type let fold = fold_aexpr_only let deep_fold = fold_aexpr end module Bexpr = struct include Putil.MakeCoreType(struct type t = bexpr [@@deriving show,ord] let hash = bexpr_hash end) let rec negate = function | And (left, right) -> Or (negate left, negate right) | Or (left, right) -> And (negate left, negate right) | Atom (Lt, left, right) -> Atom (Le, right, left) | Atom (Le, left, right) -> Atom (Lt, right, left) | Atom (Eq, left, right) -> Atom (Ne, left, right) | Atom (Ne, left, right) -> Atom (Eq, left, right) let implies x y = Or (y, negate x) let gt left right = Atom (Lt, right, left) let ge left right = Atom (Le, right, left) let of_aexpr = function | BoolExpr b -> b | aexpr -> Atom (Ne, aexpr, Aexpr.zero) let ktrue = Atom (Le, Aexpr.zero, Aexpr.zero) let kfalse = negate ktrue let havoc = of_aexpr (Havoc (Concrete (Int 1))) let subst_var = subst_var_bexpr let psubst_var = psubst_var_bexpr let subst_ap = subst_ap_bexpr let subst_aexpr = subst_aexpr_bexpr let free_vars = free_vars_bexpr let accessed = accessed_bexpr let get_uses = get_uses_bexpr let eval bexpr = let bexpr = simplify_bexpr bexpr in if bexpr_equal bexpr bexpr_true then Some true else if bexpr_equal bexpr bexpr_false then Some false else None let dnf bexpr = let f = function | OAnd (x, y) -> SrkUtil.cartesian_product (BatList.enum x) (BatList.enum y) |> BatEnum.fold (fun r (x, y) -> (x @ y)::r) [] | OOr (x, y) -> x@y | OAtom (p, a, b) -> [[Atom (p,a,b)]] in let dnf_list = fold_bexpr_only f bexpr in let construct_minterm = BatList.reduce (fun x y -> And (x, y)) in let minterms = List.map construct_minterm dnf_list in BatList.reduce (fun x y -> Or (x, y)) minterms let simplify = simplify_bexpr let strip_all_casts = strip_all_casts_bexpr let fold = fold_bexpr_only let deep_fold = fold_bexpr end let dk_get_defs defkind = match defkind with | Assign (lhs, _) -> AP.Set.singleton (Variable lhs) | Store (lhs, _) -> AP.Set.singleton lhs | Call (Some lhs, _, _) -> AP.Set.singleton (Variable lhs) | Call (None, _, _) -> AP.Set.empty | Assume expr -> Bexpr.get_uses expr | Assert (expr, _) -> Bexpr.get_uses expr | AssertMemSafe (expr, _) -> Aexpr.get_uses expr | Initial -> AP.Set.empty | Return _ -> AP.Set.empty | Builtin (Alloc (lhs, _, _)) -> AP.Set.singleton (Variable lhs) | Builtin (Fork (Some lhs, _, _)) -> AP.Set.singleton (Variable lhs) | Builtin (Fork (None, _, _)) -> AP.Set.empty | Builtin (Free _) -> AP.Set.empty | Builtin (Acquire _) | Builtin (Release _) -> AP.Set.empty | Builtin AtomicBegin | Builtin AtomicEnd -> AP.Set.empty | Builtin Exit -> AP.Set.empty let dk_assigned_var = function | Assign (v, _) | Store (Variable v, _) | Call (Some v, _, _) | Builtin (Alloc (v, _, _)) | Builtin (Fork (Some v, _, _)) -> Some v | Store _ | Assume _ | Assert _ | Initial | Return _ | Call (_, _, _) | AssertMemSafe _ | Builtin (Free _) | Builtin (Fork (None, _, _)) | Builtin (Acquire _) | Builtin (Release _) | Builtin AtomicBegin | Builtin AtomicEnd | Builtin Exit -> None let lhs_accessed = function | Variable _ -> AP.Set.empty | Deref aexpr -> Aexpr.accessed aexpr let dk_get_accessed = function | Assign (_, rhs) -> Aexpr.accessed rhs | Store (ap, rhs) -> AP.Set.union (lhs_accessed ap) (Aexpr.accessed rhs) | Call (_, callee, args) | Builtin (Fork (_, callee, args)) -> let f rest expr = AP.Set.union (Aexpr.accessed expr) rest in List.fold_left f (Aexpr.accessed callee) args | Assume bexpr | Assert (bexpr, _) -> Bexpr.accessed bexpr | AssertMemSafe (expr, _) -> Aexpr.accessed expr | Initial -> AP.Set.empty | Return (Some expr) -> Aexpr.accessed expr | Return None -> AP.Set.empty | Builtin (Alloc (_, expr, _)) -> Aexpr.accessed expr | Builtin (Free expr) -> Aexpr.accessed expr | Builtin (Acquire expr) | Builtin (Release expr) -> Aexpr.accessed expr | Builtin AtomicBegin | Builtin AtomicEnd -> AP.Set.empty | Builtin Exit -> AP.Set.empty let lhs_free_vars = function | Variable v -> Var.Set.singleton v | ap -> AP.free_vars ap let dk_free_vars = function | Assign (var, rhs) -> Var.Set.add var (Aexpr.free_vars rhs) | Store (ap, rhs) -> Var.Set.union (lhs_free_vars ap) (Aexpr.free_vars rhs) | Call (lhs, callee, args) -> let f rest exp = Var.Set.union (Aexpr.free_vars exp) rest in let accessed = List.fold_left f (Aexpr.free_vars callee) args in begin match lhs with | Some v -> Var.Set.add v accessed | None -> accessed end | Assume bexpr | Assert (bexpr, _) -> Bexpr.free_vars bexpr | AssertMemSafe (expr, _) -> Aexpr.free_vars expr | Initial -> Var.Set.empty | Return (Some expr) -> Aexpr.free_vars expr | Return None -> Var.Set.empty | Builtin (Alloc (lhs, expr, _)) -> Var.Set.add lhs (Aexpr.free_vars expr) | Builtin (Fork (Some lhs, _, _)) -> Var.Set.singleton lhs | Builtin (Fork (None, _, _)) -> Var.Set.empty | Builtin (Free expr) -> Aexpr.free_vars expr | Builtin (Acquire expr) | Builtin (Release expr) -> Aexpr.free_vars expr | Builtin AtomicBegin | Builtin AtomicEnd -> Var.Set.empty | Builtin Exit -> Var.Set.empty let exprlist_uses = let f l e = AP.Set.union (Aexpr.get_uses e) l in List.fold_left f AP.Set.empty let dk_get_uses = function | Assign (_, expr) -> Aexpr.get_uses expr | Store (_, expr) -> Aexpr.get_uses expr | Call (_, func, args) -> exprlist_uses (func::args) | Assume expr -> Bexpr.get_uses expr | Initial -> AP.Set.empty | Assert (expr, _) -> Bexpr.get_uses expr | AssertMemSafe (expr, _) -> Aexpr.get_uses expr | Return None -> AP.Set.empty | Return (Some expr) -> Aexpr.get_uses expr | Builtin (Alloc (_, expr, _)) -> Aexpr.get_uses expr | Builtin (Free expr) -> Aexpr.get_uses expr | Builtin (Fork (_, func, args)) -> exprlist_uses (func::args) | Builtin (Acquire expr) -> Aexpr.get_uses expr | Builtin (Release expr) -> Aexpr.get_uses expr | Builtin AtomicBegin | Builtin AtomicEnd -> AP.Set.empty | Builtin Exit -> AP.Set.empty module Def = struct include Putil.MakeCoreType(struct type t = def [@@deriving show,ord] let hash x = Hashtbl.hash x.did end) let def_max_id = ref 0 let def_increase_id () = def_max_id := !(def_max_id) + 1; !def_max_id;; let location_map = Hashtbl.create 991 let mk ?(loc=Cil.locUnknown) dk = let id = def_increase_id () in Hashtbl.add location_map id loc; { did = id; dkind = dk } let get_location def = try Hashtbl.find location_map def.did with Not_found -> Cil.locUnknown let clone def = mk ~loc:(get_location def) def.dkind let initial = mk Initial let get_defs def = dk_get_defs def.dkind let get_uses def = dk_get_uses def.dkind let get_accessed def = dk_get_accessed def.dkind let free_vars def = dk_free_vars def.dkind let assigned_var def = dk_assigned_var def.dkind end let pp_var = Var.pp let show_var = Var.show let show_ap = AP.show
45cd5c5a9b8465e169b70588bebe865cf864397e407c6bc5e8e9b2a1d5881cb7
manuel-serrano/hop
js_parser.scm
;*=====================================================================*/ * Author : * / * Copyright : 2007 - 16 , see LICENSE file * / ;* ------------------------------------------------------------- */ * This file is part of Scheme2Js . * / ;* */ * Scheme2Js 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 */ ;* LICENSE file for more details. */ ;*=====================================================================*/ (module js-parser (import js-nodes js-lexer) (export (parse::JsNode port::input-port next-pragma::procedure))) (define (my-error ip msg obj token) (let ((l (read-line ip))) (let loop ((msg msg) (obj obj) (token token)) (cond ((not token) (error "parser" msg (format "~a \"~a\"" obj l))) ((epair? token) (match-case (cer token) ((at ?fname ?loc) (error/location "parser" msg (format "~a \"~a\"" obj l) fname loc)) (else (loop msg obj #f)))) (else (loop msg obj #f)))))) (define (parse input-port next-pragma!) ;; fun-body at bottom of file (define *peeked-tokens* '()) (define *previous-token-type* #unspecified) ;; including new-line (define (read-regexp intro-token) (let ((token (read/rp *Reg-exp-grammar* input-port))) (if (eq? (car token) 'EOF) (my-error input-port "unfinished regular expression literal" #f token)) (if (eq? (car token) 'ERROR) (my-error input-port "bad regular-expression literal" (cdr token) token)) (string-append (symbol->string intro-token) (cdr token)))) (define (peek-token) (if (null? *peeked-tokens*) (begin (set! *peeked-tokens* (list (read/rp *JS-grammar* input-port))) ;(tprint (car *peeked-tokens*)) (if (eq? (caar *peeked-tokens*) 'NEW_LINE) (begin (set! *previous-token-type* 'NEW_LINE) (set! *peeked-tokens* (cdr *peeked-tokens*)) (peek-token)) (car *peeked-tokens*))) (car *peeked-tokens*))) (define (token-push-back! token) (set! *peeked-tokens* (cons token *peeked-tokens*))) (define (peek-token-type) (car (peek-token))) (define (at-new-line-token?) (eq? *previous-token-type* 'NEW_LINE)) (define (consume! type) (let ((token (consume-any!))) (if (eq? (car token) type) (cdr token) (my-error input-port (format "unexpected token. expected ~a got: " type) (car token) token)))) (define (consume-statement-semicolon!) (cond ((eq? (peek-token-type) 'SEMICOLON) (consume-any!)) ((or (eq? (peek-token-type) 'RBRACE) (at-new-line-token?) (eq? (peek-token-type) 'EOF)) 'do-nothing) (else (my-error input-port "unexpected token: " (peek-token) (peek-token))))) (define (consume-any!) (let ((res (peek-token))) (set! *previous-token-type* (car res)) (set! *peeked-tokens* (cdr *peeked-tokens*)) (peek-token) ;; prepare new token. res)) (define (eof?) (eq? (peek-token-type) 'EOF)) (define (program) (instantiate::JsProgram (body (source-elements)))) (define (source-elements) (let loop ((rev-ses '())) (if (eof?) (instantiate::JsBlock (stmts (reverse! rev-ses))) (loop (cons (source-element) rev-ses))))) (define (source-element) (case (peek-token-type) ((function) (function-declaration)) ((ERROR EOF) (let ((t (consume-any!))) (my-error input-port "eof or error" t t))) (else (statement)))) (define (statement) (case (peek-token-type) ((LBRACE) (block)) ((var) (var-decl-list #f)) ((SEMICOLON) (empty-statement)) ((if) (iff)) ((for while do) (iteration)) ((continue) (continue)) ((break) (break)) ((return) (return)) ((with) (with)) ((switch) (switch)) ((throw) (throw)) ((try) (trie)) ((ID) (labeled-or-expr)) ;; errors will be handled in the expr-clause. (else (expression-statement)))) (define (block) (consume! 'LBRACE) (let loop ((rev-stats '())) (case (peek-token-type) ((RBRACE) (consume-any!) (instantiate::JsBlock (stmts (reverse! rev-stats)))) ;; errors will be handled in the statemente-clause (else (loop (cons (statement) rev-stats)))))) (define (var-decl-list in-for-init?) (consume! 'var) (let loop ((rev-vars (list (var in-for-init?)))) (case (peek-token-type) ((SEMICOLON) (if (not in-for-init?) (consume-any!)) (instantiate::JsVar-Decl-List (vars (reverse! rev-vars)))) ((COMMA) (consume-any!) (loop (cons (var in-for-init?) rev-vars))) ((in) (cond ((not in-for-init?) (my-error input-port "unexpected token" "in" (peek-token))) (else (instantiate::JsVar-Decl-List (vars rev-vars))))) (else (if (and (not in-for-init?) (or (at-new-line-token?) (eq? (peek-token-type) 'EOF))) (instantiate::JsVar-Decl-List (vars (reverse! rev-vars))) (let ((t (consume-any!))) (my-error input-port "unexpected token, error or EOF" (cdr t) t))))))) (define (var in-for-init?) (let ((id (consume! 'ID))) (case (peek-token-type) ((=) (consume-any!) (let ((expr (assig-expr in-for-init?))) (instantiate::JsInit (lhs (instantiate::JsDecl (id id))) (rhs expr)))) (else (instantiate::JsDecl (id id)))))) (define (empty-statement) (consume! 'SEMICOLON) (instantiate::JsNOP)) (define (iff) (consume-any!) ;; the 'if' (consume! 'LPAREN) (let ((test (expression #f))) (consume! 'RPAREN) (let ((then (statement))) (case (peek-token-type) ((else) (consume-any!) (let ((else (statement))) (instantiate::JsIf (test test) (then then) (else else)))) (else (instantiate::JsIf (test test) (then then) (else (instantiate::JsNOP)))))))) (define (iteration) (case (peek-token-type) ((for) (for)) ((while) (while)) ((do) (do-while)))) (define (for) (define (init-first-part) (case (peek-token-type) ((var) (var-decl-list #t)) ((SEMICOLON) #f) (else (expression #t)))) (consume! 'for) (consume! 'LPAREN) (let ((first-part (init-first-part))) (case (peek-token-type) ((SEMICOLON) (for-init/test/incr first-part)) ((in) (for-in first-part))))) ;; for (init; test; incr) (define (for-init/test/incr init) (consume! 'SEMICOLON) (let ((test (case (peek-token-type) ((SEMICOLON) #f) (else (expression #f))))) (consume! 'SEMICOLON) (let ((incr (case (peek-token-type) ((RPAREN) #f) (else (expression #f))))) (consume! 'RPAREN) (let* ((body (statement))) (instantiate::JsFor (init init) (test test) (incr incr) (body body)))))) for ( lhs / var x in obj ) (define (for-in lhs) TODO : weed out bad lhs (consume! 'in) (let ((error-token (peek-token)) (obj (expression #f)) (ignore-RPAREN (consume! 'RPAREN)) (body (statement))) (cond ((isa? lhs JsVar-Decl-List) (let ((lhs-vars (with-access::JsVar-Decl-List lhs (vars) vars))) (unless (null? (cdr lhs-vars)) (my-error input-port "Only one variable allowed in 'for ... in' loop" (with-access::JsRef (cadr lhs-vars) (id) id) error-token)) (instantiate::JsFor-In (lhs lhs) (obj obj) (body body)))) ((or (isa? lhs JsSequence) (isa? lhs JsAssig) (isa? lhs JsBinary) (isa? lhs JsUnary) (isa? lhs JsPostfix)) (my-error input-port "Bad left-hand side in 'for ... in' loop construct" (class-name (object-class lhs)) error-token)) (else (instantiate::JsFor-In (lhs lhs) (obj obj) (body body)))))) (define (while) (consume! 'while) (consume! 'LPAREN) (let ((test (expression #f))) (consume! 'RPAREN) (let ((body (statement))) (instantiate::JsWhile (test test) (body body))))) (define (do-while) (consume! 'do) (let ((body (statement))) (consume! 'while) (consume! 'LPAREN) (let ((test (expression #f))) (consume! 'RPAREN) (consume-statement-semicolon!) (instantiate::JsDo (body body) (test test))))) (define (continue) (consume! 'continue) (if (and (eq? (peek-token-type) 'ID) (not (at-new-line-token?))) (let ((id (consume! 'ID))) (consume-statement-semicolon!) (instantiate::JsContinue (id id))) (begin (consume-statement-semicolon!) (instantiate::JsContinue (id #f))))) (define (break) (consume! 'break) (if (and (eq? (peek-token-type) 'ID) (not (at-new-line-token?))) (let ((id (consume! 'ID))) (consume-statement-semicolon!) (instantiate::JsBreak (id id))) (begin (consume-statement-semicolon!) (instantiate::JsBreak (id #f))))) (define (return) (consume! 'return) (if (or (case (peek-token-type) ((EOF ERROR SEMICOLON) #t) (else #f)) (at-new-line-token?)) (begin (consume-statement-semicolon!) (instantiate::JsReturn (val #f))) (let ((expr (expression #f))) (consume-statement-semicolon!) (instantiate::JsReturn (val expr))))) (define (with) (consume! 'with) (consume! 'LPAREN) (let ((expr (expression #f))) (consume! 'RPAREN) (let ((body (statement))) (instantiate::JsWith (obj expr) (body body))))) (define (switch) (consume! 'switch) (consume! 'LPAREN) (let ((key (expression #f))) (consume! 'RPAREN) (let ((cases (case-block))) (instantiate::JsSwitch (key key) (cases cases))))) (define (case-block) (consume! 'LBRACE) (let loop ((rev-cases '()) (default-case-done? #f)) (case (peek-token-type) ((RBRACE) (consume-any!) (reverse! rev-cases)) ((case) (loop (cons (case-clause) rev-cases) default-case-done?)) ((default) (if default-case-done? (error "Only one default-clause allowed" (peek-token) (peek-token)) (loop (cons (default-clause) rev-cases) #t)))))) (define (case-clause) (consume! 'case) (let ((expr (expression #f))) (consume! ':) (let ((body (switch-clause-statements))) (instantiate::JsCase (expr expr) (body body))))) (define (default-clause) (consume! 'default) (consume! ':) (instantiate::JsDefault (body (switch-clause-statements)))) (define (switch-clause-statements) (let loop ((rev-stats '())) (case (peek-token-type) ((RBRACE EOF ERROR default case) (instantiate::JsBlock (stmts (reverse! rev-stats)))) (else (loop (cons (statement) rev-stats)))))) (define (throw) (consume! 'throw) (when (at-new-line-token?) (error "throw must have a value" #f (peek-token))) (let ((expr (expression #f))) (consume-statement-semicolon!) (instantiate::JsThrow (expr expr)))) (define (trie) (consume! 'try) (let ((body (block))) (let ((catch-part #f) (finally-part #f)) (if (eq? (peek-token-type) 'catch) (set! catch-part (catch))) (if (eq? (peek-token-type) 'finally) (set! finally-part (finally))) (instantiate::JsTry (body body) (catch catch-part) (finally finally-part))))) (define (catch) (consume! 'catch) (consume! 'LPAREN) (let ((id (consume! 'ID))) (consume! 'RPAREN) (let ((body (block))) not sure , if ' ' is a really good choice . ;; we'll see... (instantiate::JsCatch (exception (instantiate::JsParam (id id))) (body body))))) (define (finally) (consume! 'finally) (block)) (define (labeled-or-expr) (let* ((id-token (consume-any!)) (next-token-type (peek-token-type))) [assert (id-token) (eq? (car id-token) 'ID)] (token-push-back! id-token) (if (eq? next-token-type ':) (labeled) (expression-statement)))) (define (expression-statement) (let ((expr (expression #f))) (consume-statement-semicolon!) expr)) (define (labeled) (let ((id (consume! 'ID))) (consume! ':) (instantiate::JsLabeled (id id) (body (statement))))) (define (function-declaration) (function #t)) (define (function-expression) (function #f)) (define (function declaration?) (consume! 'function) (let* ((id (if (or declaration? (eq? (peek-token-type) 'ID)) (consume! 'ID) #f)) (params (params)) (body (fun-body))) (if declaration? (instantiate::JsFun-Binding (lhs (instantiate::JsDecl (id id))) (rhs (instantiate::JsFun (params params) (body body)))) (if id (instantiate::JsNamed-Fun (name (instantiate::JsDecl (id id))) (fun (instantiate::JsFun (params params) (body body)))) (instantiate::JsFun (params params) (body body)))))) (define (params) (consume! 'LPAREN) (if (eq? (peek-token-type) 'RPAREN) (begin (consume-any!) '()) (let loop ((rev-params (list (instantiate::JsParam (id (consume! 'ID)))))) (if (eq? (peek-token-type) 'COMMA) (begin (consume-any!) (loop (cons (instantiate::JsParam (id (consume! 'ID))) rev-params))) (begin (consume! 'RPAREN) (reverse! rev-params)))))) (define (fun-body) (consume! 'LBRACE) (let loop ((rev-ses '())) (if (eq? (peek-token-type) 'RBRACE) (begin (consume-any!) (instantiate::JsBlock (stmts (reverse! rev-ses)))) (loop (cons (source-element) rev-ses))))) (define (expression in-for-init?) (let ((assig (assig-expr in-for-init?))) (let loop ((rev-exprs (list assig))) (if (eq? (peek-token-type) 'COMMA) (begin (consume-any!) (loop (cons (assig-expr in-for-init?) rev-exprs))) (if (null? (cdr rev-exprs)) (car rev-exprs) (instantiate::JsSequence (exprs (reverse! rev-exprs)))))))) (define (assig-operator? x) (case x ((= *= /= %= += -= <<= >>= >>>= &= ^= BIT_OR=) #t) (else #f))) (define (assig-expr in-for-init?) (define (with-out-= op=) (let* ((s= (symbol->string op=)) (s=-length (string-length s=)) (s (substring s= 0 (- s=-length 1))) (op (string->symbol s))) op)) (let ((expr (cond-expr in-for-init?))) (if (assig-operator? (peek-token-type)) (let* ((op (car (consume-any!))) ;; ops are in car (rhs (assig-expr in-for-init?))) TODO : weed out bad lhs exprs (cond ((and (eq? op '=) (isa? expr JsAccess)) (instantiate::JsAccsig (lhs expr) (rhs rhs))) ((eq? op '=) (instantiate::JsVassig (lhs expr) (rhs rhs))) ((isa? expr JsAccess) (instantiate::JsAccsig-op (lhs expr) (op (with-out-= op)) (rhs rhs))) (else (instantiate::JsVassig-op (lhs expr) (op (with-out-= op)) (rhs rhs))))) expr))) (define (cond-expr in-for-init?) (let ((expr (binary-expr in-for-init?))) (if (eq? (peek-token-type) '?) (let* ((ignore-? (consume-any!)) (then (assig-expr #f)) (ignore-colon (consume! ':)) (else (assig-expr in-for-init?))) (instantiate::JsCond (test expr) (then then) (else else))) expr))) (define (op-level op) (case op ((OR) 1) ((&&) 2) ((BIT_OR) 3) ((^) 4) ((&) 5) ((== != === !==) 6) ((< > <= >= instanceof in) 7) ((<< >> >>>) 8) ((+ -) 9) ((* / %) 10) (else #f))) ;; left-associative binary expressions (define (binary-expr in-for-init?) (define (binary-aux level) (if (> level 10) (unary) (let loop ((expr (binary-aux (+fx level 1)))) (let* ((type (peek-token-type)) (new-level (op-level type))) (cond ((and in-for-init? (eq? type 'in)) expr) ((not new-level) expr) ((=fx new-level level) ;; ops are in car (let ((token-op (car (consume-any!)))) (loop (instantiate::JsBinary (lhs expr) (op token-op) (rhs (binary-aux (+fx level 1))))))) (else expr)))))) (binary-aux 1)) (define (unary) (case (peek-token-type) ((delete void typeof ~ ! ++ -- + -) (instantiate::JsUnary (op (car (consume-any!))) (expr (unary)))) (else (postfix)))) (define (postfix) (let ((expr (lhs))) (if (not (at-new-line-token?)) (case (peek-token-type) ((++ --) (let ((op (car (consume-any!)))) (instantiate::JsPostfix (expr expr) (op op)))) (else expr)) expr))) ;; we start by getting all news (new-expr) ;; the remaining access and calls are then caught by the access-or-call ;; invocation allowing call-parenthesis. ;; ;; the access-or-call in new-expr does not all any parenthesis to be ;; consumed as they would be part of the new-expr. (define (lhs) (access-or-call (new-expr) #t)) (define (new-expr) (if (eq? (peek-token-type) 'new) (let* ((ignore (consume-any!)) (class (new-expr)) (args (if (eq? (peek-token-type) 'LPAREN) (arguments) '()))) (instantiate::JsNew (class class) (args args))) (access-or-call (primary) #f))) (define (access-or-call expr call-allowed?) (let loop ((expr expr)) (case (peek-token-type) ((LBRACKET) (let* ((ignore (consume-any!)) (field (expression #f)) (ignore-too (consume! 'RBRACKET))) (loop (instantiate::JsAccess (obj expr) (field field))))) ((DOT) (let* ((ignore (consume-any!)) (field (consume! 'ID)) (field-str (format "'~a'" field))) (loop (instantiate::JsAccess (obj expr) (field (instantiate::JsString (val field-str))))))) ((LPAREN) (if call-allowed? (loop (instantiate::JsCall (fun expr) (args (arguments)))) expr)) (else expr)))) (define (arguments) (consume! 'LPAREN) (if (eq? (peek-token-type) 'RPAREN) (begin (consume-any!) '()) (let loop ((rev-args (list (assig-expr #f)))) (if (eq? (peek-token-type) 'RPAREN) (begin (consume-any!) (reverse! rev-args)) (let* ((ignore (consume! 'COMMA)) (arg (assig-expr #f))) (loop (cons arg rev-args))))))) (define (primary) (case (peek-token-type) ((PRAGMA) (js-pragma)) ((function) (function-expression)) ((this) (consume-any!) (instantiate::JsThis)) ((ID) (instantiate::JsRef (id (consume! 'ID)))) ((LPAREN) (let ((ignore (consume-any!)) (expr (expression #f)) (ignore-too (consume! 'RPAREN))) expr)) ((LBRACKET) (array-literal)) ((LBRACE) (object-literal)) ((null) (consume-any!) (instantiate::JsNull (val 'null))) ((true false) (instantiate::JsBool (val (eq? (car (consume-any!)) 'true)))) ((NUMBER) (instantiate::JsNumber (val (consume! 'NUMBER)))) ;; still as string! ((STRING) (instantiate::JsString (val (consume! 'STRING)))) ((EOF) (my-error input-port "unexpected end of file" #f (peek-token))) ((/ /=) (let ((pattern (read-regexp (peek-token-type)))) ;; consume-any *must* be after having read the reg-exp, ;; so that the read-regexp works. Only then can we remove ;; the peeked token. (consume-any!) ;; the / or /= (instantiate::JsRegExp (pattern pattern)))) (else (let ((t (peek-token))) (my-error input-port "unexpected token: " t t))))) (define (js-pragma) (consume! 'PRAGMA) (let ((prag (next-pragma!))) (tprint "PRAG=" prag) (instantiate::JsPragma (str prag) (args '())))) (define (array-literal) (consume! 'LBRACKET) (let loop ((rev-els '()) (length 0)) (case (peek-token-type) ((RBRACKET) (consume-any!) (instantiate::JsArray (els (reverse! rev-els)) (len length))) ((COMMA) (consume-any!) (loop rev-els (+fx length 1))) (else (let ((array-el (instantiate::JsArray-Element (index length) (expr (assig-expr #f))))) (if (eq? (peek-token-type) 'COMMA) (begin (consume-any!) (loop (cons array-el rev-els) (+fx length 1))) (begin (consume! 'RBRACKET) (instantiate::JsArray (els (reverse! (cons array-el rev-els))) (len (+fx length 1)))))))))) (define (object-literal) (define (property-name) (case (peek-token-type) ;; IDs are automatically transformed to strings. ((ID) (instantiate::JsString (val (string-append "\"" (symbol->string (consume! 'ID)) "\"")))) ((STRING) (instantiate::JsString (val (consume! 'STRING)))) ((NUMBER) (instantiate::JsNumber (val (consume! 'NUMBER)))))) (define (property-init) (let* ((name (property-name)) (ignore (consume! ':)) (val (assig-expr #f))) (instantiate::JsProperty-Init (name name) (val val)))) (consume! 'LBRACE) (if (eq? (peek-token-type) 'RBRACE) (begin (consume-any!) (instantiate::JsObj-Init (inits '()))) (let loop ((rev-props (list (property-init)))) (if (eq? (peek-token-type) 'RBRACE) (begin (consume-any!) (instantiate::JsObj-Init (inits (reverse! rev-props)))) (begin (consume! 'COMMA) (loop (cons (property-init) rev-props))))))) ;; procedure entry point. ;; ---------------------- (program))
null
https://raw.githubusercontent.com/manuel-serrano/hop/481cb10478286796addd2ec9ee29c95db27aa390/scheme2js/js_parser.scm
scheme
*=====================================================================*/ * ------------------------------------------------------------- */ * */ * but WITHOUT ANY WARRANTY; without even the implied warranty of */ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */ * LICENSE file for more details. */ *=====================================================================*/ fun-body at bottom of file including new-line (tprint (car *peeked-tokens*)) prepare new token. errors will be handled in the expr-clause. errors will be handled in the statemente-clause the 'if' for (init; test; incr) we'll see... ops are in car left-associative binary expressions ops are in car we start by getting all news (new-expr) the remaining access and calls are then caught by the access-or-call invocation allowing call-parenthesis. the access-or-call in new-expr does not all any parenthesis to be consumed as they would be part of the new-expr. still as string! consume-any *must* be after having read the reg-exp, so that the read-regexp works. Only then can we remove the peeked token. the / or /= IDs are automatically transformed to strings. procedure entry point. ----------------------
* Author : * / * Copyright : 2007 - 16 , see LICENSE file * / * This file is part of Scheme2Js . * / * Scheme2Js is distributed in the hope that it will be useful , * / (module js-parser (import js-nodes js-lexer) (export (parse::JsNode port::input-port next-pragma::procedure))) (define (my-error ip msg obj token) (let ((l (read-line ip))) (let loop ((msg msg) (obj obj) (token token)) (cond ((not token) (error "parser" msg (format "~a \"~a\"" obj l))) ((epair? token) (match-case (cer token) ((at ?fname ?loc) (error/location "parser" msg (format "~a \"~a\"" obj l) fname loc)) (else (loop msg obj #f)))) (else (loop msg obj #f)))))) (define (parse input-port next-pragma!) (define *peeked-tokens* '()) (define (read-regexp intro-token) (let ((token (read/rp *Reg-exp-grammar* input-port))) (if (eq? (car token) 'EOF) (my-error input-port "unfinished regular expression literal" #f token)) (if (eq? (car token) 'ERROR) (my-error input-port "bad regular-expression literal" (cdr token) token)) (string-append (symbol->string intro-token) (cdr token)))) (define (peek-token) (if (null? *peeked-tokens*) (begin (set! *peeked-tokens* (list (read/rp *JS-grammar* input-port))) (if (eq? (caar *peeked-tokens*) 'NEW_LINE) (begin (set! *previous-token-type* 'NEW_LINE) (set! *peeked-tokens* (cdr *peeked-tokens*)) (peek-token)) (car *peeked-tokens*))) (car *peeked-tokens*))) (define (token-push-back! token) (set! *peeked-tokens* (cons token *peeked-tokens*))) (define (peek-token-type) (car (peek-token))) (define (at-new-line-token?) (eq? *previous-token-type* 'NEW_LINE)) (define (consume! type) (let ((token (consume-any!))) (if (eq? (car token) type) (cdr token) (my-error input-port (format "unexpected token. expected ~a got: " type) (car token) token)))) (define (consume-statement-semicolon!) (cond ((eq? (peek-token-type) 'SEMICOLON) (consume-any!)) ((or (eq? (peek-token-type) 'RBRACE) (at-new-line-token?) (eq? (peek-token-type) 'EOF)) 'do-nothing) (else (my-error input-port "unexpected token: " (peek-token) (peek-token))))) (define (consume-any!) (let ((res (peek-token))) (set! *previous-token-type* (car res)) (set! *peeked-tokens* (cdr *peeked-tokens*)) res)) (define (eof?) (eq? (peek-token-type) 'EOF)) (define (program) (instantiate::JsProgram (body (source-elements)))) (define (source-elements) (let loop ((rev-ses '())) (if (eof?) (instantiate::JsBlock (stmts (reverse! rev-ses))) (loop (cons (source-element) rev-ses))))) (define (source-element) (case (peek-token-type) ((function) (function-declaration)) ((ERROR EOF) (let ((t (consume-any!))) (my-error input-port "eof or error" t t))) (else (statement)))) (define (statement) (case (peek-token-type) ((LBRACE) (block)) ((var) (var-decl-list #f)) ((SEMICOLON) (empty-statement)) ((if) (iff)) ((for while do) (iteration)) ((continue) (continue)) ((break) (break)) ((return) (return)) ((with) (with)) ((switch) (switch)) ((throw) (throw)) ((try) (trie)) ((ID) (labeled-or-expr)) (else (expression-statement)))) (define (block) (consume! 'LBRACE) (let loop ((rev-stats '())) (case (peek-token-type) ((RBRACE) (consume-any!) (instantiate::JsBlock (stmts (reverse! rev-stats)))) (else (loop (cons (statement) rev-stats)))))) (define (var-decl-list in-for-init?) (consume! 'var) (let loop ((rev-vars (list (var in-for-init?)))) (case (peek-token-type) ((SEMICOLON) (if (not in-for-init?) (consume-any!)) (instantiate::JsVar-Decl-List (vars (reverse! rev-vars)))) ((COMMA) (consume-any!) (loop (cons (var in-for-init?) rev-vars))) ((in) (cond ((not in-for-init?) (my-error input-port "unexpected token" "in" (peek-token))) (else (instantiate::JsVar-Decl-List (vars rev-vars))))) (else (if (and (not in-for-init?) (or (at-new-line-token?) (eq? (peek-token-type) 'EOF))) (instantiate::JsVar-Decl-List (vars (reverse! rev-vars))) (let ((t (consume-any!))) (my-error input-port "unexpected token, error or EOF" (cdr t) t))))))) (define (var in-for-init?) (let ((id (consume! 'ID))) (case (peek-token-type) ((=) (consume-any!) (let ((expr (assig-expr in-for-init?))) (instantiate::JsInit (lhs (instantiate::JsDecl (id id))) (rhs expr)))) (else (instantiate::JsDecl (id id)))))) (define (empty-statement) (consume! 'SEMICOLON) (instantiate::JsNOP)) (define (iff) (consume! 'LPAREN) (let ((test (expression #f))) (consume! 'RPAREN) (let ((then (statement))) (case (peek-token-type) ((else) (consume-any!) (let ((else (statement))) (instantiate::JsIf (test test) (then then) (else else)))) (else (instantiate::JsIf (test test) (then then) (else (instantiate::JsNOP)))))))) (define (iteration) (case (peek-token-type) ((for) (for)) ((while) (while)) ((do) (do-while)))) (define (for) (define (init-first-part) (case (peek-token-type) ((var) (var-decl-list #t)) ((SEMICOLON) #f) (else (expression #t)))) (consume! 'for) (consume! 'LPAREN) (let ((first-part (init-first-part))) (case (peek-token-type) ((SEMICOLON) (for-init/test/incr first-part)) ((in) (for-in first-part))))) (define (for-init/test/incr init) (consume! 'SEMICOLON) (let ((test (case (peek-token-type) ((SEMICOLON) #f) (else (expression #f))))) (consume! 'SEMICOLON) (let ((incr (case (peek-token-type) ((RPAREN) #f) (else (expression #f))))) (consume! 'RPAREN) (let* ((body (statement))) (instantiate::JsFor (init init) (test test) (incr incr) (body body)))))) for ( lhs / var x in obj ) (define (for-in lhs) TODO : weed out bad lhs (consume! 'in) (let ((error-token (peek-token)) (obj (expression #f)) (ignore-RPAREN (consume! 'RPAREN)) (body (statement))) (cond ((isa? lhs JsVar-Decl-List) (let ((lhs-vars (with-access::JsVar-Decl-List lhs (vars) vars))) (unless (null? (cdr lhs-vars)) (my-error input-port "Only one variable allowed in 'for ... in' loop" (with-access::JsRef (cadr lhs-vars) (id) id) error-token)) (instantiate::JsFor-In (lhs lhs) (obj obj) (body body)))) ((or (isa? lhs JsSequence) (isa? lhs JsAssig) (isa? lhs JsBinary) (isa? lhs JsUnary) (isa? lhs JsPostfix)) (my-error input-port "Bad left-hand side in 'for ... in' loop construct" (class-name (object-class lhs)) error-token)) (else (instantiate::JsFor-In (lhs lhs) (obj obj) (body body)))))) (define (while) (consume! 'while) (consume! 'LPAREN) (let ((test (expression #f))) (consume! 'RPAREN) (let ((body (statement))) (instantiate::JsWhile (test test) (body body))))) (define (do-while) (consume! 'do) (let ((body (statement))) (consume! 'while) (consume! 'LPAREN) (let ((test (expression #f))) (consume! 'RPAREN) (consume-statement-semicolon!) (instantiate::JsDo (body body) (test test))))) (define (continue) (consume! 'continue) (if (and (eq? (peek-token-type) 'ID) (not (at-new-line-token?))) (let ((id (consume! 'ID))) (consume-statement-semicolon!) (instantiate::JsContinue (id id))) (begin (consume-statement-semicolon!) (instantiate::JsContinue (id #f))))) (define (break) (consume! 'break) (if (and (eq? (peek-token-type) 'ID) (not (at-new-line-token?))) (let ((id (consume! 'ID))) (consume-statement-semicolon!) (instantiate::JsBreak (id id))) (begin (consume-statement-semicolon!) (instantiate::JsBreak (id #f))))) (define (return) (consume! 'return) (if (or (case (peek-token-type) ((EOF ERROR SEMICOLON) #t) (else #f)) (at-new-line-token?)) (begin (consume-statement-semicolon!) (instantiate::JsReturn (val #f))) (let ((expr (expression #f))) (consume-statement-semicolon!) (instantiate::JsReturn (val expr))))) (define (with) (consume! 'with) (consume! 'LPAREN) (let ((expr (expression #f))) (consume! 'RPAREN) (let ((body (statement))) (instantiate::JsWith (obj expr) (body body))))) (define (switch) (consume! 'switch) (consume! 'LPAREN) (let ((key (expression #f))) (consume! 'RPAREN) (let ((cases (case-block))) (instantiate::JsSwitch (key key) (cases cases))))) (define (case-block) (consume! 'LBRACE) (let loop ((rev-cases '()) (default-case-done? #f)) (case (peek-token-type) ((RBRACE) (consume-any!) (reverse! rev-cases)) ((case) (loop (cons (case-clause) rev-cases) default-case-done?)) ((default) (if default-case-done? (error "Only one default-clause allowed" (peek-token) (peek-token)) (loop (cons (default-clause) rev-cases) #t)))))) (define (case-clause) (consume! 'case) (let ((expr (expression #f))) (consume! ':) (let ((body (switch-clause-statements))) (instantiate::JsCase (expr expr) (body body))))) (define (default-clause) (consume! 'default) (consume! ':) (instantiate::JsDefault (body (switch-clause-statements)))) (define (switch-clause-statements) (let loop ((rev-stats '())) (case (peek-token-type) ((RBRACE EOF ERROR default case) (instantiate::JsBlock (stmts (reverse! rev-stats)))) (else (loop (cons (statement) rev-stats)))))) (define (throw) (consume! 'throw) (when (at-new-line-token?) (error "throw must have a value" #f (peek-token))) (let ((expr (expression #f))) (consume-statement-semicolon!) (instantiate::JsThrow (expr expr)))) (define (trie) (consume! 'try) (let ((body (block))) (let ((catch-part #f) (finally-part #f)) (if (eq? (peek-token-type) 'catch) (set! catch-part (catch))) (if (eq? (peek-token-type) 'finally) (set! finally-part (finally))) (instantiate::JsTry (body body) (catch catch-part) (finally finally-part))))) (define (catch) (consume! 'catch) (consume! 'LPAREN) (let ((id (consume! 'ID))) (consume! 'RPAREN) (let ((body (block))) not sure , if ' ' is a really good choice . (instantiate::JsCatch (exception (instantiate::JsParam (id id))) (body body))))) (define (finally) (consume! 'finally) (block)) (define (labeled-or-expr) (let* ((id-token (consume-any!)) (next-token-type (peek-token-type))) [assert (id-token) (eq? (car id-token) 'ID)] (token-push-back! id-token) (if (eq? next-token-type ':) (labeled) (expression-statement)))) (define (expression-statement) (let ((expr (expression #f))) (consume-statement-semicolon!) expr)) (define (labeled) (let ((id (consume! 'ID))) (consume! ':) (instantiate::JsLabeled (id id) (body (statement))))) (define (function-declaration) (function #t)) (define (function-expression) (function #f)) (define (function declaration?) (consume! 'function) (let* ((id (if (or declaration? (eq? (peek-token-type) 'ID)) (consume! 'ID) #f)) (params (params)) (body (fun-body))) (if declaration? (instantiate::JsFun-Binding (lhs (instantiate::JsDecl (id id))) (rhs (instantiate::JsFun (params params) (body body)))) (if id (instantiate::JsNamed-Fun (name (instantiate::JsDecl (id id))) (fun (instantiate::JsFun (params params) (body body)))) (instantiate::JsFun (params params) (body body)))))) (define (params) (consume! 'LPAREN) (if (eq? (peek-token-type) 'RPAREN) (begin (consume-any!) '()) (let loop ((rev-params (list (instantiate::JsParam (id (consume! 'ID)))))) (if (eq? (peek-token-type) 'COMMA) (begin (consume-any!) (loop (cons (instantiate::JsParam (id (consume! 'ID))) rev-params))) (begin (consume! 'RPAREN) (reverse! rev-params)))))) (define (fun-body) (consume! 'LBRACE) (let loop ((rev-ses '())) (if (eq? (peek-token-type) 'RBRACE) (begin (consume-any!) (instantiate::JsBlock (stmts (reverse! rev-ses)))) (loop (cons (source-element) rev-ses))))) (define (expression in-for-init?) (let ((assig (assig-expr in-for-init?))) (let loop ((rev-exprs (list assig))) (if (eq? (peek-token-type) 'COMMA) (begin (consume-any!) (loop (cons (assig-expr in-for-init?) rev-exprs))) (if (null? (cdr rev-exprs)) (car rev-exprs) (instantiate::JsSequence (exprs (reverse! rev-exprs)))))))) (define (assig-operator? x) (case x ((= *= /= %= += -= <<= >>= >>>= &= ^= BIT_OR=) #t) (else #f))) (define (assig-expr in-for-init?) (define (with-out-= op=) (let* ((s= (symbol->string op=)) (s=-length (string-length s=)) (s (substring s= 0 (- s=-length 1))) (op (string->symbol s))) op)) (let ((expr (cond-expr in-for-init?))) (if (assig-operator? (peek-token-type)) (rhs (assig-expr in-for-init?))) TODO : weed out bad lhs exprs (cond ((and (eq? op '=) (isa? expr JsAccess)) (instantiate::JsAccsig (lhs expr) (rhs rhs))) ((eq? op '=) (instantiate::JsVassig (lhs expr) (rhs rhs))) ((isa? expr JsAccess) (instantiate::JsAccsig-op (lhs expr) (op (with-out-= op)) (rhs rhs))) (else (instantiate::JsVassig-op (lhs expr) (op (with-out-= op)) (rhs rhs))))) expr))) (define (cond-expr in-for-init?) (let ((expr (binary-expr in-for-init?))) (if (eq? (peek-token-type) '?) (let* ((ignore-? (consume-any!)) (then (assig-expr #f)) (ignore-colon (consume! ':)) (else (assig-expr in-for-init?))) (instantiate::JsCond (test expr) (then then) (else else))) expr))) (define (op-level op) (case op ((OR) 1) ((&&) 2) ((BIT_OR) 3) ((^) 4) ((&) 5) ((== != === !==) 6) ((< > <= >= instanceof in) 7) ((<< >> >>>) 8) ((+ -) 9) ((* / %) 10) (else #f))) (define (binary-expr in-for-init?) (define (binary-aux level) (if (> level 10) (unary) (let loop ((expr (binary-aux (+fx level 1)))) (let* ((type (peek-token-type)) (new-level (op-level type))) (cond ((and in-for-init? (eq? type 'in)) expr) ((not new-level) expr) ((=fx new-level level) (let ((token-op (car (consume-any!)))) (loop (instantiate::JsBinary (lhs expr) (op token-op) (rhs (binary-aux (+fx level 1))))))) (else expr)))))) (binary-aux 1)) (define (unary) (case (peek-token-type) ((delete void typeof ~ ! ++ -- + -) (instantiate::JsUnary (op (car (consume-any!))) (expr (unary)))) (else (postfix)))) (define (postfix) (let ((expr (lhs))) (if (not (at-new-line-token?)) (case (peek-token-type) ((++ --) (let ((op (car (consume-any!)))) (instantiate::JsPostfix (expr expr) (op op)))) (else expr)) expr))) (define (lhs) (access-or-call (new-expr) #t)) (define (new-expr) (if (eq? (peek-token-type) 'new) (let* ((ignore (consume-any!)) (class (new-expr)) (args (if (eq? (peek-token-type) 'LPAREN) (arguments) '()))) (instantiate::JsNew (class class) (args args))) (access-or-call (primary) #f))) (define (access-or-call expr call-allowed?) (let loop ((expr expr)) (case (peek-token-type) ((LBRACKET) (let* ((ignore (consume-any!)) (field (expression #f)) (ignore-too (consume! 'RBRACKET))) (loop (instantiate::JsAccess (obj expr) (field field))))) ((DOT) (let* ((ignore (consume-any!)) (field (consume! 'ID)) (field-str (format "'~a'" field))) (loop (instantiate::JsAccess (obj expr) (field (instantiate::JsString (val field-str))))))) ((LPAREN) (if call-allowed? (loop (instantiate::JsCall (fun expr) (args (arguments)))) expr)) (else expr)))) (define (arguments) (consume! 'LPAREN) (if (eq? (peek-token-type) 'RPAREN) (begin (consume-any!) '()) (let loop ((rev-args (list (assig-expr #f)))) (if (eq? (peek-token-type) 'RPAREN) (begin (consume-any!) (reverse! rev-args)) (let* ((ignore (consume! 'COMMA)) (arg (assig-expr #f))) (loop (cons arg rev-args))))))) (define (primary) (case (peek-token-type) ((PRAGMA) (js-pragma)) ((function) (function-expression)) ((this) (consume-any!) (instantiate::JsThis)) ((ID) (instantiate::JsRef (id (consume! 'ID)))) ((LPAREN) (let ((ignore (consume-any!)) (expr (expression #f)) (ignore-too (consume! 'RPAREN))) expr)) ((LBRACKET) (array-literal)) ((LBRACE) (object-literal)) ((null) (consume-any!) (instantiate::JsNull (val 'null))) ((true false) (instantiate::JsBool (val (eq? (car (consume-any!)) 'true)))) ((STRING) (instantiate::JsString (val (consume! 'STRING)))) ((EOF) (my-error input-port "unexpected end of file" #f (peek-token))) ((/ /=) (let ((pattern (read-regexp (peek-token-type)))) (instantiate::JsRegExp (pattern pattern)))) (else (let ((t (peek-token))) (my-error input-port "unexpected token: " t t))))) (define (js-pragma) (consume! 'PRAGMA) (let ((prag (next-pragma!))) (tprint "PRAG=" prag) (instantiate::JsPragma (str prag) (args '())))) (define (array-literal) (consume! 'LBRACKET) (let loop ((rev-els '()) (length 0)) (case (peek-token-type) ((RBRACKET) (consume-any!) (instantiate::JsArray (els (reverse! rev-els)) (len length))) ((COMMA) (consume-any!) (loop rev-els (+fx length 1))) (else (let ((array-el (instantiate::JsArray-Element (index length) (expr (assig-expr #f))))) (if (eq? (peek-token-type) 'COMMA) (begin (consume-any!) (loop (cons array-el rev-els) (+fx length 1))) (begin (consume! 'RBRACKET) (instantiate::JsArray (els (reverse! (cons array-el rev-els))) (len (+fx length 1)))))))))) (define (object-literal) (define (property-name) (case (peek-token-type) ((ID) (instantiate::JsString (val (string-append "\"" (symbol->string (consume! 'ID)) "\"")))) ((STRING) (instantiate::JsString (val (consume! 'STRING)))) ((NUMBER) (instantiate::JsNumber (val (consume! 'NUMBER)))))) (define (property-init) (let* ((name (property-name)) (ignore (consume! ':)) (val (assig-expr #f))) (instantiate::JsProperty-Init (name name) (val val)))) (consume! 'LBRACE) (if (eq? (peek-token-type) 'RBRACE) (begin (consume-any!) (instantiate::JsObj-Init (inits '()))) (let loop ((rev-props (list (property-init)))) (if (eq? (peek-token-type) 'RBRACE) (begin (consume-any!) (instantiate::JsObj-Init (inits (reverse! rev-props)))) (begin (consume! 'COMMA) (loop (cons (property-init) rev-props))))))) (program))
88b328f45f46ce0e58e9a261d6eb4e6302f8a592ede39d6df395004006a92542
scalaris-team/scalaris
prime.erl
2012 - 2014 Zuse Institute Berlin 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 % % -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. @author < > %% @doc prime number module %% implemented method: trail division %% @end @reference 2009 - < em > The Genuine Sieve of Eratosthenes < /em > Journal of Functional Programming 19(1 ) pp : 95 - 106 %% Implemented Method: Trial Division %% @version $Id$ -module(prime). -author(''). -vsn('$Id$'). -include("record_helpers.hrl"). -include("scalaris.hrl"). -export([get_nearest/1, is_prime/1]). % feeder for tester -export([is_prime_feeder/1, get_nearest_feeder/1]). -type prime() :: pos_integer(). % last prime in prime_cache/0 -define(PrimeCache, 5003). -define(TESTER_MAX_PRIME, 5250). -on_load(init/0). %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -spec init() -> ok | {error, term()}. init() -> %% loads the shared library SoName = case code:priv_dir(scalaris) of {error, bad_name} -> Dir1 = filename:join( [filename:dirname(code:where_is_file("scalaris.beam")), "..", priv]), case filelib:is_dir(Dir1) of true -> filename:join(Dir1, ?MODULE); _ -> filename:join(["..", priv, ?MODULE]) end; Dir -> filename:join(Dir, ?MODULE) end, % tolerate some errors trying to load the library: case erlang:load_nif(SoName, 0) of ok -> ok; {error, {load_failed, Text}} -> log:log(warn, "~s - falling back to the (considerably) slower Erlang native code", [Text]), ok; Error -> Error end. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -spec get_nearest_feeder(1..?TESTER_MAX_PRIME) -> {1..?TESTER_MAX_PRIME}. get_nearest_feeder(N) -> {N}. @doc Returns the first prime larger than or equal to N. -spec get_nearest(pos_integer()) -> prime(). get_nearest(N) when N > ?PrimeCache -> MaxN = if N >= 396738 -> for x > = 396738 there is at least one prime between x and ( 1 + 1/(25ln^2(x)))x Dusart , ( 2010 ) . " Estimates of Some Functions Over Primes without " . LogN = math:log(N), util:ceil((1 + 1 / (25 * LogN*LogN)) * N); N >= 25 -> x > = 25 , there is always a prime between n and ( 1 + 1/5)n Nagura , J. " On the interval containing at least one prime number . " Proceedings of the Japan Academy , Series A 28 ( 1952 ) , pp . 177 - 181 . N + (N + 4) div 5 end, sieve_num(tl(prime_cache()), lists:seq(?PrimeCache + 2, MaxN, 2), N); get_nearest(N) when N =< ?PrimeCache -> find_in_cache(N, prime_cache()). %% @doc Finds a number at least as large as N in the given prime list. %% Such a number must exist! -spec find_in_cache(pos_integer(), [pos_integer()]) -> prime(). find_in_cache(N, [P | _Cache]) when P >= N -> P; find_in_cache(N, [_ | Cache]) -> find_in_cache(N, Cache). @doc Sieves out all non - primes of the given list and returns the first number bigger than . Throws if there is no such number . -spec sieve_num(Primes::[non_neg_integer()], Candidates::[non_neg_integer()], Num::non_neg_integer()) -> Prime::non_neg_integer(). sieve_num([H | _TL], _Candidates, Num) when H >= Num -> H; sieve_num([H | TL], Candidates, Num) -> sieve_num(TL, sieve_filter(Candidates, H*H, H), Num); sieve_num([], [H | _TL], Num) when H >= Num -> H; sieve_num([], [H | TL], Num) -> sieve_num([], sieve_filter(TL, H*H, H), Num). @doc Removes all factors of Inc from List , starting with . -spec sieve_filter(List::[non_neg_integer()], Num::non_neg_integer(), Inc::non_neg_integer()) -> [non_neg_integer()]. sieve_filter([], _Num, _Inc) -> []; sieve_filter([Num | TL], Num, Inc) -> sieve_filter(TL, Num + Inc, Inc); sieve_filter([H | _TL] = All, Num, Inc) when H > Num -> sieve_filter(All, Num + Inc, Inc); sieve_filter([H | TL], Num, Inc) -> [H | sieve_filter(TL, Num, Inc)]. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -spec is_prime_feeder(1..?TESTER_MAX_PRIME) -> {1..?TESTER_MAX_PRIME}. is_prime_feeder(N) -> {N}. -spec is_prime(pos_integer()) -> boolean(). is_prime(V) when V =< ?PrimeCache -> lists:member(V, prime_cache()); is_prime(V) -> get_nearest(V-1) =:= V. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% @doc list of all primes less than 5003 from -spec prime_cache() -> [pos_integer()]. prime_cache() -> [ 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997, 1009, 1013, 1019, 1021, 1031, 1033, 1039, 1049, 1051, 1061, 1063, 1069, 1087, 1091, 1093, 1097, 1103, 1109, 1117, 1123, 1129, 1151, 1153, 1163, 1171, 1181, 1187, 1193, 1201, 1213, 1217, 1223, 1229, 1231, 1237, 1249, 1259, 1277, 1279, 1283, 1289, 1291, 1297, 1301, 1303, 1307, 1319, 1321, 1327, 1361, 1367, 1373, 1381, 1399, 1409, 1423, 1427, 1429, 1433, 1439, 1447, 1451, 1453, 1459, 1471, 1481, 1483, 1487, 1489, 1493, 1499, 1511, 1523, 1531, 1543, 1549, 1553, 1559, 1567, 1571, 1579, 1583, 1597, 1601, 1607, 1609, 1613, 1619, 1621, 1627, 1637, 1657, 1663, 1667, 1669, 1693, 1697, 1699, 1709, 1721, 1723, 1733, 1741, 1747, 1753, 1759, 1777, 1783, 1787, 1789, 1801, 1811, 1823, 1831, 1847, 1861, 1867, 1871, 1873, 1877, 1879, 1889, 1901, 1907, 1913, 1931, 1933, 1949, 1951, 1973, 1979, 1987, 1993, 1997, 1999, 2003, 2011, 2017, 2027, 2029, 2039, 2053, 2063, 2069, 2081, 2083, 2087, 2089, 2099, 2111, 2113, 2129, 2131, 2137, 2141, 2143, 2153, 2161, 2179, 2203, 2207, 2213, 2221, 2237, 2239, 2243, 2251, 2267, 2269, 2273, 2281, 2287, 2293, 2297, 2309, 2311, 2333, 2339, 2341, 2347, 2351, 2357, 2371, 2377, 2381, 2383, 2389, 2393, 2399, 2411, 2417, 2423, 2437, 2441, 2447, 2459, 2467, 2473, 2477, 2503, 2521, 2531, 2539, 2543, 2549, 2551, 2557, 2579, 2591, 2593, 2609, 2617, 2621, 2633, 2647, 2657, 2659, 2663, 2671, 2677, 2683, 2687, 2689, 2693, 2699, 2707, 2711, 2713, 2719, 2729, 2731, 2741, 2749, 2753, 2767, 2777, 2789, 2791, 2797, 2801, 2803, 2819, 2833, 2837, 2843, 2851, 2857, 2861, 2879, 2887, 2897, 2903, 2909, 2917, 2927, 2939, 2953, 2957, 2963, 2969, 2971, 2999, 3001, 3011, 3019, 3023, 3037, 3041, 3049, 3061, 3067, 3079, 3083, 3089, 3109, 3119, 3121, 3137, 3163, 3167, 3169, 3181, 3187, 3191, 3203, 3209, 3217, 3221, 3229, 3251, 3253, 3257, 3259, 3271, 3299, 3301, 3307, 3313, 3319, 3323, 3329, 3331, 3343, 3347, 3359, 3361, 3371, 3373, 3389, 3391, 3407, 3413, 3433, 3449, 3457, 3461, 3463, 3467, 3469, 3491, 3499, 3511, 3517, 3527, 3529, 3533, 3539, 3541, 3547, 3557, 3559, 3571, 3581, 3583, 3593, 3607, 3613, 3617, 3623, 3631, 3637, 3643, 3659, 3671, 3673, 3677, 3691, 3697, 3701, 3709, 3719, 3727, 3733, 3739, 3761, 3767, 3769, 3779, 3793, 3797, 3803, 3821, 3823, 3833, 3847, 3851, 3853, 3863, 3877, 3881, 3889, 3907, 3911, 3917, 3919, 3923, 3929, 3931, 3943, 3947, 3967, 3989, 4001, 4003, 4007, 4013, 4019, 4021, 4027, 4049, 4051, 4057, 4073, 4079, 4091, 4093, 4099, 4111, 4127, 4129, 4133, 4139, 4153, 4157, 4159, 4177, 4201, 4211, 4217, 4219, 4229, 4231, 4241, 4243, 4253, 4259, 4261, 4271, 4273, 4283, 4289, 4297, 4327, 4337, 4339, 4349, 4357, 4363, 4373, 4391, 4397, 4409, 4421, 4423, 4441, 4447, 4451, 4457, 4463, 4481, 4483, 4493, 4507, 4513, 4517, 4519, 4523, 4547, 4549, 4561, 4567, 4583, 4591, 4597, 4603, 4621, 4637, 4639, 4643, 4649, 4651, 4657, 4663, 4673, 4679, 4691, 4703, 4721, 4723, 4729, 4733, 4751, 4759, 4783, 4787, 4789, 4793, 4799, 4801, 4813, 4817, 4831, 4861, 4871, 4877, 4889, 4903, 4909, 4919, 4931, 4933, 4937, 4943, 4951, 4957, 4967, 4969, 4973, 4987, 4993, 4999, 5003].
null
https://raw.githubusercontent.com/scalaris-team/scalaris/feb894d54e642bb3530e709e730156b0ecc1635f/src/prime.erl
erlang
you may not use this file except in compliance with the License. You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing, software 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. @doc prime number module implemented method: trail division @end Implemented Method: Trial Division @version $Id$ feeder for tester last prime in prime_cache/0 loads the shared library tolerate some errors trying to load the library: @doc Finds a number at least as large as N in the given prime list. Such a number must exist!
2012 - 2014 Zuse Institute Berlin Licensed under the Apache License , Version 2.0 ( the " License " ) ; distributed under the License is distributed on an " AS IS " BASIS , @author < > @reference 2009 - < em > The Genuine Sieve of Eratosthenes < /em > Journal of Functional Programming 19(1 ) pp : 95 - 106 -module(prime). -author(''). -vsn('$Id$'). -include("record_helpers.hrl"). -include("scalaris.hrl"). -export([get_nearest/1, is_prime/1]). -export([is_prime_feeder/1, get_nearest_feeder/1]). -type prime() :: pos_integer(). -define(PrimeCache, 5003). -define(TESTER_MAX_PRIME, 5250). -on_load(init/0). -spec init() -> ok | {error, term()}. init() -> SoName = case code:priv_dir(scalaris) of {error, bad_name} -> Dir1 = filename:join( [filename:dirname(code:where_is_file("scalaris.beam")), "..", priv]), case filelib:is_dir(Dir1) of true -> filename:join(Dir1, ?MODULE); _ -> filename:join(["..", priv, ?MODULE]) end; Dir -> filename:join(Dir, ?MODULE) end, case erlang:load_nif(SoName, 0) of ok -> ok; {error, {load_failed, Text}} -> log:log(warn, "~s - falling back to the (considerably) slower Erlang native code", [Text]), ok; Error -> Error end. -spec get_nearest_feeder(1..?TESTER_MAX_PRIME) -> {1..?TESTER_MAX_PRIME}. get_nearest_feeder(N) -> {N}. @doc Returns the first prime larger than or equal to N. -spec get_nearest(pos_integer()) -> prime(). get_nearest(N) when N > ?PrimeCache -> MaxN = if N >= 396738 -> for x > = 396738 there is at least one prime between x and ( 1 + 1/(25ln^2(x)))x Dusart , ( 2010 ) . " Estimates of Some Functions Over Primes without " . LogN = math:log(N), util:ceil((1 + 1 / (25 * LogN*LogN)) * N); N >= 25 -> x > = 25 , there is always a prime between n and ( 1 + 1/5)n Nagura , J. " On the interval containing at least one prime number . " Proceedings of the Japan Academy , Series A 28 ( 1952 ) , pp . 177 - 181 . N + (N + 4) div 5 end, sieve_num(tl(prime_cache()), lists:seq(?PrimeCache + 2, MaxN, 2), N); get_nearest(N) when N =< ?PrimeCache -> find_in_cache(N, prime_cache()). -spec find_in_cache(pos_integer(), [pos_integer()]) -> prime(). find_in_cache(N, [P | _Cache]) when P >= N -> P; find_in_cache(N, [_ | Cache]) -> find_in_cache(N, Cache). @doc Sieves out all non - primes of the given list and returns the first number bigger than . Throws if there is no such number . -spec sieve_num(Primes::[non_neg_integer()], Candidates::[non_neg_integer()], Num::non_neg_integer()) -> Prime::non_neg_integer(). sieve_num([H | _TL], _Candidates, Num) when H >= Num -> H; sieve_num([H | TL], Candidates, Num) -> sieve_num(TL, sieve_filter(Candidates, H*H, H), Num); sieve_num([], [H | _TL], Num) when H >= Num -> H; sieve_num([], [H | TL], Num) -> sieve_num([], sieve_filter(TL, H*H, H), Num). @doc Removes all factors of Inc from List , starting with . -spec sieve_filter(List::[non_neg_integer()], Num::non_neg_integer(), Inc::non_neg_integer()) -> [non_neg_integer()]. sieve_filter([], _Num, _Inc) -> []; sieve_filter([Num | TL], Num, Inc) -> sieve_filter(TL, Num + Inc, Inc); sieve_filter([H | _TL] = All, Num, Inc) when H > Num -> sieve_filter(All, Num + Inc, Inc); sieve_filter([H | TL], Num, Inc) -> [H | sieve_filter(TL, Num, Inc)]. -spec is_prime_feeder(1..?TESTER_MAX_PRIME) -> {1..?TESTER_MAX_PRIME}. is_prime_feeder(N) -> {N}. -spec is_prime(pos_integer()) -> boolean(). is_prime(V) when V =< ?PrimeCache -> lists:member(V, prime_cache()); is_prime(V) -> get_nearest(V-1) =:= V. @doc list of all primes less than 5003 from -spec prime_cache() -> [pos_integer()]. prime_cache() -> [ 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997, 1009, 1013, 1019, 1021, 1031, 1033, 1039, 1049, 1051, 1061, 1063, 1069, 1087, 1091, 1093, 1097, 1103, 1109, 1117, 1123, 1129, 1151, 1153, 1163, 1171, 1181, 1187, 1193, 1201, 1213, 1217, 1223, 1229, 1231, 1237, 1249, 1259, 1277, 1279, 1283, 1289, 1291, 1297, 1301, 1303, 1307, 1319, 1321, 1327, 1361, 1367, 1373, 1381, 1399, 1409, 1423, 1427, 1429, 1433, 1439, 1447, 1451, 1453, 1459, 1471, 1481, 1483, 1487, 1489, 1493, 1499, 1511, 1523, 1531, 1543, 1549, 1553, 1559, 1567, 1571, 1579, 1583, 1597, 1601, 1607, 1609, 1613, 1619, 1621, 1627, 1637, 1657, 1663, 1667, 1669, 1693, 1697, 1699, 1709, 1721, 1723, 1733, 1741, 1747, 1753, 1759, 1777, 1783, 1787, 1789, 1801, 1811, 1823, 1831, 1847, 1861, 1867, 1871, 1873, 1877, 1879, 1889, 1901, 1907, 1913, 1931, 1933, 1949, 1951, 1973, 1979, 1987, 1993, 1997, 1999, 2003, 2011, 2017, 2027, 2029, 2039, 2053, 2063, 2069, 2081, 2083, 2087, 2089, 2099, 2111, 2113, 2129, 2131, 2137, 2141, 2143, 2153, 2161, 2179, 2203, 2207, 2213, 2221, 2237, 2239, 2243, 2251, 2267, 2269, 2273, 2281, 2287, 2293, 2297, 2309, 2311, 2333, 2339, 2341, 2347, 2351, 2357, 2371, 2377, 2381, 2383, 2389, 2393, 2399, 2411, 2417, 2423, 2437, 2441, 2447, 2459, 2467, 2473, 2477, 2503, 2521, 2531, 2539, 2543, 2549, 2551, 2557, 2579, 2591, 2593, 2609, 2617, 2621, 2633, 2647, 2657, 2659, 2663, 2671, 2677, 2683, 2687, 2689, 2693, 2699, 2707, 2711, 2713, 2719, 2729, 2731, 2741, 2749, 2753, 2767, 2777, 2789, 2791, 2797, 2801, 2803, 2819, 2833, 2837, 2843, 2851, 2857, 2861, 2879, 2887, 2897, 2903, 2909, 2917, 2927, 2939, 2953, 2957, 2963, 2969, 2971, 2999, 3001, 3011, 3019, 3023, 3037, 3041, 3049, 3061, 3067, 3079, 3083, 3089, 3109, 3119, 3121, 3137, 3163, 3167, 3169, 3181, 3187, 3191, 3203, 3209, 3217, 3221, 3229, 3251, 3253, 3257, 3259, 3271, 3299, 3301, 3307, 3313, 3319, 3323, 3329, 3331, 3343, 3347, 3359, 3361, 3371, 3373, 3389, 3391, 3407, 3413, 3433, 3449, 3457, 3461, 3463, 3467, 3469, 3491, 3499, 3511, 3517, 3527, 3529, 3533, 3539, 3541, 3547, 3557, 3559, 3571, 3581, 3583, 3593, 3607, 3613, 3617, 3623, 3631, 3637, 3643, 3659, 3671, 3673, 3677, 3691, 3697, 3701, 3709, 3719, 3727, 3733, 3739, 3761, 3767, 3769, 3779, 3793, 3797, 3803, 3821, 3823, 3833, 3847, 3851, 3853, 3863, 3877, 3881, 3889, 3907, 3911, 3917, 3919, 3923, 3929, 3931, 3943, 3947, 3967, 3989, 4001, 4003, 4007, 4013, 4019, 4021, 4027, 4049, 4051, 4057, 4073, 4079, 4091, 4093, 4099, 4111, 4127, 4129, 4133, 4139, 4153, 4157, 4159, 4177, 4201, 4211, 4217, 4219, 4229, 4231, 4241, 4243, 4253, 4259, 4261, 4271, 4273, 4283, 4289, 4297, 4327, 4337, 4339, 4349, 4357, 4363, 4373, 4391, 4397, 4409, 4421, 4423, 4441, 4447, 4451, 4457, 4463, 4481, 4483, 4493, 4507, 4513, 4517, 4519, 4523, 4547, 4549, 4561, 4567, 4583, 4591, 4597, 4603, 4621, 4637, 4639, 4643, 4649, 4651, 4657, 4663, 4673, 4679, 4691, 4703, 4721, 4723, 4729, 4733, 4751, 4759, 4783, 4787, 4789, 4793, 4799, 4801, 4813, 4817, 4831, 4861, 4871, 4877, 4889, 4903, 4909, 4919, 4931, 4933, 4937, 4943, 4951, 4957, 4967, 4969, 4973, 4987, 4993, 4999, 5003].
61b163e9745c5645acf27d08c132b512a44ed909d51fc452b749c3ea73b080e4
Clozure/ccl
system.lisp
(in-package :ccl) (defparameter *easygui-pathname* (or *load-pathname* *loading-file-source-file*)) (defvar *easygui-files* '("package" "new-cocoa-bindings" "events" "rgb" "views" "action-targets" "dialogs")) (defvar *easygui-examples* '("tiny" "currency-converter" "view-hierarchy")) (defun load-easygui (&optional (force-compile t)) (with-compilation-unit () (setq force-compile (load-ide-files *easygui-files* *easygui-pathname* force-compile)) (setq force-compile (load-ide-files *easygui-examples* (merge-pathnames ";example;" *easygui-pathname*) force-compile)) (push :easygui *features*)) force-compile)
null
https://raw.githubusercontent.com/Clozure/ccl/6c1a9458f7a5437b73ec227e989aa5b825f32fd3/examples/cocoa/easygui/system.lisp
lisp
(in-package :ccl) (defparameter *easygui-pathname* (or *load-pathname* *loading-file-source-file*)) (defvar *easygui-files* '("package" "new-cocoa-bindings" "events" "rgb" "views" "action-targets" "dialogs")) (defvar *easygui-examples* '("tiny" "currency-converter" "view-hierarchy")) (defun load-easygui (&optional (force-compile t)) (with-compilation-unit () (setq force-compile (load-ide-files *easygui-files* *easygui-pathname* force-compile)) (setq force-compile (load-ide-files *easygui-examples* (merge-pathnames ";example;" *easygui-pathname*) force-compile)) (push :easygui *features*)) force-compile)
06471c607bf434047c00100bbf9b6a56cab22068ddbaafd8df1c2802f5aee5f7
eponai/sulolive
core.cljs
(ns sulo-native.ios.core (:require [om.next :as om :refer-macros [defui]] [re-natal.support :as sup] [sulo-native.state :as state])) (set! js/window.React (js/require "react")) (def ReactNative (js/require "react-native")) (defn create-element [rn-comp opts & children] (apply js/React.createElement rn-comp (clj->js opts) children)) (def app-registry (.-AppRegistry ReactNative)) (def view (partial create-element (.-View ReactNative))) (def text (partial create-element (.-Text ReactNative))) (def image (partial create-element (.-Image ReactNative))) (def touchable-highlight (partial create-element (.-TouchableHighlight ReactNative))) (def logo-img (js/require "./images/cljs.png")) (defn alert [title] (.alert (.-Alert ReactNative) title)) (defui AppRoot static om/IQuery (query [this] '[:app/msg]) Object (render [this] (let [{:keys [app/msg]} (om/props this)] (view {:style {:flexDirection "column" :margin 40 :alignItems "center"}} (text {:style {:fontSize 30 :fontWeight "100" :marginBottom 20 :textAlign "center"}} msg) (image {:source logo-img :style {:width 80 :height 80 :marginBottom 30}}) (touchable-highlight {:style {:backgroundColor "#999" :padding 10 :borderRadius 5} :onPress #(alert "HELLO!")} (text {:style {:color "white" :textAlign "center" :fontWeight "bold"}} "press me")))))) (defonce RootNode (sup/root-node! 1)) (defonce app-root (om/factory RootNode)) (defn init [] (om/add-root! state/reconciler AppRoot 1) (.registerComponent app-registry "SuloNative" (fn [] app-root)))
null
https://raw.githubusercontent.com/eponai/sulolive/7a70701bbd3df6bbb92682679dcedb53f8822c18/sulo-native/src/sulo_native/ios/core.cljs
clojure
(ns sulo-native.ios.core (:require [om.next :as om :refer-macros [defui]] [re-natal.support :as sup] [sulo-native.state :as state])) (set! js/window.React (js/require "react")) (def ReactNative (js/require "react-native")) (defn create-element [rn-comp opts & children] (apply js/React.createElement rn-comp (clj->js opts) children)) (def app-registry (.-AppRegistry ReactNative)) (def view (partial create-element (.-View ReactNative))) (def text (partial create-element (.-Text ReactNative))) (def image (partial create-element (.-Image ReactNative))) (def touchable-highlight (partial create-element (.-TouchableHighlight ReactNative))) (def logo-img (js/require "./images/cljs.png")) (defn alert [title] (.alert (.-Alert ReactNative) title)) (defui AppRoot static om/IQuery (query [this] '[:app/msg]) Object (render [this] (let [{:keys [app/msg]} (om/props this)] (view {:style {:flexDirection "column" :margin 40 :alignItems "center"}} (text {:style {:fontSize 30 :fontWeight "100" :marginBottom 20 :textAlign "center"}} msg) (image {:source logo-img :style {:width 80 :height 80 :marginBottom 30}}) (touchable-highlight {:style {:backgroundColor "#999" :padding 10 :borderRadius 5} :onPress #(alert "HELLO!")} (text {:style {:color "white" :textAlign "center" :fontWeight "bold"}} "press me")))))) (defonce RootNode (sup/root-node! 1)) (defonce app-root (om/factory RootNode)) (defn init [] (om/add-root! state/reconciler AppRoot 1) (.registerComponent app-registry "SuloNative" (fn [] app-root)))
532882e7092a7fd13271fa3b82d635755804a52632a17c634cc6fa3fab22e964
patoline/patoline
pa_convert.ml
open Earley_core open Earley open Earley_ocaml open Pa_ocaml_prelude #define LOCATE locate module Ext = functor(In:Extension) -> struct include In FIXME use Blanks.line_comments . Blank function let blank str pos = let rec fn state ((str, pos) as cur) = let (c, str', pos') = Input.read str pos in let next = (str', pos') in match state, c with EOF reached | `Ini, (' ' | '\t' | '\r') -> fn `Ini next | `Ini, '#' -> fn `Com next | `Ini, _ -> cur | `Com, '\n' -> fn `Ini next | `Com, _ -> fn `Com next in fn `Ini (str, pos) Parser for let ex_int = parser i:''0x[0-9a-fA-F]+'' -> int_of_string i (* Single mapping parser *) let mapping = change_layout ( parser i:ex_int _:''[ \t]*'' j:ex_int?[-1] ) no_blank let build_file _loc ms = let combine (i, j) e = <:expr<arr.($int:i$) <- $int:j$; $e$>> in let e = List.fold_right combine ms <:expr<arr>> in <:struct< exception Undefined let conversion_array : int array = let arr = Array.make 256 (-1) in $e$ let to_uchar : char -> UChar.uchar = fun c -> let i = Char.code c in if i < 0 || i > 255 then raise Undefined; let u = conversion_array.(i) in if u < 0 then raise Undefined; u let to_utf8 : string -> string = fun s -> UTF8.init (String.length s) (fun i -> to_uchar s.[i-1]) let to_utf16 : string -> string = fun s -> UTF16.init (String.length s) (fun i -> to_uchar s.[i-1]) let to_utf32 : string -> string = fun s -> UTF32.init (String.length s) (fun i -> to_uchar s.[i-1]) >> let mappings = parser ms:mapping* "\x0A\x1A"? EOF -> build_file _loc ms let entry_points = (".TXT", Implementation (mappings, blank)) :: entry_points end (* Creating and running the extension *) module PatolineDefault = Pa_ocaml.Make(Ext(Pa_ocaml_prelude.Initial)) module M = Pa_main.Start(PatolineDefault)
null
https://raw.githubusercontent.com/patoline/patoline/3dcd41fdff64895d795d4a78baa27d572b161081/unicodelib/pa_convert.ml
ocaml
Single mapping parser Creating and running the extension
open Earley_core open Earley open Earley_ocaml open Pa_ocaml_prelude #define LOCATE locate module Ext = functor(In:Extension) -> struct include In FIXME use Blanks.line_comments . Blank function let blank str pos = let rec fn state ((str, pos) as cur) = let (c, str', pos') = Input.read str pos in let next = (str', pos') in match state, c with EOF reached | `Ini, (' ' | '\t' | '\r') -> fn `Ini next | `Ini, '#' -> fn `Com next | `Ini, _ -> cur | `Com, '\n' -> fn `Ini next | `Com, _ -> fn `Com next in fn `Ini (str, pos) Parser for let ex_int = parser i:''0x[0-9a-fA-F]+'' -> int_of_string i let mapping = change_layout ( parser i:ex_int _:''[ \t]*'' j:ex_int?[-1] ) no_blank let build_file _loc ms = let combine (i, j) e = <:expr<arr.($int:i$) <- $int:j$; $e$>> in let e = List.fold_right combine ms <:expr<arr>> in <:struct< exception Undefined let conversion_array : int array = let arr = Array.make 256 (-1) in $e$ let to_uchar : char -> UChar.uchar = fun c -> let i = Char.code c in if i < 0 || i > 255 then raise Undefined; let u = conversion_array.(i) in if u < 0 then raise Undefined; u let to_utf8 : string -> string = fun s -> UTF8.init (String.length s) (fun i -> to_uchar s.[i-1]) let to_utf16 : string -> string = fun s -> UTF16.init (String.length s) (fun i -> to_uchar s.[i-1]) let to_utf32 : string -> string = fun s -> UTF32.init (String.length s) (fun i -> to_uchar s.[i-1]) >> let mappings = parser ms:mapping* "\x0A\x1A"? EOF -> build_file _loc ms let entry_points = (".TXT", Implementation (mappings, blank)) :: entry_points end module PatolineDefault = Pa_ocaml.Make(Ext(Pa_ocaml_prelude.Initial)) module M = Pa_main.Start(PatolineDefault)
53df1d191094910b5fff3a661cbffac3285e362fcf7496f691b1d715aa84ae51
scrintal/heroicons-reagent
chart_bar_square.cljs
(ns com.scrintal.heroicons.mini.chart-bar-square) (defn render [] [:svg {:xmlns "" :viewBox "0 0 20 20" :fill "currentColor" :aria-hidden "true"} [:path {:fillRule "evenodd" :d "M4.25 2A2.25 2.25 0 002 4.25v11.5A2.25 2.25 0 004.25 18h11.5A2.25 2.25 0 0018 15.75V4.25A2.25 2.25 0 0015.75 2H4.25zM15 5.75a.75.75 0 00-1.5 0v8.5a.75.75 0 001.5 0v-8.5zm-8.5 6a.75.75 0 00-1.5 0v2.5a.75.75 0 001.5 0v-2.5zM8.584 9a.75.75 0 01.75.75v4.5a.75.75 0 01-1.5 0v-4.5a.75.75 0 01.75-.75zm3.58-1.25a.75.75 0 00-1.5 0v6.5a.75.75 0 001.5 0v-6.5z" :clipRule "evenodd"}]])
null
https://raw.githubusercontent.com/scrintal/heroicons-reagent/572f51d2466697ec4d38813663ee2588960365b6/src/com/scrintal/heroicons/mini/chart_bar_square.cljs
clojure
(ns com.scrintal.heroicons.mini.chart-bar-square) (defn render [] [:svg {:xmlns "" :viewBox "0 0 20 20" :fill "currentColor" :aria-hidden "true"} [:path {:fillRule "evenodd" :d "M4.25 2A2.25 2.25 0 002 4.25v11.5A2.25 2.25 0 004.25 18h11.5A2.25 2.25 0 0018 15.75V4.25A2.25 2.25 0 0015.75 2H4.25zM15 5.75a.75.75 0 00-1.5 0v8.5a.75.75 0 001.5 0v-8.5zm-8.5 6a.75.75 0 00-1.5 0v2.5a.75.75 0 001.5 0v-2.5zM8.584 9a.75.75 0 01.75.75v4.5a.75.75 0 01-1.5 0v-4.5a.75.75 0 01.75-.75zm3.58-1.25a.75.75 0 00-1.5 0v6.5a.75.75 0 001.5 0v-6.5z" :clipRule "evenodd"}]])
89380256a86a9546515ae592e594462a9c366e840140c94d21b3c7974485c470
huangjs/cl
trans2.lisp
-*- Mode : Lisp ; Package : Maxima ; Syntax : Common - Lisp ; Base : 10 -*- ; ; ; ; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; The data in this file contains enhancments. ;;;;; ;;; ;;;;; Copyright ( c ) 1984,1987 by , University of Texas ; ; ; ; ; ;;; All rights reserved ;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Please do not modify this file. See GJC ;;; ( c ) Copyright 1980 Massachusetts Institute of Technology ; ; ; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (in-package :maxima) ;;; TRANSLATION PROPERTIES FOR MACSYMA OPERATORS AND FUNCTIONS. ;;; This file is for list and array manipulation optimizations. (macsyma-module trans2) (transl-module trans2) (def%tr $random (form) `($fixnum . ($random ,@(tr-args (cdr form))))) (def%tr mequal (form) `($any . (simplify (list '(mequal) ,@(tr-args (cdr form)))))) (def%tr mcall (form) (setq form (cdr form)) (let ((mode (cond ((atom (car form)) (function-mode (car form))) (t '$any)))) (setq form (tr-args form)) (let ((op (car form))) (call-and-simp mode 'mcall `(,op . ,(cdr form)))))) ;;; Meaning of the mode properties: most names are historical. ( GETL X ' ( ARRAY - MODE ) ) means it is an array callable by the ;;; old maclisp style. This is unfortunately still useful to ;;; avoid indirection through the property list to get to the ;;; array. (defvar $translate_fast_arrays nil) ;;When $translate_fast_arrays and $use_fast_arrays are true there should only be two types of arrays and they should be stored on ;;the value cell of the symbol. These should be the equivalent of the and the si : equal - hash - table . Note that maxima lists ;;and maxima $matrices are also allowed for setting. Note also that ;;because of some hokey things like mqapply etc, if you want ;;fast referenceing use a[i], or b[i]:..., ie use variables, ;;since if you try something complicated it may not translate as ;;simply. Idea of these is for the to store the array in the value cell ;;to use equal-hash-tables, and to clean up the local variable ;;in translated code for an array. ;;txx(i,j):=block([hl],hl[i]:j,hl[i]); should leave hl unbound, after creating ;;a hash table for hl, There should be a resource of these. acceptable arguments to ar[i ] or ar[i]:val (defun lispm-marray-type (ar) (cond ((arrayp ar) 'array) ( (hash-table-p ar) 'hash-table) (($listp ar) '$list) (($matrixp ar) '$matrix) ((symbolp ar) 'symbol) (t nil))) (defun tr-maset (ar val inds) Top - level forms need to define the variable first . (if *macexpr-top-level-form-p* `(nil progn (defvar ,ar ',ar) (maset ,val ,ar ,@ inds)) `(nil maset ,val ,ar ,@ inds))) (defun maset1 ( val ar &rest inds &aux ) (cond ((and (typep ar 'cl:array) (= (length inds) (cl:array-rank ar))) (setf (apply #'aref ar inds) val)) ((typep ar 'cl:hash-table) (setf (gethash (if (cdr inds) (copy-list inds) (car inds)) ar) val)) ((symbolp ar) (error "must set the hash table outside")) ((and (= (length inds) 1) (or ($listp ar) ($matrixp ar))) (setf (nth (car inds) ar) val) val) ((and ($matrixp ar) (= (length inds) 2)) (setf (nth (second inds) (nth (car inds) ar)) val) val) (t (error "not a valid array reference to ~A" ar)))) ;;apply is too expensive for a simple array reference. The time is increased by a factor of 6 . Note we use the locf form to get at ;;the local variable of the function calling maset in order to be able ;;to store a hash-table there in the case that the variable was not an ;;array ;;COULD USE THE FOLLOWING TO handle fast_arrays:true. ;;(defun set-up-hash-table (&optional val key &aux tab) ;; (setq tab (make-hash-table :test 'equal)) ;alike? ( setf ( gethash key tab ) ) tab ) ;; ( defun maset - help1 ( val ar & rest inds & aux ) ;; "returns t if it set and nil if what went in could not be set but is a variable that ;; should be set to hash array" ;; (cond ((hash-table-p ar) ( setf ( gethash ( car inds ) ar ) ) ) ;; ((symbolp ar) nil) ;; (($listp ar) ( setf ( nth ( car inds ) ar ) ) t ) ( ( $ matrixp ar ) ( setf ( nth ( second inds ) ( nth ( car inds ) ar ) ) ) t ) ;; (t (error "not valid place ~A to put an array" ar)))) ;; ;; does n't prevent multiple evaluation of inds and ar .. but does n't use locf ( ( val ar & rest inds ) ;; `(cond ( ( arrayp ar ) ( setf ( aref ar , @ inds ) , ) ) ( ( maset - help1 , , ar , @ inds ) , ) ( t ( setf , ar ( set - up - hash - table , ( car , ind))),val ) ) ) ;; ( ( ar & rest inds ) ;; `(cond ((arrayp ,ar) (aref ,ar ,@ inds)) ( ( hash - table - p , ar ) ( gethash , ar ( car , inds ) ) ) ;; ((symbolp ,ar)`((,ar ,@ (copy-list ,inds)))))) ;;in maref in transl now (defun tr-maref (ar inds) `(nil maref , ar ,@ (copy-list inds))) (defun maref1 (ar &rest inds &aux ) (cond ((and (typep ar 'cl:array) (= (length inds) (cl:array-rank ar))) (apply #'aref ar inds)) ((typep ar 'cl:hash-table) (gethash (if (cdr inds) inds (car inds)) ar)) ((symbolp ar) (cond ((mget ar 'hashar) (harrfind `((,ar array) ,@(copy-list inds)))) (t `((,ar array) ,@(copy-list inds))))) ((and (= (length inds) 1) (or ($listp ar) ($matrixp ar))) (nth (first inds) ar)) ((and ($matrixp ar) (= (length inds) 2)) (nth (second inds) (nth (first inds) ar))) (t (merror "Wrong number of indices:~%~M" (cons '(mlist) inds))))) (defun tr-arraycall (form &aux all-inds) (cond ((get (caar form) 'array-mode) (pushnew (caar form) arrays :test #'eq) `(,(array-mode (caar form)) . (,(caar form) ,@(tr-args (cdr form))))) ($translate_fast_arrays (setq all-inds (mapcar 'dtranslate (cdr form))) ;;not apply changed 'tr-maref (funcall 'tr-maref (cdr (translate (caar form))) all-inds)) (t (translate `((marrayref) ,(if $tr_array_as_ref (caar form) `((mquote) ,(caar form))) ,@(cdr form)))))) (defun tr-arraysetq (array-ref value) actually an array SETF , but it comes from A[X]:FOO ;; which is ((MSETQ) ... ...) (cond ((getl (caar array-ref) '(array-mode)) (let ((t-ref (translate array-ref)) (t-value (translate value)) (mode)) (warn-mode array-ref (car t-ref) (car t-value)) (setq mode (car t-ref)) ; ooh, could be bad. `(,mode . (store ,(cdr t-ref) ,(cdr t-value))))) ($translate_fast_arrays (funcall 'tr-maset (caar array-ref) (dtranslate value) (mapcar 'dtranslate (copy-list (cdr array-ref))))) (t ;; oops. Hey, I switch around order of evaluation ;; here. no need to either man. gee. (translate `((marrayset) ,value ,(if $tr_array_as_ref (caar array-ref) `((mquote) ,(caar array-ref))) ,@(cdr array-ref)))))) (def%tr marrayref (form) (setq form (cdr form)) (let ((mode (cond ((atom (car form)) (mget (car form) 'array-mode))))) (cond ((null mode) (setq mode '$any))) (setq form (tr-args form)) (let ((op (car form))) `(,mode . (,(if (and (= (length form) 2) (eq mode '$float)) (progn (push-autoload-def 'marrayref '(marrayref1$)) 'marrayref1$) 'marrayref) ,op . ,(cdr form)))))) (def%tr marrayset (form) (setq form (cdr form)) (let ((mode (cond ((atom (cadr form)) (mget (cadr form) 'array-mode))))) (when (null mode) (setq mode '$any)) (setq form (tr-args form)) (destructuring-let (((val aarray . inds) form)) `(,mode . (,(if (and (= (length inds) 1) (eq mode '$float)) (progn (push-autoload-def 'marrayset '(marrayset1$)) 'marrayset1$) 'marrayset) ,val ,aarray . ,inds))))) (def%tr mlist (form) (if (null (cdr form)) ;;; [] '($any . '((mlist))) `($any . (list '(mlist) . ,(tr-args (cdr form)))))) (def%tr $first (form) (setq form (translate (cadr form))) (call-and-simp '$any (if (eq '$list (car form)) 'cadr '$first) (list (cdr form)))) ;; Local Modes: ;; Mode: LISP Comment Col : 40 ;; END:
null
https://raw.githubusercontent.com/huangjs/cl/96158b3f82f82a6b7d53ef04b3b29c5c8de2dbf7/lib/maxima/src/trans2.lisp
lisp
Package : Maxima ; Syntax : Common - Lisp ; Base : 10 -*- ; ; ; ; The data in this file contains enhancments. ;;;;; ;;;;; ; ; ; ; All rights reserved ;;;;; Please do not modify this file. See GJC ;;; ; ; TRANSLATION PROPERTIES FOR MACSYMA OPERATORS AND FUNCTIONS. This file is for list and array manipulation optimizations. Meaning of the mode properties: most names are historical. old maclisp style. This is unfortunately still useful to avoid indirection through the property list to get to the array. When $translate_fast_arrays and $use_fast_arrays are true the value cell of the symbol. These should be the equivalent of the and maxima $matrices are also allowed for setting. Note also that because of some hokey things like mqapply etc, if you want fast referenceing use a[i], or b[i]:..., ie use variables, since if you try something complicated it may not translate as simply. to use equal-hash-tables, and to clean up the local variable in translated code for an array. txx(i,j):=block([hl],hl[i]:j,hl[i]); should leave hl unbound, after creating a hash table for hl, There should be a resource of these. apply is too expensive for a simple array reference. The time the local variable of the function calling maset in order to be able to store a hash-table there in the case that the variable was not an array COULD USE THE FOLLOWING TO handle fast_arrays:true. (defun set-up-hash-table (&optional val key &aux tab) (setq tab (make-hash-table :test 'equal)) ;alike? "returns t if it set and nil if what went in could not be set but is a variable that should be set to hash array" (cond ((hash-table-p ar) ((symbolp ar) nil) (($listp ar) (t (error "not valid place ~A to put an array" ar)))) `(cond `(cond ((arrayp ,ar) (aref ,ar ,@ inds)) ((symbolp ,ar)`((,ar ,@ (copy-list ,inds)))))) in maref in transl now not apply changed 'tr-maref which is ((MSETQ) ... ...) ooh, could be bad. oops. Hey, I switch around order of evaluation here. no need to either man. gee. [] Local Modes: Mode: LISP END:
(in-package :maxima) (macsyma-module trans2) (transl-module trans2) (def%tr $random (form) `($fixnum . ($random ,@(tr-args (cdr form))))) (def%tr mequal (form) `($any . (simplify (list '(mequal) ,@(tr-args (cdr form)))))) (def%tr mcall (form) (setq form (cdr form)) (let ((mode (cond ((atom (car form)) (function-mode (car form))) (t '$any)))) (setq form (tr-args form)) (let ((op (car form))) (call-and-simp mode 'mcall `(,op . ,(cdr form)))))) ( GETL X ' ( ARRAY - MODE ) ) means it is an array callable by the (defvar $translate_fast_arrays nil) there should only be two types of arrays and they should be stored on and the si : equal - hash - table . Note that maxima lists Idea of these is for the to store the array in the value cell acceptable arguments to ar[i ] or ar[i]:val (defun lispm-marray-type (ar) (cond ((arrayp ar) 'array) ( (hash-table-p ar) 'hash-table) (($listp ar) '$list) (($matrixp ar) '$matrix) ((symbolp ar) 'symbol) (t nil))) (defun tr-maset (ar val inds) Top - level forms need to define the variable first . (if *macexpr-top-level-form-p* `(nil progn (defvar ,ar ',ar) (maset ,val ,ar ,@ inds)) `(nil maset ,val ,ar ,@ inds))) (defun maset1 ( val ar &rest inds &aux ) (cond ((and (typep ar 'cl:array) (= (length inds) (cl:array-rank ar))) (setf (apply #'aref ar inds) val)) ((typep ar 'cl:hash-table) (setf (gethash (if (cdr inds) (copy-list inds) (car inds)) ar) val)) ((symbolp ar) (error "must set the hash table outside")) ((and (= (length inds) 1) (or ($listp ar) ($matrixp ar))) (setf (nth (car inds) ar) val) val) ((and ($matrixp ar) (= (length inds) 2)) (setf (nth (second inds) (nth (car inds) ar)) val) val) (t (error "not a valid array reference to ~A" ar)))) is increased by a factor of 6 . Note we use the locf form to get at ( setf ( gethash key tab ) ) tab ) ( defun maset - help1 ( val ar & rest inds & aux ) ( setf ( gethash ( car inds ) ar ) ) ) ( setf ( nth ( car inds ) ar ) ) t ) ( ( $ matrixp ar ) ( setf ( nth ( second inds ) ( nth ( car inds ) ar ) ) ) t ) does n't prevent multiple evaluation of inds and ar .. but does n't use locf ( ( val ar & rest inds ) ( ( arrayp ar ) ( setf ( aref ar , @ inds ) , ) ) ( ( maset - help1 , , ar , @ inds ) , ) ( t ( setf , ar ( set - up - hash - table , ( car , ind))),val ) ) ) ( ( ar & rest inds ) ( ( hash - table - p , ar ) ( gethash , ar ( car , inds ) ) ) (defun tr-maref (ar inds) `(nil maref , ar ,@ (copy-list inds))) (defun maref1 (ar &rest inds &aux ) (cond ((and (typep ar 'cl:array) (= (length inds) (cl:array-rank ar))) (apply #'aref ar inds)) ((typep ar 'cl:hash-table) (gethash (if (cdr inds) inds (car inds)) ar)) ((symbolp ar) (cond ((mget ar 'hashar) (harrfind `((,ar array) ,@(copy-list inds)))) (t `((,ar array) ,@(copy-list inds))))) ((and (= (length inds) 1) (or ($listp ar) ($matrixp ar))) (nth (first inds) ar)) ((and ($matrixp ar) (= (length inds) 2)) (nth (second inds) (nth (first inds) ar))) (t (merror "Wrong number of indices:~%~M" (cons '(mlist) inds))))) (defun tr-arraycall (form &aux all-inds) (cond ((get (caar form) 'array-mode) (pushnew (caar form) arrays :test #'eq) `(,(array-mode (caar form)) . (,(caar form) ,@(tr-args (cdr form))))) ($translate_fast_arrays (setq all-inds (mapcar 'dtranslate (cdr form))) (funcall 'tr-maref (cdr (translate (caar form))) all-inds)) (t (translate `((marrayref) ,(if $tr_array_as_ref (caar form) `((mquote) ,(caar form))) ,@(cdr form)))))) (defun tr-arraysetq (array-ref value) actually an array SETF , but it comes from A[X]:FOO (cond ((getl (caar array-ref) '(array-mode)) (let ((t-ref (translate array-ref)) (t-value (translate value)) (mode)) (warn-mode array-ref (car t-ref) (car t-value)) `(,mode . (store ,(cdr t-ref) ,(cdr t-value))))) ($translate_fast_arrays (funcall 'tr-maset (caar array-ref) (dtranslate value) (mapcar 'dtranslate (copy-list (cdr array-ref))))) (t (translate `((marrayset) ,value ,(if $tr_array_as_ref (caar array-ref) `((mquote) ,(caar array-ref))) ,@(cdr array-ref)))))) (def%tr marrayref (form) (setq form (cdr form)) (let ((mode (cond ((atom (car form)) (mget (car form) 'array-mode))))) (cond ((null mode) (setq mode '$any))) (setq form (tr-args form)) (let ((op (car form))) `(,mode . (,(if (and (= (length form) 2) (eq mode '$float)) (progn (push-autoload-def 'marrayref '(marrayref1$)) 'marrayref1$) 'marrayref) ,op . ,(cdr form)))))) (def%tr marrayset (form) (setq form (cdr form)) (let ((mode (cond ((atom (cadr form)) (mget (cadr form) 'array-mode))))) (when (null mode) (setq mode '$any)) (setq form (tr-args form)) (destructuring-let (((val aarray . inds) form)) `(,mode . (,(if (and (= (length inds) 1) (eq mode '$float)) (progn (push-autoload-def 'marrayset '(marrayset1$)) 'marrayset1$) 'marrayset) ,val ,aarray . ,inds))))) (def%tr mlist (form) '($any . '((mlist))) `($any . (list '(mlist) . ,(tr-args (cdr form)))))) (def%tr $first (form) (setq form (translate (cadr form))) (call-and-simp '$any (if (eq '$list (car form)) 'cadr '$first) (list (cdr form)))) Comment Col : 40
d5a5427b64e4bc47e62ac0ae8c14b7bf93c9cc59eda47738f8dad291e1f9719d
lpw25/ocaml-typed-effects
datarepr.ml
(***********************************************************************) (* *) (* OCaml *) (* *) , projet Cristal , INRIA Rocquencourt (* *) Copyright 1996 Institut National de Recherche en Informatique et en Automatique . All rights reserved . This file is distributed under the terms of the Q Public License version 1.0 . (* *) (***********************************************************************) Compute constructor and label descriptions from type declarations , determining their representation . determining their representation. *) open Asttypes open Types open Btype (* Simplified version of Ctype.free_vars *) let free_vars ty = let ret = ref TypeSet.empty in let rec loop ty = let ty = repr ty in if ty.level >= lowest_level then begin ty.level <- pivot_level - ty.level; match ty.desc with | Tvar _ -> ret := TypeSet.add ty !ret | Tvariant row -> let row = row_repr row in iter_row loop row; if not (static_row row) then loop row.row_more | _ -> iter_type_expr loop ty end in loop ty; unmark_type ty; !ret let constructor_descrs ty_res cstrs priv = let num_consts = ref 0 and num_nonconsts = ref 0 and num_normal = ref 0 in List.iter (fun {cd_args; cd_res; _} -> if cd_args = [] then incr num_consts else incr num_nonconsts; if cd_res = None then incr num_normal) cstrs; let rec describe_constructors idx_const idx_nonconst = function [] -> [] | {cd_id; cd_args; cd_res; cd_loc; cd_attributes} :: rem -> let ty_res = match cd_res with | Some ty_res' -> ty_res' | None -> ty_res in let (tag, descr_rem) = match cd_args with [] -> (Cstr_constant idx_const, describe_constructors (idx_const+1) idx_nonconst rem) | _ -> (Cstr_block idx_nonconst, describe_constructors idx_const (idx_nonconst+1) rem) in let existentials = match cd_res with | None -> [] | Some type_ret -> let res_vars = free_vars type_ret in let arg_vars = free_vars (newgenty (Ttuple cd_args)) in TypeSet.elements (TypeSet.diff arg_vars res_vars) in let cstr = { cstr_name = Ident.name cd_id; cstr_res = ty_res; cstr_existentials = existentials; cstr_args = cd_args; cstr_arity = List.length cd_args; cstr_tag = tag; cstr_consts = !num_consts; cstr_nonconsts = !num_nonconsts; cstr_normal = !num_normal; cstr_private = priv; cstr_generalized = cd_res <> None; cstr_loc = cd_loc; cstr_attributes = cd_attributes; } in (cd_id, cstr) :: descr_rem in describe_constructors 0 0 cstrs let extension_descr path_ext ext = let ty_res = match ext.ext_ret_type with Some type_ret -> type_ret | None -> newgenty (Tconstr(ext.ext_type_path, ext.ext_type_params, Stype, ref Mnil)) in let tag = Cstr_extension(path_ext, ext.ext_args = []) in let existentials = match ext.ext_ret_type with | None -> [] | Some type_ret -> let vars = free_vars (newgenty (Ttuple (type_ret :: ext.ext_args))) in TypeSet.elements vars in { cstr_name = Path.last path_ext; cstr_res = ty_res; cstr_existentials = existentials; cstr_args = ext.ext_args; cstr_arity = List.length ext.ext_args; cstr_tag = tag; cstr_consts = -1; cstr_nonconsts = -1; cstr_private = ext.ext_private; cstr_normal = -1; cstr_generalized = ext.ext_ret_type <> None; cstr_loc = ext.ext_loc; cstr_attributes = ext.ext_attributes; } let none = {desc = Ttuple []; level = -1; id = -1} (* Clearly ill-formed type *) let dummy_label = { lbl_name = ""; lbl_res = none; lbl_arg = none; lbl_mut = Lmut_immutable; lbl_pos = (-1); lbl_all = [||]; lbl_repres = Record_regular; lbl_private = Public; lbl_loc = Location.none; lbl_attributes = []; } let label_descrs ty_res lbls repres priv = let all_labels = Array.make (List.length lbls) dummy_label in let rec describe_labels num = function [] -> [] | l :: rest -> let lbl = { lbl_name = Ident.name l.ld_id; lbl_res = ty_res; lbl_arg = l.ld_type; lbl_mut = l.ld_mutable; lbl_pos = num; lbl_all = all_labels; lbl_repres = repres; lbl_private = priv; lbl_loc = l.ld_loc; lbl_attributes = l.ld_attributes; } in all_labels.(num) <- lbl; (l.ld_id, lbl) :: describe_labels (num+1) rest in describe_labels 0 lbls let effect_constructor_descrs eff_path ecs = * let total = ecs in * let rec describe_constructors pos = function * | [ ] - > [ ] * | { ec_name ; ec_args ; ec_res ; ec_loc ; ec_attributes } : : rem - > * let existentials = * match ec_res with * | None - > [ ] * | Some res - > * let res_vars = free_vars res in * let arg_vars = free_vars ( newgenty ( Ttuple ec_args ) ) in * TypeSet.elements ( TypeSet.diff arg_vars res_vars ) * in * let = * { ecstr_name = Ident.name ec_id ; * ecstr_eff_path = eff_path ; * ecstr_pos = pos ; * ecstr_res = ec_res ; * ecstr_existentials = existentials ; * ecstr_args = ec_args ; * ecstr_arity = List.length ec_args ; * ecstr_constructors = total ; * = ec_loc ; * ecstr_attributes = ec_attributes ; * } * in * let rem = describe_constructors ( pos + 1 ) rem in * ( ec_id , ) : : rem * in * describe_constructors 0 ecs * let total = List.length ecs in * let rec describe_constructors pos = function * | [] -> [] * | {ec_name; ec_args; ec_res; ec_loc; ec_attributes} :: rem -> * let existentials = * match ec_res with * | None -> [] * | Some res -> * let res_vars = free_vars res in * let arg_vars = free_vars (newgenty (Ttuple ec_args)) in * TypeSet.elements (TypeSet.diff arg_vars res_vars) * in * let ecstr = * { ecstr_name = Ident.name ec_id; * ecstr_eff_path = eff_path; * ecstr_pos = pos; * ecstr_res = ec_res; * ecstr_existentials = existentials; * ecstr_args = ec_args; * ecstr_arity = List.length ec_args; * ecstr_constructors = total; * ecstr_loc = ec_loc; * ecstr_attributes = ec_attributes; * } * in * let rem = describe_constructors (pos + 1) rem in * (ec_id, ecstr) :: rem * in * describe_constructors 0 ecs *) exception Constr_not_found let rec find_constr tag num_const num_nonconst = function [] -> raise Constr_not_found | {cd_args = []; _} as c :: rem -> if tag = Cstr_constant num_const then c else find_constr tag (num_const + 1) num_nonconst rem | c :: rem -> if tag = Cstr_block num_nonconst then c else find_constr tag num_const (num_nonconst + 1) rem let find_constr_by_tag tag cstrlist = find_constr tag 0 0 cstrlist
null
https://raw.githubusercontent.com/lpw25/ocaml-typed-effects/79ea08b285c1fd9caf3f5a4d2aa112877f882bea/typing/datarepr.ml
ocaml
********************************************************************* OCaml ********************************************************************* Simplified version of Ctype.free_vars Clearly ill-formed type
, projet Cristal , INRIA Rocquencourt Copyright 1996 Institut National de Recherche en Informatique et en Automatique . All rights reserved . This file is distributed under the terms of the Q Public License version 1.0 . Compute constructor and label descriptions from type declarations , determining their representation . determining their representation. *) open Asttypes open Types open Btype let free_vars ty = let ret = ref TypeSet.empty in let rec loop ty = let ty = repr ty in if ty.level >= lowest_level then begin ty.level <- pivot_level - ty.level; match ty.desc with | Tvar _ -> ret := TypeSet.add ty !ret | Tvariant row -> let row = row_repr row in iter_row loop row; if not (static_row row) then loop row.row_more | _ -> iter_type_expr loop ty end in loop ty; unmark_type ty; !ret let constructor_descrs ty_res cstrs priv = let num_consts = ref 0 and num_nonconsts = ref 0 and num_normal = ref 0 in List.iter (fun {cd_args; cd_res; _} -> if cd_args = [] then incr num_consts else incr num_nonconsts; if cd_res = None then incr num_normal) cstrs; let rec describe_constructors idx_const idx_nonconst = function [] -> [] | {cd_id; cd_args; cd_res; cd_loc; cd_attributes} :: rem -> let ty_res = match cd_res with | Some ty_res' -> ty_res' | None -> ty_res in let (tag, descr_rem) = match cd_args with [] -> (Cstr_constant idx_const, describe_constructors (idx_const+1) idx_nonconst rem) | _ -> (Cstr_block idx_nonconst, describe_constructors idx_const (idx_nonconst+1) rem) in let existentials = match cd_res with | None -> [] | Some type_ret -> let res_vars = free_vars type_ret in let arg_vars = free_vars (newgenty (Ttuple cd_args)) in TypeSet.elements (TypeSet.diff arg_vars res_vars) in let cstr = { cstr_name = Ident.name cd_id; cstr_res = ty_res; cstr_existentials = existentials; cstr_args = cd_args; cstr_arity = List.length cd_args; cstr_tag = tag; cstr_consts = !num_consts; cstr_nonconsts = !num_nonconsts; cstr_normal = !num_normal; cstr_private = priv; cstr_generalized = cd_res <> None; cstr_loc = cd_loc; cstr_attributes = cd_attributes; } in (cd_id, cstr) :: descr_rem in describe_constructors 0 0 cstrs let extension_descr path_ext ext = let ty_res = match ext.ext_ret_type with Some type_ret -> type_ret | None -> newgenty (Tconstr(ext.ext_type_path, ext.ext_type_params, Stype, ref Mnil)) in let tag = Cstr_extension(path_ext, ext.ext_args = []) in let existentials = match ext.ext_ret_type with | None -> [] | Some type_ret -> let vars = free_vars (newgenty (Ttuple (type_ret :: ext.ext_args))) in TypeSet.elements vars in { cstr_name = Path.last path_ext; cstr_res = ty_res; cstr_existentials = existentials; cstr_args = ext.ext_args; cstr_arity = List.length ext.ext_args; cstr_tag = tag; cstr_consts = -1; cstr_nonconsts = -1; cstr_private = ext.ext_private; cstr_normal = -1; cstr_generalized = ext.ext_ret_type <> None; cstr_loc = ext.ext_loc; cstr_attributes = ext.ext_attributes; } let none = {desc = Ttuple []; level = -1; id = -1} let dummy_label = { lbl_name = ""; lbl_res = none; lbl_arg = none; lbl_mut = Lmut_immutable; lbl_pos = (-1); lbl_all = [||]; lbl_repres = Record_regular; lbl_private = Public; lbl_loc = Location.none; lbl_attributes = []; } let label_descrs ty_res lbls repres priv = let all_labels = Array.make (List.length lbls) dummy_label in let rec describe_labels num = function [] -> [] | l :: rest -> let lbl = { lbl_name = Ident.name l.ld_id; lbl_res = ty_res; lbl_arg = l.ld_type; lbl_mut = l.ld_mutable; lbl_pos = num; lbl_all = all_labels; lbl_repres = repres; lbl_private = priv; lbl_loc = l.ld_loc; lbl_attributes = l.ld_attributes; } in all_labels.(num) <- lbl; (l.ld_id, lbl) :: describe_labels (num+1) rest in describe_labels 0 lbls let effect_constructor_descrs eff_path ecs = * let total = ecs in * let rec describe_constructors pos = function * | [ ] - > [ ] * | { ec_name ; ec_args ; ec_res ; ec_loc ; ec_attributes } : : rem - > * let existentials = * match ec_res with * | None - > [ ] * | Some res - > * let res_vars = free_vars res in * let arg_vars = free_vars ( newgenty ( Ttuple ec_args ) ) in * TypeSet.elements ( TypeSet.diff arg_vars res_vars ) * in * let = * { ecstr_name = Ident.name ec_id ; * ecstr_eff_path = eff_path ; * ecstr_pos = pos ; * ecstr_res = ec_res ; * ecstr_existentials = existentials ; * ecstr_args = ec_args ; * ecstr_arity = List.length ec_args ; * ecstr_constructors = total ; * = ec_loc ; * ecstr_attributes = ec_attributes ; * } * in * let rem = describe_constructors ( pos + 1 ) rem in * ( ec_id , ) : : rem * in * describe_constructors 0 ecs * let total = List.length ecs in * let rec describe_constructors pos = function * | [] -> [] * | {ec_name; ec_args; ec_res; ec_loc; ec_attributes} :: rem -> * let existentials = * match ec_res with * | None -> [] * | Some res -> * let res_vars = free_vars res in * let arg_vars = free_vars (newgenty (Ttuple ec_args)) in * TypeSet.elements (TypeSet.diff arg_vars res_vars) * in * let ecstr = * { ecstr_name = Ident.name ec_id; * ecstr_eff_path = eff_path; * ecstr_pos = pos; * ecstr_res = ec_res; * ecstr_existentials = existentials; * ecstr_args = ec_args; * ecstr_arity = List.length ec_args; * ecstr_constructors = total; * ecstr_loc = ec_loc; * ecstr_attributes = ec_attributes; * } * in * let rem = describe_constructors (pos + 1) rem in * (ec_id, ecstr) :: rem * in * describe_constructors 0 ecs *) exception Constr_not_found let rec find_constr tag num_const num_nonconst = function [] -> raise Constr_not_found | {cd_args = []; _} as c :: rem -> if tag = Cstr_constant num_const then c else find_constr tag (num_const + 1) num_nonconst rem | c :: rem -> if tag = Cstr_block num_nonconst then c else find_constr tag num_const (num_nonconst + 1) rem let find_constr_by_tag tag cstrlist = find_constr tag 0 0 cstrlist
92277158cb4548e8e6abd03f571bf4830db1ed62ac744e823f88ea44394ee332
pink-gorilla/goldly
system.cljs
(ns goldly.component.type.system (:require [taoensso.timbre :as timbre :refer-macros [debugf infof errorf]] [goldly.component.ui :refer [render-component]] [goldly.system.sci :refer [render-system]])) (defmethod render-component :system [{:keys [id data args]}] (let [{:keys [fns-clj cljs]} @data {:keys [ext]} args] (infof "rendering system: id: %s data: %s args: %s" id @data args) [render-system (merge {:id id :fns-clj fns-clj} cljs) ext]))
null
https://raw.githubusercontent.com/pink-gorilla/goldly/a942f29378e51da5725989ba017bac5a61e7fe54/src-unused/system/goldly/component/type/system.cljs
clojure
(ns goldly.component.type.system (:require [taoensso.timbre :as timbre :refer-macros [debugf infof errorf]] [goldly.component.ui :refer [render-component]] [goldly.system.sci :refer [render-system]])) (defmethod render-component :system [{:keys [id data args]}] (let [{:keys [fns-clj cljs]} @data {:keys [ext]} args] (infof "rendering system: id: %s data: %s args: %s" id @data args) [render-system (merge {:id id :fns-clj fns-clj} cljs) ext]))
95c66daad96f819cf5d8fdc26755453a274c8b5197396c663e5fb871672ac48b
typelead/intellij-eta
Hello00001.hs
main = print "Hello, World!"
null
https://raw.githubusercontent.com/typelead/intellij-eta/ee66d621aa0bfdf56d7d287279a9a54e89802cf9/plugin/src/test/resources/fixtures/eta/sources/Hello00001.hs
haskell
main = print "Hello, World!"
2f123b825cd4195994bb0cf0d8633dd84cd6c1b17c3857c1452f06eef26c5964
Clozure/ccl
splay-tree.lisp
-*-Mode : LISP ; Package : CCL -*- ;;; Copyright 2003 - 2009 Clozure Associates ;;; 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 ;;; ;;; -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. (in-package "CCL") A ( partial ) implementation of SPLAY - TREEs , which are binary trees ;;; that reorganize themselves so that the most recently accessed keys ;;; cluster near the tree's root. (defstruct (tree-node (:constructor make-tree-node (key value))) key value the child < this key , or NIL the child > this key , or NIL parent ; we're the root if NIL. ) (defmethod print-object ((node tree-node) stream) (print-unreadable-object (node stream :type t :identity t) (let* ((*print-circle* t)) (format stream "~s -> ~s" (tree-node-key node) (tree-node-value node))))) (defun tree-node-is-leaf (n) (and (null (tree-node-left n)) (null (tree-node-right n)))) (defun tree-node-is-root (n) (null (tree-node-parent n))) ;;; Is node the left child of its parent ? (defun tree-node-is-left (n) (let* ((parent (tree-node-parent n))) (and parent (eq n (tree-node-left parent))))) (defun tree-node-is-right (n) (let* ((parent (tree-node-parent n))) (and parent (eq n (tree-node-right parent))))) (defun tree-node-set-right (node newright) (when (setf (tree-node-right node) newright) (setf (tree-node-parent newright) node))) (defun tree-node-set-left (node newleft) (when (setf (tree-node-left node) newleft) (setf (tree-node-parent newleft) node))) (defun tree-node-replace-child (node old new) (if (eq old (tree-node-left node)) (tree-node-set-left node new) (tree-node-set-right node new))) (defstruct (splay-tree (:constructor %make-splay-tree)) (root nil #|:type (or null splay-tree-node)|#) equal ; true if x = y less ; true if x < y (count 0) ) (defmethod print-object ((tree splay-tree) stream) (print-unreadable-object (tree stream :type t :identity t) (format stream "count = ~d, root = ~s" (splay-tree-count tree) (splay-tree-root tree)))) Returns tree - node or NIL (defun binary-tree-get (tree key) (do* ((equal (splay-tree-equal tree)) (less (splay-tree-less tree)) (node (splay-tree-root tree))) ((null node)) (let* ((node-key (tree-node-key node))) (if (funcall equal key node-key) (return node) (if (funcall less key node-key) (setq node (tree-node-left node)) (setq node (tree-node-right node))))))) ;;; No node with matching key exists in the tree (defun binary-tree-insert (tree node) (let* ((root (splay-tree-root tree))) (if (null root) (setf (splay-tree-root tree) node) (do* ((less (splay-tree-less tree)) (key (tree-node-key node)) (current root) (parent nil)) ((null current) (if (funcall less key (tree-node-key parent)) (tree-node-set-left parent node) (tree-node-set-right parent node))) (setq parent current) (if (funcall less key (tree-node-key current)) (setq current (tree-node-left current)) (setq current (tree-node-right current)))))) (incf (splay-tree-count tree))) ;;; Replace the node's parent with the node itself, updating the ;;; affected children so that the binary tree remains properly ;;; ordered. (defun binary-tree-rotate (tree node) (when (and node (not (tree-node-is-root node))) (let* ((parent (tree-node-parent node)) (grandparent (if parent (tree-node-parent parent))) (was-left (tree-node-is-left node))) (if grandparent (tree-node-replace-child grandparent parent node) (setf (splay-tree-root tree) node (tree-node-parent node) nil)) (if was-left (progn (tree-node-set-left parent (tree-node-right node)) (tree-node-set-right node parent)) (progn (tree-node-set-right parent (tree-node-left node)) (tree-node-set-left node parent)))))) ;;; Keep rotating the node (and maybe its parent) until the node's the ;;; root of tree. (defun splay-tree-splay (tree node) (when node (do* () ((tree-node-is-root node)) (let* ((parent (tree-node-parent node)) (grandparent (tree-node-parent parent))) (cond ((null grandparent) (binary-tree-rotate tree node)) ; node is now root ((eq (tree-node-is-left node) (tree-node-is-left parent)) (binary-tree-rotate tree parent) (binary-tree-rotate tree node)) (t (binary-tree-rotate tree node) (binary-tree-rotate tree node))))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; ;;; The more-or-less public API follows. ;;; ;;; I suppose that we should support DELETE as well, and perhaps ;;; UPDATE (find the node and modify its key in place.) For now, SPLAY - TREE - PUT assumes that no node with a matching key exists . ;;; Access to the tree has to be serialized by the caller. (defun splay-tree-get (tree key &optional default) (let* ((node (binary-tree-get tree key))) (if node (progn (splay-tree-splay tree node) (tree-node-value node)) default))) (defun splay-tree-put (tree key value) (let* ((node (make-tree-node key value))) (binary-tree-insert tree node) (splay-tree-splay tree node) value)) Note that the tree wants two comparison functions . This may increase the chance that builtin CL functions can be used ; a tree ;;; whose keys are real numbers could use #'= and #'<, for instance. Using two comparison functions is ( at best ) only slightly better ;;; than insisting that a single comparison function return (values equal less ) , or ( member -1 0 1 ) , or some other convention . (defun make-splay-tree (equal less) (check-type equal function) (check-type less function) (%make-splay-tree :equal equal :less less)) ;;; Do an inorder traversal of the splay tree, applying function F ;;; to the value of each node. (defun map-splay-tree (tree f) (labels ((map-tree-node (node) (when node (map-tree-node (tree-node-left node)) (funcall f (tree-node-value node)) (map-tree-node (tree-node-right node))))) (map-tree-node (splay-tree-root tree)))) (defun map-splay-tree-keys-and-values (tree f) (labels ((map-tree-node (node) (when node (map-tree-node (tree-node-left node)) (funcall f (tree-node-key node) (tree-node-value node)) (map-tree-node (tree-node-right node))))) (map-tree-node (splay-tree-root tree))))
null
https://raw.githubusercontent.com/Clozure/ccl/6c1a9458f7a5437b73ec227e989aa5b825f32fd3/library/splay-tree.lisp
lisp
Package : CCL -*- you may not use this file except in compliance with the License. You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing, software 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. that reorganize themselves so that the most recently accessed keys cluster near the tree's root. we're the root if NIL. Is node the left child of its parent ? :type (or null splay-tree-node) true if x = y true if x < y No node with matching key exists in the tree Replace the node's parent with the node itself, updating the affected children so that the binary tree remains properly ordered. Keep rotating the node (and maybe its parent) until the node's the root of tree. node is now root The more-or-less public API follows. I suppose that we should support DELETE as well, and perhaps UPDATE (find the node and modify its key in place.) For now, Access to the tree has to be serialized by the caller. a tree whose keys are real numbers could use #'= and #'<, for instance. than insisting that a single comparison function return (values Do an inorder traversal of the splay tree, applying function F to the value of each node.
Copyright 2003 - 2009 Clozure Associates distributed under the License is distributed on an " AS IS " BASIS , (in-package "CCL") A ( partial ) implementation of SPLAY - TREEs , which are binary trees (defstruct (tree-node (:constructor make-tree-node (key value))) key value the child < this key , or NIL the child > this key , or NIL ) (defmethod print-object ((node tree-node) stream) (print-unreadable-object (node stream :type t :identity t) (let* ((*print-circle* t)) (format stream "~s -> ~s" (tree-node-key node) (tree-node-value node))))) (defun tree-node-is-leaf (n) (and (null (tree-node-left n)) (null (tree-node-right n)))) (defun tree-node-is-root (n) (null (tree-node-parent n))) (defun tree-node-is-left (n) (let* ((parent (tree-node-parent n))) (and parent (eq n (tree-node-left parent))))) (defun tree-node-is-right (n) (let* ((parent (tree-node-parent n))) (and parent (eq n (tree-node-right parent))))) (defun tree-node-set-right (node newright) (when (setf (tree-node-right node) newright) (setf (tree-node-parent newright) node))) (defun tree-node-set-left (node newleft) (when (setf (tree-node-left node) newleft) (setf (tree-node-parent newleft) node))) (defun tree-node-replace-child (node old new) (if (eq old (tree-node-left node)) (tree-node-set-left node new) (tree-node-set-right node new))) (defstruct (splay-tree (:constructor %make-splay-tree)) (count 0) ) (defmethod print-object ((tree splay-tree) stream) (print-unreadable-object (tree stream :type t :identity t) (format stream "count = ~d, root = ~s" (splay-tree-count tree) (splay-tree-root tree)))) Returns tree - node or NIL (defun binary-tree-get (tree key) (do* ((equal (splay-tree-equal tree)) (less (splay-tree-less tree)) (node (splay-tree-root tree))) ((null node)) (let* ((node-key (tree-node-key node))) (if (funcall equal key node-key) (return node) (if (funcall less key node-key) (setq node (tree-node-left node)) (setq node (tree-node-right node))))))) (defun binary-tree-insert (tree node) (let* ((root (splay-tree-root tree))) (if (null root) (setf (splay-tree-root tree) node) (do* ((less (splay-tree-less tree)) (key (tree-node-key node)) (current root) (parent nil)) ((null current) (if (funcall less key (tree-node-key parent)) (tree-node-set-left parent node) (tree-node-set-right parent node))) (setq parent current) (if (funcall less key (tree-node-key current)) (setq current (tree-node-left current)) (setq current (tree-node-right current)))))) (incf (splay-tree-count tree))) (defun binary-tree-rotate (tree node) (when (and node (not (tree-node-is-root node))) (let* ((parent (tree-node-parent node)) (grandparent (if parent (tree-node-parent parent))) (was-left (tree-node-is-left node))) (if grandparent (tree-node-replace-child grandparent parent node) (setf (splay-tree-root tree) node (tree-node-parent node) nil)) (if was-left (progn (tree-node-set-left parent (tree-node-right node)) (tree-node-set-right node parent)) (progn (tree-node-set-right parent (tree-node-left node)) (tree-node-set-left node parent)))))) (defun splay-tree-splay (tree node) (when node (do* () ((tree-node-is-root node)) (let* ((parent (tree-node-parent node)) (grandparent (tree-node-parent parent))) (cond ((null grandparent) ((eq (tree-node-is-left node) (tree-node-is-left parent)) (binary-tree-rotate tree parent) (binary-tree-rotate tree node)) (t (binary-tree-rotate tree node) (binary-tree-rotate tree node))))))) SPLAY - TREE - PUT assumes that no node with a matching key exists . (defun splay-tree-get (tree key &optional default) (let* ((node (binary-tree-get tree key))) (if node (progn (splay-tree-splay tree node) (tree-node-value node)) default))) (defun splay-tree-put (tree key value) (let* ((node (make-tree-node key value))) (binary-tree-insert tree node) (splay-tree-splay tree node) value)) Note that the tree wants two comparison functions . This may Using two comparison functions is ( at best ) only slightly better equal less ) , or ( member -1 0 1 ) , or some other convention . (defun make-splay-tree (equal less) (check-type equal function) (check-type less function) (%make-splay-tree :equal equal :less less)) (defun map-splay-tree (tree f) (labels ((map-tree-node (node) (when node (map-tree-node (tree-node-left node)) (funcall f (tree-node-value node)) (map-tree-node (tree-node-right node))))) (map-tree-node (splay-tree-root tree)))) (defun map-splay-tree-keys-and-values (tree f) (labels ((map-tree-node (node) (when node (map-tree-node (tree-node-left node)) (funcall f (tree-node-key node) (tree-node-value node)) (map-tree-node (tree-node-right node))))) (map-tree-node (splay-tree-root tree))))
9b31dfe38f92bdc4f650681df6dcf7bc9938c808a5255fcb9324bdfc9d9f433b
KULeuven-CS/CPL
CALL-BY-NEED.rkt
#lang eopl (require "syntax.rkt") ;(require "store.rkt") (require "../EXPLICIT-REFS/store.rkt") (provide (all-defined-out)) Semantics (define-datatype expval expval? (num-val (value number?)) (bool-val (boolean boolean?)) (proc-val (proc proc?)) ) ;; proc? : SchemeVal -> Bool ;; procedure : Var * Exp * Env -> Proc (define-datatype proc proc? (procedure (var symbol?) (body expression?) (env environment?))) ;; expval->num : ExpVal -> Int Page : 70 (define expval->num (lambda (v) (cases expval v (num-val (num) num) (else (expval-extractor-error 'num v))))) ;; expval->bool : ExpVal -> Bool Page : 70 (define expval->bool (lambda (v) (cases expval v (bool-val (bool) bool) (else (expval-extractor-error 'bool v))))) ;; expval->proc : ExpVal -> Proc (define expval->proc (lambda (v) (cases expval v (proc-val (p) p) (else (expval-extractor-error 'proc v))))) (define expval-extractor-error (lambda (variant value) (eopl:error 'expval-extractors "Looking for a ~s, found ~s" variant value))) ;; Environments (define-datatype environment environment? (empty-env) (extend-env (bvar symbol?) (bval reference?) ; new for implicit-refs (saved-env environment?)) (extend-env-rec* (proc-names (list-of symbol?)) (b-vars (list-of symbol?)) (proc-bodies (list-of expression?)) (saved-env environment?))) ;; apply-env: Env x Var -> Ref (define apply-env (lambda (env search-sym) (cases environment env (empty-env () (eopl:error 'apply-env "No binding for ~s" search-sym)) (extend-env (bvar bval saved-env) (if (eqv? search-sym bvar) bval (apply-env saved-env search-sym))) (extend-env-rec* (p-names b-vars p-bodies saved-env) (let ((n (location search-sym p-names))) ;; n : (maybe int) (if n (newref (proc-val (procedure (list-ref b-vars n) (list-ref p-bodies n) env))) (apply-env saved-env search-sym)))) ))) ;; location : Sym * Listof(Sym) -> Maybe(Int) ( location sym syms ) returns the location of sym in syms or # f is sym is not in syms . We can specify this as follows : if ( ) then ( list - ref ( location sym syms ) ) = sym ;; else (location sym syms) = #f (define location (lambda (sym syms) (cond ((null? syms) #f) ((eqv? sym (car syms)) 0) ((location sym (cdr syms)) => (lambda (n) (+ n 1))) (else #f)))) ;; init-env : () -> Env (define init-env (lambda () (extend-env 'i (newref (num-val 1)) (extend-env 'v (newref (num-val 5)) (extend-env 'x (newref (num-val 10)) (empty-env)))))) ;; Interpreter value - of - program : Program - > ExpVal Page : 71 (define value-of-program (lambda (pgm) (initialize-store!) (cases program pgm (a-program (exp1) (value-of exp1 (init-env)))))) ;; ... ;; BASED ON IMPLICIT-REFS ;===========CHANGES=FROM=HERE============= Additions of CALL - BY - NEED see p 137,138 ;; Define new thunk datatype (define-datatype thunk thunk? (a-thunk (exp1 expression?) (env environment?))) ;; Returns the proper bound value references of an ;; operand at function call-time. ;; In the case that this operand is already thunked ;; the reference in the given Env is returned ;; value-of-operand : Exp * Env -> Ref (define value-of-operand (lambda (exp env) (cases expression exp (var-exp (var) (apply-env env var)) ;Operand that is already referenced (and thunked) (else (newref (a-thunk exp env)))))) ;Create new thunk for the actual expression Evalutes the given thunk to an actual value . value - of - thunk : Thunk - > ExpVal (define value-of-thunk (lambda (th) (cases thunk th (a-thunk (exp1 saved-env) (value-of exp1 saved-env))))) value - of : Exp * Env - > ExpVal Page : 71 (define value-of (lambda (exp env) (cases expression exp (const-exp (num) (num-val num)) ;; CALL-BY-NAME implementation ; (var-exp (var) ( let ( ( ref1 ( apply - env env var ) ) ) ( let ( ( w ( deref ref1 ) ) ) ; (if (expval? w) ; w ; (value-of-thunk w))))) ; CALL-BY-NEED used (var-exp (var) ; Evaluate thunk when the referenced var is one. (let ((ref1 (apply-env env var))) (let ((w (deref ref1))) (if (expval? w) Referenced is an actual expression already Evaluate thunk and update ref1 (begin (setref! ref1 val1) val1)))))) (diff-exp (exp1 exp2) (let ((val1 (value-of exp1 env)) (val2 (value-of exp2 env))) (let ((num1 (expval->num val1)) (num2 (expval->num val2))) (num-val (- num1 num2))))) (zero?-exp (exp1) (let ((val1 (value-of exp1 env))) (let ((num1 (expval->num val1))) (if (zero? num1) (bool-val #t) (bool-val #f))))) (if-exp (exp1 exp2 exp3) (let ((val1 (value-of exp1 env))) (if (expval->bool val1) (value-of exp2 env) (value-of exp3 env)))) (let-exp (var exp1 body) (let ((v1 (value-of exp1 env))) (value-of body (extend-env var (newref v1) env)))) (proc-exp (var body) (proc-val (procedure var body env))) ; ... (call-exp (rator rand) (let ((proc (expval->proc (value-of rator env))) ; (arg (value-of rand env))) (arg (value-of-operand rand env))) ; Store thunk as bound operand (apply-procedure proc arg))) ; ... (letrec-exp (p-names b-vars p-bodies letrec-body) (value-of letrec-body (extend-env-rec* p-names b-vars p-bodies env))) (begin-exp (exp1 exps) (letrec ((value-of-begins (lambda (e1 es) (let ((v1 (value-of e1 env))) (if (null? es) v1 (value-of-begins (car es) (cdr es))))))) (value-of-begins exp1 exps))) (assign-exp (var exp1) (begin (setref! (apply-env env var) (value-of exp1 env)) (num-val 27))) ))) (define apply-procedure (lambda (proc1 arg) (cases proc proc1 (procedure (var body saved-env) (let ((r (newref arg))) (let ((new-env (extend-env var r saved-env))) (value-of body new-env)))))))
null
https://raw.githubusercontent.com/KULeuven-CS/CPL/0c62cca832edc43218ac63c4e8233e3c3f05d20a/chapter4/CALL-BY-NEED/CALL-BY-NEED.rkt
racket
(require "store.rkt") proc? : SchemeVal -> Bool procedure : Var * Exp * Env -> Proc expval->num : ExpVal -> Int expval->bool : ExpVal -> Bool expval->proc : ExpVal -> Proc Environments new for implicit-refs apply-env: Env x Var -> Ref n : (maybe int) location : Sym * Listof(Sym) -> Maybe(Int) else (location sym syms) = #f init-env : () -> Env Interpreter ... BASED ON IMPLICIT-REFS ===========CHANGES=FROM=HERE============= Define new thunk datatype Returns the proper bound value references of an operand at function call-time. In the case that this operand is already thunked the reference in the given Env is returned value-of-operand : Exp * Env -> Ref Operand that is already referenced (and thunked) Create new thunk for the actual expression CALL-BY-NAME implementation (var-exp (var) (if (expval? w) w (value-of-thunk w))))) CALL-BY-NEED used Evaluate thunk when the referenced var is one. ... (arg (value-of rand env))) Store thunk as bound operand ...
#lang eopl (require "syntax.rkt") (require "../EXPLICIT-REFS/store.rkt") (provide (all-defined-out)) Semantics (define-datatype expval expval? (num-val (value number?)) (bool-val (boolean boolean?)) (proc-val (proc proc?)) ) (define-datatype proc proc? (procedure (var symbol?) (body expression?) (env environment?))) Page : 70 (define expval->num (lambda (v) (cases expval v (num-val (num) num) (else (expval-extractor-error 'num v))))) Page : 70 (define expval->bool (lambda (v) (cases expval v (bool-val (bool) bool) (else (expval-extractor-error 'bool v))))) (define expval->proc (lambda (v) (cases expval v (proc-val (p) p) (else (expval-extractor-error 'proc v))))) (define expval-extractor-error (lambda (variant value) (eopl:error 'expval-extractors "Looking for a ~s, found ~s" variant value))) (define-datatype environment environment? (empty-env) (extend-env (bvar symbol?) (saved-env environment?)) (extend-env-rec* (proc-names (list-of symbol?)) (b-vars (list-of symbol?)) (proc-bodies (list-of expression?)) (saved-env environment?))) (define apply-env (lambda (env search-sym) (cases environment env (empty-env () (eopl:error 'apply-env "No binding for ~s" search-sym)) (extend-env (bvar bval saved-env) (if (eqv? search-sym bvar) bval (apply-env saved-env search-sym))) (extend-env-rec* (p-names b-vars p-bodies saved-env) (let ((n (location search-sym p-names))) (if n (newref (proc-val (procedure (list-ref b-vars n) (list-ref p-bodies n) env))) (apply-env saved-env search-sym)))) ))) ( location sym syms ) returns the location of sym in syms or # f is sym is not in syms . We can specify this as follows : if ( ) then ( list - ref ( location sym syms ) ) = sym (define location (lambda (sym syms) (cond ((null? syms) #f) ((eqv? sym (car syms)) 0) ((location sym (cdr syms)) => (lambda (n) (+ n 1))) (else #f)))) (define init-env (lambda () (extend-env 'i (newref (num-val 1)) (extend-env 'v (newref (num-val 5)) (extend-env 'x (newref (num-val 10)) (empty-env)))))) value - of - program : Program - > ExpVal Page : 71 (define value-of-program (lambda (pgm) (initialize-store!) (cases program pgm (a-program (exp1) (value-of exp1 (init-env)))))) Additions of CALL - BY - NEED see p 137,138 (define-datatype thunk thunk? (a-thunk (exp1 expression?) (env environment?))) (define value-of-operand (lambda (exp env) (cases expression exp (else Evalutes the given thunk to an actual value . value - of - thunk : Thunk - > ExpVal (define value-of-thunk (lambda (th) (cases thunk th (a-thunk (exp1 saved-env) (value-of exp1 saved-env))))) value - of : Exp * Env - > ExpVal Page : 71 (define value-of (lambda (exp env) (cases expression exp (const-exp (num) (num-val num)) ( let ( ( ref1 ( apply - env env var ) ) ) ( let ( ( w ( deref ref1 ) ) ) (let ((ref1 (apply-env env var))) (let ((w (deref ref1))) (if (expval? w) Referenced is an actual expression already Evaluate thunk and update ref1 (begin (setref! ref1 val1) val1)))))) (diff-exp (exp1 exp2) (let ((val1 (value-of exp1 env)) (val2 (value-of exp2 env))) (let ((num1 (expval->num val1)) (num2 (expval->num val2))) (num-val (- num1 num2))))) (zero?-exp (exp1) (let ((val1 (value-of exp1 env))) (let ((num1 (expval->num val1))) (if (zero? num1) (bool-val #t) (bool-val #f))))) (if-exp (exp1 exp2 exp3) (let ((val1 (value-of exp1 env))) (if (expval->bool val1) (value-of exp2 env) (value-of exp3 env)))) (let-exp (var exp1 body) (let ((v1 (value-of exp1 env))) (value-of body (extend-env var (newref v1) env)))) (proc-exp (var body) (proc-val (procedure var body env))) (call-exp (rator rand) (let ((proc (expval->proc (value-of rator env))) (apply-procedure proc arg))) (letrec-exp (p-names b-vars p-bodies letrec-body) (value-of letrec-body (extend-env-rec* p-names b-vars p-bodies env))) (begin-exp (exp1 exps) (letrec ((value-of-begins (lambda (e1 es) (let ((v1 (value-of e1 env))) (if (null? es) v1 (value-of-begins (car es) (cdr es))))))) (value-of-begins exp1 exps))) (assign-exp (var exp1) (begin (setref! (apply-env env var) (value-of exp1 env)) (num-val 27))) ))) (define apply-procedure (lambda (proc1 arg) (cases proc proc1 (procedure (var body saved-env) (let ((r (newref arg))) (let ((new-env (extend-env var r saved-env))) (value-of body new-env)))))))
5bee3e8bb258ec91892cf9616ff1608e55c3eeeae7d68f233477cdf512ca85b5
myaosato/clcm
inlines.lisp
(defpackage :clcm/inlines/inlines (:use :cl :clcm/utils :clcm/raw-html-regex :clcm/characters :clcm/inlines/parser :clcm/inlines/backslash-escape :clcm/inlines/character-references :clcm/inlines/code-span :clcm/inlines/special-characters :clcm/inlines/html-tag :clcm/inlines/line-break :clcm/inlines/emphasis :clcm/inlines/link-image :clcm/inlines/autolink) (:import-from :cl-ppcre) (:export :inlines->html :inlines->html*)) (in-package :clcm/inlines/inlines) ;; api (defun inlines->html (strings &key last-break) (%inlines->html strings (lambda (parser) (or (scan-backslash-escape parser) (scan-character-references parser) (scan-code-span parser #'inlines->html*) (scan-autolink parser) (scan-html-tag parser) (scan-line-break parser) (scan-emphasis parser) (scan-open-link parser) (scan-open-image parser) (scan-close-link-image parser) (scan-special-characters parser) (push-chars parser (read-c parser)))) last-break)) (defun inlines->html* (strings &key last-break) ;; only ;; < -> &lt; ;; > -> &gt; ;; & -> &amp; ;; " -> &quot; (%inlines->html strings (lambda (parser) (or (scan-special-characters parser) (push-chars parser (read-c parser)))) last-break)) ;; main functions (defun %inlines->html (strings proc last-break) (if (null strings) (return-from %inlines->html "")) (let* ((chars (format nil "~{~A~^~%~}~A" strings (if last-break #\Newline ""))) (parser (make-inlines-parser :input chars))) (loop :while (peek-c parser) :do (funcall proc parser)) (process-emphasis parser) (output parser))) (defun output (parser) (format nil "~A" (ip-queue parser)))
null
https://raw.githubusercontent.com/myaosato/clcm/fd0390bedf00c5be3f5c2eb8176ff73bede797b0/src/inlines/inlines.lisp
lisp
api only < -> &lt; > -> &gt; & -> &amp; " -> &quot; main functions
(defpackage :clcm/inlines/inlines (:use :cl :clcm/utils :clcm/raw-html-regex :clcm/characters :clcm/inlines/parser :clcm/inlines/backslash-escape :clcm/inlines/character-references :clcm/inlines/code-span :clcm/inlines/special-characters :clcm/inlines/html-tag :clcm/inlines/line-break :clcm/inlines/emphasis :clcm/inlines/link-image :clcm/inlines/autolink) (:import-from :cl-ppcre) (:export :inlines->html :inlines->html*)) (in-package :clcm/inlines/inlines) (defun inlines->html (strings &key last-break) (%inlines->html strings (lambda (parser) (or (scan-backslash-escape parser) (scan-character-references parser) (scan-code-span parser #'inlines->html*) (scan-autolink parser) (scan-html-tag parser) (scan-line-break parser) (scan-emphasis parser) (scan-open-link parser) (scan-open-image parser) (scan-close-link-image parser) (scan-special-characters parser) (push-chars parser (read-c parser)))) last-break)) (defun inlines->html* (strings &key last-break) (%inlines->html strings (lambda (parser) (or (scan-special-characters parser) (push-chars parser (read-c parser)))) last-break)) (defun %inlines->html (strings proc last-break) (if (null strings) (return-from %inlines->html "")) (let* ((chars (format nil "~{~A~^~%~}~A" strings (if last-break #\Newline ""))) (parser (make-inlines-parser :input chars))) (loop :while (peek-c parser) :do (funcall proc parser)) (process-emphasis parser) (output parser))) (defun output (parser) (format nil "~A" (ip-queue parser)))
7ee06e05478279a36537ab7fd8af341ee9228ad1a5af490b94e32113e2151834
gwkkwg/metatilities
package.lisp
(in-package #:common-lisp-user) (defpackage #:metatilities-base-test (:use #:common-lisp #:lift #:metatilities) (:import-from #:metatilities #:*automatic-slot-accessors?* #:*automatic-slot-initargs?* #:*prune-unknown-slot-options*))
null
https://raw.githubusercontent.com/gwkkwg/metatilities/82e13df0545d0e47ae535ea35c5c99dd3a44e69e/tests/unit-tests/package.lisp
lisp
(in-package #:common-lisp-user) (defpackage #:metatilities-base-test (:use #:common-lisp #:lift #:metatilities) (:import-from #:metatilities #:*automatic-slot-accessors?* #:*automatic-slot-initargs?* #:*prune-unknown-slot-options*))
a46662364b7645c72600431e39fef68df0906244961ded1ccf2a0e13e7283d70
ruhler/smten
STP.hs
# LANGUAGE NoImplicitPrelude # | This module provides the STP backend for smten . module Smten.Search.Solver.STP (stp) where import Smten.Plugin.Annotations import Smten.Prelude import Smten.Search.Prim # ANN module PrimitiveModule # | The STP smten solver stp :: Solver stp = primitive "Smten.Search.Solver.STP.stp"
null
https://raw.githubusercontent.com/ruhler/smten/16dd37fb0ee3809408803d4be20401211b6c4027/smten-stp/Smten/Search/Solver/STP.hs
haskell
# LANGUAGE NoImplicitPrelude # | This module provides the STP backend for smten . module Smten.Search.Solver.STP (stp) where import Smten.Plugin.Annotations import Smten.Prelude import Smten.Search.Prim # ANN module PrimitiveModule # | The STP smten solver stp :: Solver stp = primitive "Smten.Search.Solver.STP.stp"
078b91e8552c4febd841a6455984d92540e67a73fda1b26387bb1ced30bbec70
gelisam/frp-zoo
Main.hs
module Main where import Control.Applicative import Control.DysFRP import Graphics.Gloss.Interface.IO.Game hiding (Event) import Buttons import GlossInterface Utilities if_then_else :: Bool -> a -> a -> a if_then_else True t _ = t if_then_else False _ f = f replaceWith :: a -> Event b -> Event a replaceWith = fmap . const filterEq :: Eq a => a -> Event a -> Event () filterEq x = replaceWith () . filterE (== x) eachE :: Event () -> a -> Event a eachE = flip replaceWith -- FRP network mainDysFRP :: Event Float -> Event InputEvent -> BehaviorGen Picture mainDysFRP _ glossEvent = do -- Part 1: static version -- mode0 <- accumB True $ constE not toggle0 mode5 <- accumB True $ constE not toggle5 mode10 <- accumB True $ constE not toggle10 count0 <- accumB 0 $ constE (+1) click0 `appendE` constE (const 0) toggle0 count5 <- accumB 0 $ whenE mode5 $ constE (+1) click5 count10 <- accumB 0 $ constE (+1) click10 let output0 = if_then_else <$> mode0 <*> count0 <*> minus1 let output5 = if_then_else <$> mode5 <*> count5 <*> minus1 let output10 = if_then_else <$> mode10 <*> count10 <*> minus1 let counterB click = accumB 0 $ constE (+1) click Part 2 : dynamic version -- scenario 0: new counter created each time initCount0 <- counterB click0 dynamicCount0 <- switchB initCount0 $ genToE (\b -> if b then -1 else counterB click0) $ snapshotE mode0 $ toggle0 scenario 10 : re - using the first counter initCount10 <- counterB click10 dynamicCount10 <- switchB initCount10 $ fmap (\b -> if b then -1 else initCount10) $ snapshotE mode10 $ toggle10 return $ renderButtons <$> output0 <*> (Just <$> dynamicCount0) <*> output5 <*> pure Nothing <*> output10 <*> (Just <$> dynamicCount10) where minus1 = constB (-1) -- Input click0, click5, click10 :: Event () click0 = filterEq (Just Click) $ filter0 <$> glossEvent click5 = filterEq (Just Click) $ filter5 <$> glossEvent click10 = filterEq (Just Click) $ filter10 <$> glossEvent toggle0, toggle5, toggle10 :: Event () toggle0 = filterEq (Just Toggle) $ filter0 <$> glossEvent toggle5 = filterEq (Just Toggle) $ filter5 <$> glossEvent toggle10 = filterEq (Just Toggle) $ filter10 <$> glossEvent -- Gloss event loop main :: IO () main = playDysFRP (InWindow "DysFRP Example" (320, 240) (800, 200)) white 30 mainDysFRP
null
https://raw.githubusercontent.com/gelisam/frp-zoo/1a1704e4294b17a1c6e4b417a73e61216bad2321/DysFRP-example/Main.hs
haskell
FRP network Part 1: static version scenario 0: new counter created each time Input Gloss event loop
module Main where import Control.Applicative import Control.DysFRP import Graphics.Gloss.Interface.IO.Game hiding (Event) import Buttons import GlossInterface Utilities if_then_else :: Bool -> a -> a -> a if_then_else True t _ = t if_then_else False _ f = f replaceWith :: a -> Event b -> Event a replaceWith = fmap . const filterEq :: Eq a => a -> Event a -> Event () filterEq x = replaceWith () . filterE (== x) eachE :: Event () -> a -> Event a eachE = flip replaceWith mainDysFRP :: Event Float -> Event InputEvent -> BehaviorGen Picture mainDysFRP _ glossEvent = do mode0 <- accumB True $ constE not toggle0 mode5 <- accumB True $ constE not toggle5 mode10 <- accumB True $ constE not toggle10 count0 <- accumB 0 $ constE (+1) click0 `appendE` constE (const 0) toggle0 count5 <- accumB 0 $ whenE mode5 $ constE (+1) click5 count10 <- accumB 0 $ constE (+1) click10 let output0 = if_then_else <$> mode0 <*> count0 <*> minus1 let output5 = if_then_else <$> mode5 <*> count5 <*> minus1 let output10 = if_then_else <$> mode10 <*> count10 <*> minus1 let counterB click = accumB 0 $ constE (+1) click Part 2 : dynamic version initCount0 <- counterB click0 dynamicCount0 <- switchB initCount0 $ genToE (\b -> if b then -1 else counterB click0) $ snapshotE mode0 $ toggle0 scenario 10 : re - using the first counter initCount10 <- counterB click10 dynamicCount10 <- switchB initCount10 $ fmap (\b -> if b then -1 else initCount10) $ snapshotE mode10 $ toggle10 return $ renderButtons <$> output0 <*> (Just <$> dynamicCount0) <*> output5 <*> pure Nothing <*> output10 <*> (Just <$> dynamicCount10) where minus1 = constB (-1) click0, click5, click10 :: Event () click0 = filterEq (Just Click) $ filter0 <$> glossEvent click5 = filterEq (Just Click) $ filter5 <$> glossEvent click10 = filterEq (Just Click) $ filter10 <$> glossEvent toggle0, toggle5, toggle10 :: Event () toggle0 = filterEq (Just Toggle) $ filter0 <$> glossEvent toggle5 = filterEq (Just Toggle) $ filter5 <$> glossEvent toggle10 = filterEq (Just Toggle) $ filter10 <$> glossEvent main :: IO () main = playDysFRP (InWindow "DysFRP Example" (320, 240) (800, 200)) white 30 mainDysFRP
69ad1a4d85311a828a36aa94e9110ec2b4022d31872b92bbb2ea65004738f37e
05st/artemis
BuiltIn.hs
module BuiltIn (defTEnv, defEnv) where import Data.Functor import qualified Data.Set as Set import qualified Data.Map as Map import Data.Char import Data.Time import Data.Time.Clock.POSIX import System.IO import Type import Value import Name -- Built-in functions, type checker guarantees that these patterns are matched addInt [VInt a, VInt b] = return $ VInt (a + b) subInt [VInt a, VInt b] = return $ VInt (a - b) mulInt [VInt a, VInt b] = return $ VInt (a * b) divInt [VInt a, VInt b] = return $ VInt (a `div` b) floor' [VFloat a] = return $ VInt (floor a) ordChar [VChar c] = return $ VInt (fromIntegral (ord c)) addFloat [VFloat a, VFloat b] = return $ VFloat (a + b) subFloat [VFloat a, VFloat b] = return $ VFloat (a - b) mulFloat [VFloat a, VFloat b] = return $ VFloat (a * b) divFloat [VFloat a, VFloat b] = return $ VFloat (a / b) intToFloat [VInt a] = return $ VFloat (fromIntegral a) eqInt [VInt a, VInt b] = return $ VBool (a == b) eqFloat [VFloat a, VFloat b] = return $ VBool (a == b) eqBool [VBool a, VBool b] = return $ VBool (a == b) eqChar [VChar a, VChar b] = return $ VBool (a == b) leqInt [VInt a, VInt b] = return $ VBool (a <= b) showInt [VInt a] = return $ fromString (show a) showFloat [VFloat a] = return $ fromString (show a) showBool [VBool a] = return $ fromString $ if a then "true" else "false" showChar' [VChar a] = return $ fromString (show a) showUnit [VUnit] = return $ fromString "()" readInt [a] = return $ VInt (read $ toString a) readFloat [a] = return $ VFloat (read $ toString a) print' [a] = putStr (toString a) >> hFlush stdout >> return VUnit error' [a] = Prelude.error $ "ERROR: " ++ toString a clock [a] = getCurrentTime <&> VInt . floor . (1e9 *) . nominalDiffTimeToSeconds . utcTimeToPOSIXSeconds input [a] = getLine <&> fromString -- Helper function Turns a List < char > into a Haskell [ ] toString :: Value -> String toString (VData (Qualified _ "Cons") [VChar c, n]) = c : toString n toString (VData (Qualified _"Empty") []) = [] toString _ = error "Not possible" fromString :: String -> Value fromString (c : cs) = VData (Qualified (Relative Global "std") "Cons") [VChar c, fromString cs] fromString [] = VData (Qualified (Relative Global "std") "Empty") [] builtIn :: String -> ([Value] -> IO Value) -> Int -> [TVar] -> Type -> (String, Value, Scheme, Bool) builtIn name fn arity vs t = (name, VFunc (BuiltIn arity [] fn), Forall (Set.fromList vs) t, False) toQualified :: String -> QualifiedName toQualified = Qualified Global builtIns :: [(String, Value, Scheme, Bool)] builtIns = [ builtIn "addInt" addInt 2 [] (TInt :-> (TInt :-> TInt)), builtIn "subInt" subInt 2 [] (TInt :-> (TInt :-> TInt)), builtIn "mulInt" mulInt 2 [] (TInt :-> (TInt :-> TInt)), builtIn "divInt" divInt 2 [] (TInt :-> (TInt :-> TInt)), builtIn "floor" floor' 1 [] (TFloat :-> TInt), builtIn "ordChar" ordChar 1 [] (TChar :-> TInt), builtIn "addFloat" addFloat 2 [] (TFloat :-> (TFloat :-> TFloat)), builtIn "subFloat" subFloat 2 [] (TFloat :-> (TFloat :-> TFloat)), builtIn "mulFloat" mulFloat 2 [] (TFloat :-> (TFloat :-> TFloat)), builtIn "divFloat" divFloat 2 [] (TFloat :-> (TFloat :-> TFloat)), builtIn "intToFloat" intToFloat 1 [] (TInt :-> TFloat), builtIn "eqInt" eqInt 2 [] (TInt :-> (TInt :-> TBool)), builtIn "leqInt" leqInt 2 [] (TInt :-> (TInt :-> TBool)), builtIn "eqFloat" eqFloat 2 [] (TFloat :-> (TFloat :-> TBool)), builtIn "eqBool" eqBool 2 [] (TBool :-> (TBool :-> TBool)), builtIn "eqChar" eqChar 2 [] (TChar :-> (TChar :-> TBool)), builtIn "showInt" showInt 1 [] (TInt :-> TList TChar), builtIn "showFloat" showFloat 1 [] (TFloat :-> TList TChar), builtIn "showBool" showBool 1 [] (TBool :-> TList TChar), builtIn "showChar" showChar' 1 [] (TChar :-> TList TChar), builtIn "showUnit" showUnit 1 [] (TUnit :-> TList TChar), builtIn "readInt" readInt 1 [] (TList TChar :-> TInt), builtIn "readFloat" readFloat 1 [] (TList TChar :-> TFloat), builtIn "print" print' 1 [] (TList TChar :-> TUnit), builtIn "error" error' 1 [TV "a" Star] (TList TChar :-> TVar (TV "a" Star)), builtIn "clock" clock 1 [] (TUnit :-> TInt), builtIn "input" input 1 [] (TUnit :-> TList TChar) ] defTEnv :: TEnv defTEnv = Map.fromList $ map (\(i, _, s, m) -> (toQualified i, (s, m))) builtIns defEnv :: Env defEnv = Map.fromList $ map (\(i, v, _, _) -> (toQualified i, v)) builtIns
null
https://raw.githubusercontent.com/05st/artemis/4d329a8e221076678a44fa29913a59892bb1b2ab/src/BuiltIn.hs
haskell
Built-in functions, type checker guarantees that these patterns are matched Helper function
module BuiltIn (defTEnv, defEnv) where import Data.Functor import qualified Data.Set as Set import qualified Data.Map as Map import Data.Char import Data.Time import Data.Time.Clock.POSIX import System.IO import Type import Value import Name addInt [VInt a, VInt b] = return $ VInt (a + b) subInt [VInt a, VInt b] = return $ VInt (a - b) mulInt [VInt a, VInt b] = return $ VInt (a * b) divInt [VInt a, VInt b] = return $ VInt (a `div` b) floor' [VFloat a] = return $ VInt (floor a) ordChar [VChar c] = return $ VInt (fromIntegral (ord c)) addFloat [VFloat a, VFloat b] = return $ VFloat (a + b) subFloat [VFloat a, VFloat b] = return $ VFloat (a - b) mulFloat [VFloat a, VFloat b] = return $ VFloat (a * b) divFloat [VFloat a, VFloat b] = return $ VFloat (a / b) intToFloat [VInt a] = return $ VFloat (fromIntegral a) eqInt [VInt a, VInt b] = return $ VBool (a == b) eqFloat [VFloat a, VFloat b] = return $ VBool (a == b) eqBool [VBool a, VBool b] = return $ VBool (a == b) eqChar [VChar a, VChar b] = return $ VBool (a == b) leqInt [VInt a, VInt b] = return $ VBool (a <= b) showInt [VInt a] = return $ fromString (show a) showFloat [VFloat a] = return $ fromString (show a) showBool [VBool a] = return $ fromString $ if a then "true" else "false" showChar' [VChar a] = return $ fromString (show a) showUnit [VUnit] = return $ fromString "()" readInt [a] = return $ VInt (read $ toString a) readFloat [a] = return $ VFloat (read $ toString a) print' [a] = putStr (toString a) >> hFlush stdout >> return VUnit error' [a] = Prelude.error $ "ERROR: " ++ toString a clock [a] = getCurrentTime <&> VInt . floor . (1e9 *) . nominalDiffTimeToSeconds . utcTimeToPOSIXSeconds input [a] = getLine <&> fromString Turns a List < char > into a Haskell [ ] toString :: Value -> String toString (VData (Qualified _ "Cons") [VChar c, n]) = c : toString n toString (VData (Qualified _"Empty") []) = [] toString _ = error "Not possible" fromString :: String -> Value fromString (c : cs) = VData (Qualified (Relative Global "std") "Cons") [VChar c, fromString cs] fromString [] = VData (Qualified (Relative Global "std") "Empty") [] builtIn :: String -> ([Value] -> IO Value) -> Int -> [TVar] -> Type -> (String, Value, Scheme, Bool) builtIn name fn arity vs t = (name, VFunc (BuiltIn arity [] fn), Forall (Set.fromList vs) t, False) toQualified :: String -> QualifiedName toQualified = Qualified Global builtIns :: [(String, Value, Scheme, Bool)] builtIns = [ builtIn "addInt" addInt 2 [] (TInt :-> (TInt :-> TInt)), builtIn "subInt" subInt 2 [] (TInt :-> (TInt :-> TInt)), builtIn "mulInt" mulInt 2 [] (TInt :-> (TInt :-> TInt)), builtIn "divInt" divInt 2 [] (TInt :-> (TInt :-> TInt)), builtIn "floor" floor' 1 [] (TFloat :-> TInt), builtIn "ordChar" ordChar 1 [] (TChar :-> TInt), builtIn "addFloat" addFloat 2 [] (TFloat :-> (TFloat :-> TFloat)), builtIn "subFloat" subFloat 2 [] (TFloat :-> (TFloat :-> TFloat)), builtIn "mulFloat" mulFloat 2 [] (TFloat :-> (TFloat :-> TFloat)), builtIn "divFloat" divFloat 2 [] (TFloat :-> (TFloat :-> TFloat)), builtIn "intToFloat" intToFloat 1 [] (TInt :-> TFloat), builtIn "eqInt" eqInt 2 [] (TInt :-> (TInt :-> TBool)), builtIn "leqInt" leqInt 2 [] (TInt :-> (TInt :-> TBool)), builtIn "eqFloat" eqFloat 2 [] (TFloat :-> (TFloat :-> TBool)), builtIn "eqBool" eqBool 2 [] (TBool :-> (TBool :-> TBool)), builtIn "eqChar" eqChar 2 [] (TChar :-> (TChar :-> TBool)), builtIn "showInt" showInt 1 [] (TInt :-> TList TChar), builtIn "showFloat" showFloat 1 [] (TFloat :-> TList TChar), builtIn "showBool" showBool 1 [] (TBool :-> TList TChar), builtIn "showChar" showChar' 1 [] (TChar :-> TList TChar), builtIn "showUnit" showUnit 1 [] (TUnit :-> TList TChar), builtIn "readInt" readInt 1 [] (TList TChar :-> TInt), builtIn "readFloat" readFloat 1 [] (TList TChar :-> TFloat), builtIn "print" print' 1 [] (TList TChar :-> TUnit), builtIn "error" error' 1 [TV "a" Star] (TList TChar :-> TVar (TV "a" Star)), builtIn "clock" clock 1 [] (TUnit :-> TInt), builtIn "input" input 1 [] (TUnit :-> TList TChar) ] defTEnv :: TEnv defTEnv = Map.fromList $ map (\(i, _, s, m) -> (toQualified i, (s, m))) builtIns defEnv :: Env defEnv = Map.fromList $ map (\(i, v, _, _) -> (toQualified i, v)) builtIns
d2134f61709eee37acd602c16cb1fc1cf13c477fcb4b1fcee629c52fd4f751f7
bzliu94/cs61a_fa07
lab3.scm
(define (substitute sent old_wd new_wd) (substitute-helper () sent old_wd new_wd)) (define (substitute-helper next_sent sent old_wd new_wd) (if (empty? sent) next_sent (let ((curr_wd (first sent))) (let ((substituted_curr_wd (get-next-word curr_wd old_wd new_wd))) (let ((next_next_sent (sentence next_sent substituted_curr_wd))) (substitute-helper next_next_sent (bf sent) old_wd new_wd)))))) (define (get-next-word curr_wd old_wd new_wd) (if (equal? old_wd curr_wd) new_wd curr_wd)) (define (g) (lambda (x) 3)) ;; return type is function f , ( f ) , ( f 3 ) , ( ( f ) ) , ( ( ( f ) ) 3 ) ;; f - value or function taking any number of arguments ;; (f) - function taking no arguments ( f 3 ) - function taking one argument ;; ((f)) - function taking no argument that returns a function taking no argument ( ( ( f ) ) 3 ) - function taking no argument that returns a function taking no argument that returns a function taking one argument ( ( t 1 + ) 0 ) does 1 + three times ( ( t ( t 1 + ) ) 0 ) does 1 + 3 * 3 times ( ( ( t t ) 1 + ) 0 ) does 1 + 3 ^ 3 times ( ( t 1 + ) 0 ) = ( 1 + ( 1 + ( 1 + 0 ) ) ) = 3 ;; ((t (t 1+)) 0) = ((t (lambda (x) (1+ (1+ (1+ x))))) 0) ;; = ((lambda (y) (lambda (x) (1+ (1+ (1+ y))))) ;; ((lambda (y) (lambda (x) (1+ (1+ (1+ y))))) ;; (lambda (y) (lambda (x) (1+ (1+ (1+ y)))))) 0) = ( ... ( ... 3 ) ) = ( ... 6 ) = 9 ( ( ( t t ) 1 + ) 0 ) = ( ( lambda ( x ) ( t ( t ( t x ) ) ) 1 + ) 0 ) = ( ( ( lambda ( x ) ( t ( t ( t x ) ) ) ) 1 + ) 0 ) ;; = ((lambda (x) ((lambda (a) (a (a (a x)))) (lambda (b) (b (b (b x))) (lambda (c) (c (c (c x))))))) 0) ;; = (... (... (... 0))) = ( ... ( ... 3 ) ) = ( ... 9 ) = 27 (define (t f) (lambda (x) (f (f (f x))))) ( ( t s ) 0 ) does 1 + three times ( ( t ( t s ) ) 0 ) does 1 + 3 * 3 times ( ( ( t t ) s ) 0 ) does 1 + 3 ^ 3 times ;; ((t s) 0) ;; ((t (t s)) 0) ;; (((t t) s) 0) (define (s x) (+ 1 x)) (define (make-tester w) (lambda (x) (if (equal? w x) #t #f)))
null
https://raw.githubusercontent.com/bzliu94/cs61a_fa07/12a62689f149ef035a36b326351928928f6e7b5d/02%20-%20labs/lab3/lab3.scm
scheme
return type is function f - value or function taking any number of arguments (f) - function taking no arguments ((f)) - function taking no argument that returns a function taking no argument ((t (t 1+)) 0) = ((t (lambda (x) (1+ (1+ (1+ x))))) 0) = ((lambda (y) (lambda (x) (1+ (1+ (1+ y))))) ((lambda (y) (lambda (x) (1+ (1+ (1+ y))))) (lambda (y) (lambda (x) (1+ (1+ (1+ y)))))) 0) = ((lambda (x) ((lambda (a) (a (a (a x)))) (lambda (b) (b (b (b x))) (lambda (c) (c (c (c x))))))) 0) = (... (... (... 0))) ((t s) 0) ((t (t s)) 0) (((t t) s) 0)
(define (substitute sent old_wd new_wd) (substitute-helper () sent old_wd new_wd)) (define (substitute-helper next_sent sent old_wd new_wd) (if (empty? sent) next_sent (let ((curr_wd (first sent))) (let ((substituted_curr_wd (get-next-word curr_wd old_wd new_wd))) (let ((next_next_sent (sentence next_sent substituted_curr_wd))) (substitute-helper next_next_sent (bf sent) old_wd new_wd)))))) (define (get-next-word curr_wd old_wd new_wd) (if (equal? old_wd curr_wd) new_wd curr_wd)) (define (g) (lambda (x) 3)) f , ( f ) , ( f 3 ) , ( ( f ) ) , ( ( ( f ) ) 3 ) ( f 3 ) - function taking one argument ( ( ( f ) ) 3 ) - function taking no argument that returns a function taking no argument that returns a function taking one argument ( ( t 1 + ) 0 ) does 1 + three times ( ( t ( t 1 + ) ) 0 ) does 1 + 3 * 3 times ( ( ( t t ) 1 + ) 0 ) does 1 + 3 ^ 3 times ( ( t 1 + ) 0 ) = ( 1 + ( 1 + ( 1 + 0 ) ) ) = 3 = ( ... ( ... 3 ) ) = ( ... 6 ) = 9 ( ( ( t t ) 1 + ) 0 ) = ( ( lambda ( x ) ( t ( t ( t x ) ) ) 1 + ) 0 ) = ( ( ( lambda ( x ) ( t ( t ( t x ) ) ) ) 1 + ) 0 ) = ( ... ( ... 3 ) ) = ( ... 9 ) = 27 (define (t f) (lambda (x) (f (f (f x))))) ( ( t s ) 0 ) does 1 + three times ( ( t ( t s ) ) 0 ) does 1 + 3 * 3 times ( ( ( t t ) s ) 0 ) does 1 + 3 ^ 3 times (define (s x) (+ 1 x)) (define (make-tester w) (lambda (x) (if (equal? w x) #t #f)))
8510e41753c43ff4d686ab21efbe7d24169946ac74cf69a0799b2e9661f88b37
kadena-io/chainweaver
Api.hs
# LANGUAGE LambdaCase # {-# LANGUAGE OverloadedStrings #-} module Common.Api where import Data.Text (Text) import qualified Data.Text as T import qualified Data.Text.Encoding as T import qualified Data.Text.Encoding.Error as T import Obelisk.Configs -- | Where to find the network list configuration, under config/common verificationServerPath :: Text verificationServerPath = "common/verification-server" | Get the normalized url of the remote verification server suitable for Pact . getVerificationServerUrl :: HasConfigs m => m (Maybe Text) getVerificationServerUrl = do mUri <- getConfig verificationServerPath pure $ T.dropWhileEnd (== '/') . T.decodeUtf8With T.lenientDecode <$> mUri -- | Get "config/common/route" normalized. getConfigRoute :: HasConfigs m => m Text getConfigRoute = T.dropWhileEnd (== '/') <$> getMandatoryTextCfg "common/route" getTextCfg :: HasConfigs m => Text -> m (Maybe Text) getTextCfg p = fmap (T.strip . T.decodeUtf8With T.lenientDecode) <$> getConfig p getMandatoryTextCfg :: HasConfigs m => Text -> m Text getMandatoryTextCfg p = getTextCfg p >>= \case Nothing -> fail $ "Obelisk.ExecutableConfig, could not find: '" <> T.unpack p <> "'!" Just r -> pure r
null
https://raw.githubusercontent.com/kadena-io/chainweaver/3ea0bb317c07ddf954d4ebf24b33d1be7d5f9c45/common/src/Common/Api.hs
haskell
# LANGUAGE OverloadedStrings # | Where to find the network list configuration, under config/common | Get "config/common/route" normalized.
# LANGUAGE LambdaCase # module Common.Api where import Data.Text (Text) import qualified Data.Text as T import qualified Data.Text.Encoding as T import qualified Data.Text.Encoding.Error as T import Obelisk.Configs verificationServerPath :: Text verificationServerPath = "common/verification-server" | Get the normalized url of the remote verification server suitable for Pact . getVerificationServerUrl :: HasConfigs m => m (Maybe Text) getVerificationServerUrl = do mUri <- getConfig verificationServerPath pure $ T.dropWhileEnd (== '/') . T.decodeUtf8With T.lenientDecode <$> mUri getConfigRoute :: HasConfigs m => m Text getConfigRoute = T.dropWhileEnd (== '/') <$> getMandatoryTextCfg "common/route" getTextCfg :: HasConfigs m => Text -> m (Maybe Text) getTextCfg p = fmap (T.strip . T.decodeUtf8With T.lenientDecode) <$> getConfig p getMandatoryTextCfg :: HasConfigs m => Text -> m Text getMandatoryTextCfg p = getTextCfg p >>= \case Nothing -> fail $ "Obelisk.ExecutableConfig, could not find: '" <> T.unpack p <> "'!" Just r -> pure r
2923b1c8f9d4be3b3590c440cec97e7c10ca6f63ea82bc444fd8b18be6b734b6
emqx/quic
example_server_stream.erl
%%-------------------------------------------------------------------- Copyright ( c ) 2022 EMQ Technologies Co. , Ltd. All Rights Reserved . %% Licensed under the Apache License , Version 2.0 ( the " License " ) ; %% you may not use this file except in compliance with the License. %% You may obtain a copy of the License at %% %% -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(example_server_stream). -behavior(quicer_stream). -export([ init_handoff/4 , post_handoff/3 , new_stream/3 , start_completed/3 , send_complete/3 , peer_send_shutdown/3 , peer_send_aborted/3 , peer_receive_aborted/3 , send_shutdown_complete/3 , stream_closed/3 , peer_accepted/3 , passive/3 ]). -export([handle_stream_data/4]). -export([handle_call/3]). -include("quicer.hrl"). -include_lib("snabbkaffe/include/snabbkaffe.hrl"). init_handoff(Stream, StreamOpts, Conn, #{flags := Flags}) -> InitState = #{ stream => Stream , conn => Conn , peer_stream => undefined , is_local => false , is_unidir => quicer:is_unidirectional(Flags) }, ct:pal("init_handoff ~p", [{InitState, StreamOpts}]), {ok, InitState}. post_handoff(Stream, _PostData, State) -> ok = quicer:setopt(Stream, active, true), {ok, State}. new_stream(Stream, #{flags := Flags}, Conn) -> InitState = #{ stream => Stream , conn => Conn , peer_stream => undefined , is_local => false , is_unidir => quicer:is_unidirectional(Flags)}, {ok, InitState}. peer_accepted(_Stream, _Flags, S) -> %% we just ignore it {ok, S}. peer_receive_aborted(Stream, ErrorCode, #{is_unidir := false} = S) -> %% we abort send with same reason quicer:async_shutdown_stream(Stream, ?QUIC_STREAM_SHUTDOWN_FLAG_ABORT, ErrorCode), {ok, S}; peer_receive_aborted(Stream, ErrorCode, #{is_unidir := true, is_local := true} = S) -> quicer:async_shutdown_stream(Stream, ?QUIC_STREAM_SHUTDOWN_FLAG_ABORT, ErrorCode), {ok, S}. peer_send_aborted(Stream, ErrorCode, #{is_unidir := false} = S) -> %% we abort receive with same reason quicer:async_shutdown_stream(Stream, ?QUIC_STREAM_SHUTDOWN_FLAG_ABORT_RECEIVE, ErrorCode), {ok, S}; peer_send_aborted(Stream, ErrorCode, #{is_unidir := true, is_local := false} = S) -> quicer:async_shutdown_stream(Stream, ?QUIC_STREAM_SHUTDOWN_FLAG_ABORT_RECEIVE, ErrorCode), {ok, S}. peer_send_shutdown(Stream, _Flags, S) -> ok = quicer:async_shutdown_stream(Stream, ?QUIC_STREAM_SHUTDOWN_FLAG_GRACEFUL, 0), {ok, S}. send_complete(_Stream, false, S) -> {ok, S}; send_complete(_Stream, true = _IsCanceled, S) -> ct:pal("~p : send is canceled", [?FUNCTION_NAME]), {ok, S}. send_shutdown_complete(_Stream, _Flags, S) -> ct:pal("~p : stream send is complete", [?FUNCTION_NAME]), {ok, S}. start_completed(_Stream, #{status := success, stream_id := StreamId}, S) -> {ok, S#{stream_id => StreamId}}; start_completed(_Stream, #{status := Other }, S) -> %% or we could retry {stop, {start_fail, Other}, S}. handle_stream_data(Stream, <<"flow_control.enable_bidi">> = Bin, _Flags, #{is_unidir := true, conn := Conn} = State) -> ?tp(debug, #{stream => Stream, data => Bin, module => ?MODULE, dir => unidir}), ok = quicer:setopt(Conn, param_conn_settings, #{peer_bidi_stream_count => 2}), {ok, State}; handle_stream_data(Stream, Bin, _Flags, #{is_unidir := false} = State) -> for bidir stream , we just echo in place . ?tp(debug, #{stream => Stream, data => Bin, module => ?MODULE, dir => bidir}), ct:pal("Server recv: ~p from ~p", [Bin, Stream] ), {ok, _} = quicer:send(Stream, Bin), {ok, State}; handle_stream_data(Stream, Bin, _Flags, #{is_unidir := true, peer_stream := PeerStream, conn := Conn} = State) -> ?tp(debug, #{stream => Stream, data => Bin, module => ?MODULE, dir => unidir}), ct:pal("Server recv: ~p from ~p", [Bin, Stream] ), case PeerStream of undefined -> {ok, StreamProc} = quicer_stream:start_link(?MODULE, Conn, [ {open_flag, ?QUIC_STREAM_OPEN_FLAG_UNIDIRECTIONAL} , {is_local, true} ]), {ok, _} = quicer_stream:send(StreamProc, Bin), {ok, State#{peer_stream := StreamProc}}; StreamProc when is_pid(StreamProc) -> {ok, _} = quicer_stream:send(StreamProc, Bin), {ok, State} end. passive(_Stream, undefined, S)-> ct:fail("Steam go into passive mode"), {ok, S}. stream_closed(_Stream, #{ is_conn_shutdown := IsConnShutdown , is_app_closing := IsAppClosing , is_shutdown_by_app := IsAppShutdown , is_closed_remotely := IsRemote , status := Status , error := Code }, S) when is_boolean(IsConnShutdown) andalso is_boolean(IsAppClosing) andalso is_boolean(IsAppShutdown) andalso is_boolean(IsRemote) andalso is_atom(Status) andalso is_integer(Code) -> {stop, normal, S}. handle_call(_Request, _From, S) -> {reply, {error, not_impl}, S}.
null
https://raw.githubusercontent.com/emqx/quic/dc4746944acbc3f93572baebea5ff25071f2e09b/test/example_server_stream.erl
erlang
-------------------------------------------------------------------- you may not use this file except in compliance with the License. You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing, software 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. -------------------------------------------------------------------- we just ignore it we abort send with same reason we abort receive with same reason or we could retry
Copyright ( c ) 2022 EMQ Technologies Co. , Ltd. All Rights Reserved . Licensed under the Apache License , Version 2.0 ( the " License " ) ; distributed under the License is distributed on an " AS IS " BASIS , -module(example_server_stream). -behavior(quicer_stream). -export([ init_handoff/4 , post_handoff/3 , new_stream/3 , start_completed/3 , send_complete/3 , peer_send_shutdown/3 , peer_send_aborted/3 , peer_receive_aborted/3 , send_shutdown_complete/3 , stream_closed/3 , peer_accepted/3 , passive/3 ]). -export([handle_stream_data/4]). -export([handle_call/3]). -include("quicer.hrl"). -include_lib("snabbkaffe/include/snabbkaffe.hrl"). init_handoff(Stream, StreamOpts, Conn, #{flags := Flags}) -> InitState = #{ stream => Stream , conn => Conn , peer_stream => undefined , is_local => false , is_unidir => quicer:is_unidirectional(Flags) }, ct:pal("init_handoff ~p", [{InitState, StreamOpts}]), {ok, InitState}. post_handoff(Stream, _PostData, State) -> ok = quicer:setopt(Stream, active, true), {ok, State}. new_stream(Stream, #{flags := Flags}, Conn) -> InitState = #{ stream => Stream , conn => Conn , peer_stream => undefined , is_local => false , is_unidir => quicer:is_unidirectional(Flags)}, {ok, InitState}. peer_accepted(_Stream, _Flags, S) -> {ok, S}. peer_receive_aborted(Stream, ErrorCode, #{is_unidir := false} = S) -> quicer:async_shutdown_stream(Stream, ?QUIC_STREAM_SHUTDOWN_FLAG_ABORT, ErrorCode), {ok, S}; peer_receive_aborted(Stream, ErrorCode, #{is_unidir := true, is_local := true} = S) -> quicer:async_shutdown_stream(Stream, ?QUIC_STREAM_SHUTDOWN_FLAG_ABORT, ErrorCode), {ok, S}. peer_send_aborted(Stream, ErrorCode, #{is_unidir := false} = S) -> quicer:async_shutdown_stream(Stream, ?QUIC_STREAM_SHUTDOWN_FLAG_ABORT_RECEIVE, ErrorCode), {ok, S}; peer_send_aborted(Stream, ErrorCode, #{is_unidir := true, is_local := false} = S) -> quicer:async_shutdown_stream(Stream, ?QUIC_STREAM_SHUTDOWN_FLAG_ABORT_RECEIVE, ErrorCode), {ok, S}. peer_send_shutdown(Stream, _Flags, S) -> ok = quicer:async_shutdown_stream(Stream, ?QUIC_STREAM_SHUTDOWN_FLAG_GRACEFUL, 0), {ok, S}. send_complete(_Stream, false, S) -> {ok, S}; send_complete(_Stream, true = _IsCanceled, S) -> ct:pal("~p : send is canceled", [?FUNCTION_NAME]), {ok, S}. send_shutdown_complete(_Stream, _Flags, S) -> ct:pal("~p : stream send is complete", [?FUNCTION_NAME]), {ok, S}. start_completed(_Stream, #{status := success, stream_id := StreamId}, S) -> {ok, S#{stream_id => StreamId}}; start_completed(_Stream, #{status := Other }, S) -> {stop, {start_fail, Other}, S}. handle_stream_data(Stream, <<"flow_control.enable_bidi">> = Bin, _Flags, #{is_unidir := true, conn := Conn} = State) -> ?tp(debug, #{stream => Stream, data => Bin, module => ?MODULE, dir => unidir}), ok = quicer:setopt(Conn, param_conn_settings, #{peer_bidi_stream_count => 2}), {ok, State}; handle_stream_data(Stream, Bin, _Flags, #{is_unidir := false} = State) -> for bidir stream , we just echo in place . ?tp(debug, #{stream => Stream, data => Bin, module => ?MODULE, dir => bidir}), ct:pal("Server recv: ~p from ~p", [Bin, Stream] ), {ok, _} = quicer:send(Stream, Bin), {ok, State}; handle_stream_data(Stream, Bin, _Flags, #{is_unidir := true, peer_stream := PeerStream, conn := Conn} = State) -> ?tp(debug, #{stream => Stream, data => Bin, module => ?MODULE, dir => unidir}), ct:pal("Server recv: ~p from ~p", [Bin, Stream] ), case PeerStream of undefined -> {ok, StreamProc} = quicer_stream:start_link(?MODULE, Conn, [ {open_flag, ?QUIC_STREAM_OPEN_FLAG_UNIDIRECTIONAL} , {is_local, true} ]), {ok, _} = quicer_stream:send(StreamProc, Bin), {ok, State#{peer_stream := StreamProc}}; StreamProc when is_pid(StreamProc) -> {ok, _} = quicer_stream:send(StreamProc, Bin), {ok, State} end. passive(_Stream, undefined, S)-> ct:fail("Steam go into passive mode"), {ok, S}. stream_closed(_Stream, #{ is_conn_shutdown := IsConnShutdown , is_app_closing := IsAppClosing , is_shutdown_by_app := IsAppShutdown , is_closed_remotely := IsRemote , status := Status , error := Code }, S) when is_boolean(IsConnShutdown) andalso is_boolean(IsAppClosing) andalso is_boolean(IsAppShutdown) andalso is_boolean(IsRemote) andalso is_atom(Status) andalso is_integer(Code) -> {stop, normal, S}. handle_call(_Request, _From, S) -> {reply, {error, not_impl}, S}.
33ef45b72a7fb6d60e61bc48d76ac6f1ef20743c87d7f7ef8c6e599f3878cd8b
EligiusSantori/L2Apf
my_target_selected.scm
(module system racket/base (require "../../packet.scm") (provide game-server-packet/my-target-selected) (define (game-server-packet/my-target-selected buffer) (let ((s (open-input-bytes buffer))) (list (cons 'id (read-byte s)) (cons 'target-id (read-int32 #f s)) (cons 'color (read-int16 #f s)) ) ) ) )
null
https://raw.githubusercontent.com/EligiusSantori/L2Apf/30ffe0828e8a401f58d39984efd862c8aeab8c30/packet/game/server/my_target_selected.scm
scheme
(module system racket/base (require "../../packet.scm") (provide game-server-packet/my-target-selected) (define (game-server-packet/my-target-selected buffer) (let ((s (open-input-bytes buffer))) (list (cons 'id (read-byte s)) (cons 'target-id (read-int32 #f s)) (cons 'color (read-int16 #f s)) ) ) ) )
24bb974ddf1a18fb49d23e73b539de72a940c75d965a472fe489bae38d96a229
CodyReichert/qi
utsname.lisp
;;;; -*- Mode: lisp; indent-tabs-mode: nil -*- ;;; ;;; utsname.lisp --- Grovel definitions for uname(3). ;;; Copyright ( C ) 2007 , ;;; ;;; Permission is hereby granted, free of charge, to any person ;;; obtaining a copy of this software and associated documentation files ( the " Software " ) , to deal in the Software without ;;; restriction, including without limitation the rights to use, copy, ;;; modify, merge, publish, distribute, sublicense, and/or sell copies of the Software , and to permit persons to whom the Software is ;;; furnished to do so, subject to the following conditions: ;;; ;;; The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software . ;;; THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , ;;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF ;;; MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND ;;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT ;;; HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, ;;; WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, ;;; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER ;;; DEALINGS IN THE SOFTWARE. (in-package :trivial-features-tests) (include "sys/utsname.h") (cstruct utsname "struct utsname" (sysname "sysname" :type :char) (nodename "nodename" :type :char) (release "release" :type :char) (version "version" :type :char) (machine "machine" :type :char))
null
https://raw.githubusercontent.com/CodyReichert/qi/9cf6d31f40e19f4a7f60891ef7c8c0381ccac66f/dependencies/trivial-features-latest/tests/utsname.lisp
lisp
-*- Mode: lisp; indent-tabs-mode: nil -*- utsname.lisp --- Grovel definitions for uname(3). Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Copyright ( C ) 2007 , files ( the " Software " ) , to deal in the Software without of the Software , and to permit persons to whom the Software is included in all copies or substantial portions of the Software . THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , (in-package :trivial-features-tests) (include "sys/utsname.h") (cstruct utsname "struct utsname" (sysname "sysname" :type :char) (nodename "nodename" :type :char) (release "release" :type :char) (version "version" :type :char) (machine "machine" :type :char))
cc1c3610eb6044052e2f2e80b02cabb342fd2181216934169fda54c913684a75
tsloughter/kuberl
kuberl_v1_object_meta.erl
-module(kuberl_v1_object_meta). -export([encode/1]). -export_type([kuberl_v1_object_meta/0]). -type kuberl_v1_object_meta() :: #{ 'annotations' => maps:map(), 'clusterName' => binary(), 'creationTimestamp' => kuberl_date_time:kuberl_date_time(), 'deletionGracePeriodSeconds' => integer(), 'deletionTimestamp' => kuberl_date_time:kuberl_date_time(), 'finalizers' => list(), 'generateName' => binary(), 'generation' => integer(), 'labels' => maps:map(), 'managedFields' => list(), 'name' => binary(), 'namespace' => binary(), 'ownerReferences' => list(), 'resourceVersion' => binary(), 'selfLink' => binary(), 'uid' => binary() }. encode(#{ 'annotations' := Annotations, 'clusterName' := ClusterName, 'creationTimestamp' := CreationTimestamp, 'deletionGracePeriodSeconds' := DeletionGracePeriodSeconds, 'deletionTimestamp' := DeletionTimestamp, 'finalizers' := Finalizers, 'generateName' := GenerateName, 'generation' := Generation, 'labels' := Labels, 'managedFields' := ManagedFields, 'name' := Name, 'namespace' := Namespace, 'ownerReferences' := OwnerReferences, 'resourceVersion' := ResourceVersion, 'selfLink' := SelfLink, 'uid' := Uid }) -> #{ 'annotations' => Annotations, 'clusterName' => ClusterName, 'creationTimestamp' => CreationTimestamp, 'deletionGracePeriodSeconds' => DeletionGracePeriodSeconds, 'deletionTimestamp' => DeletionTimestamp, 'finalizers' => Finalizers, 'generateName' => GenerateName, 'generation' => Generation, 'labels' => Labels, 'managedFields' => ManagedFields, 'name' => Name, 'namespace' => Namespace, 'ownerReferences' => OwnerReferences, 'resourceVersion' => ResourceVersion, 'selfLink' => SelfLink, 'uid' => Uid }.
null
https://raw.githubusercontent.com/tsloughter/kuberl/f02ae6680d6ea5db6e8b6c7acbee8c4f9df482e2/gen/kuberl_v1_object_meta.erl
erlang
-module(kuberl_v1_object_meta). -export([encode/1]). -export_type([kuberl_v1_object_meta/0]). -type kuberl_v1_object_meta() :: #{ 'annotations' => maps:map(), 'clusterName' => binary(), 'creationTimestamp' => kuberl_date_time:kuberl_date_time(), 'deletionGracePeriodSeconds' => integer(), 'deletionTimestamp' => kuberl_date_time:kuberl_date_time(), 'finalizers' => list(), 'generateName' => binary(), 'generation' => integer(), 'labels' => maps:map(), 'managedFields' => list(), 'name' => binary(), 'namespace' => binary(), 'ownerReferences' => list(), 'resourceVersion' => binary(), 'selfLink' => binary(), 'uid' => binary() }. encode(#{ 'annotations' := Annotations, 'clusterName' := ClusterName, 'creationTimestamp' := CreationTimestamp, 'deletionGracePeriodSeconds' := DeletionGracePeriodSeconds, 'deletionTimestamp' := DeletionTimestamp, 'finalizers' := Finalizers, 'generateName' := GenerateName, 'generation' := Generation, 'labels' := Labels, 'managedFields' := ManagedFields, 'name' := Name, 'namespace' := Namespace, 'ownerReferences' := OwnerReferences, 'resourceVersion' := ResourceVersion, 'selfLink' := SelfLink, 'uid' := Uid }) -> #{ 'annotations' => Annotations, 'clusterName' => ClusterName, 'creationTimestamp' => CreationTimestamp, 'deletionGracePeriodSeconds' => DeletionGracePeriodSeconds, 'deletionTimestamp' => DeletionTimestamp, 'finalizers' => Finalizers, 'generateName' => GenerateName, 'generation' => Generation, 'labels' => Labels, 'managedFields' => ManagedFields, 'name' => Name, 'namespace' => Namespace, 'ownerReferences' => OwnerReferences, 'resourceVersion' => ResourceVersion, 'selfLink' => SelfLink, 'uid' => Uid }.
64fca26f9256641f1e6a00b2ee9f90d80623c564a8540026c0513d540ae8a28e
NashFP/bowling
bowling.erl
Erlang Bowling game scorer % % Expects a list of scores as input, generates game score as output. -module(bowling). -export([score/1, strike/2, spare/2]). % specials: Strike : current + next two balls Spare : current + next one ball score([]) -> 0; score([[N1,N2,N3]]) when N1 =:= 10 -> N1 + N2 + N3; %final frame score([[N1,N2]|L]) when N1 =:= 10 -> strike([N1,N2], L) + score(L); score([[N1,N2]|L]) when N1 + N2 =:= 10 -> spare([N1,N2], L) + score(L); score([[N1,N2]|L]) -> N1 + N2 + score(L); score([[N]|L]) when N =:= 10 -> strike([N,0], L) + score(L); score([[N]|L]) -> N + score(L). strike([N1,N2], L) when N2 > 0 -> case L of [[N3]] -> N1 + N2 + N3; [] -> N1 + N2 end; strike([N1,_], L) when length(L) > 0 -> case L of [[N3,N4]|_] -> N1 + N3 + N4; [[N3,N4,_]|_] -> N1 + N3 + N4; [[N3]|T] -> case T of [[N4]|_] -> N1 + N3 + N4; [[N4,_,_]|_] -> N1 + N3 + N4; %final frame [] -> N1 + N3 end end; strike([N1,N2], _) -> N1 + N2. spare([N1,N2], L) -> case L of [[N3,_]] -> N1 + N2 + N3; [] -> N1 + N2 end.
null
https://raw.githubusercontent.com/NashFP/bowling/d7829668fc221784528019796cc33011b1c65a2d/robhardin%2Berlang/bowling.erl
erlang
Expects a list of scores as input, generates game score as output. specials: final frame final frame
Erlang Bowling game scorer -module(bowling). -export([score/1, strike/2, spare/2]). Strike : current + next two balls Spare : current + next one ball score([]) -> 0; score([[N1,N2,N3]]) when N1 =:= 10 -> score([[N1,N2]|L]) when N1 =:= 10 -> strike([N1,N2], L) + score(L); score([[N1,N2]|L]) when N1 + N2 =:= 10 -> spare([N1,N2], L) + score(L); score([[N1,N2]|L]) -> N1 + N2 + score(L); score([[N]|L]) when N =:= 10 -> strike([N,0], L) + score(L); score([[N]|L]) -> N + score(L). strike([N1,N2], L) when N2 > 0 -> case L of [[N3]] -> N1 + N2 + N3; [] -> N1 + N2 end; strike([N1,_], L) when length(L) > 0 -> case L of [[N3,N4]|_] -> N1 + N3 + N4; [[N3,N4,_]|_] -> N1 + N3 + N4; [[N3]|T] -> case T of [[N4]|_] -> N1 + N3 + N4; [] -> N1 + N3 end end; strike([N1,N2], _) -> N1 + N2. spare([N1,N2], L) -> case L of [[N3,_]] -> N1 + N2 + N3; [] -> N1 + N2 end.
a0c45fee72338d08c0e25efaf2a49bab6a3efeb442a2cf8c53c617bf9516c535
nasa/Common-Metadata-Repository
subscriptions_test.clj
(ns cmr.system-int-test.bootstrap.bulk-index.subscriptions-test "Integration test for CMR bulk index subscription operations." (:require [cmr.system-int-test.data2.umm-spec-collection :as data-umm-c] [clojure.test :refer :all] [cmr.mock-echo.client.echo-util :as echo-util] [cmr.system-int-test.bootstrap.bulk-index.core :as core] [cmr.system-int-test.data2.core :as d] [cmr.system-int-test.data2.umm-json :as data-umm-json] [cmr.system-int-test.system :as system] [cmr.system-int-test.utils.bootstrap-util :as bootstrap] [cmr.system-int-test.utils.index-util :as index] [cmr.system-int-test.utils.ingest-util :as ingest] [cmr.system-int-test.utils.search-util :as search] [cmr.system-int-test.utils.subscription-util :as subscription] [cmr.umm-spec.versioning :as umm-version] [cmr.mock-echo.client.mock-urs-client :as mock-urs])) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Fixtures ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn auto-index-fixture "Disable automatic indexing during tests." [f] (core/disable-automatic-indexing) (f) (core/reenable-automatic-indexing)) (use-fixtures :each (join-fixtures [(ingest/reset-fixture {"provguid1" "PROV1" "provguid2" "PROV2" "provguid3" "PROV3"} {:grant-all-ingest? true :grant-all-search? true :grant-all-access-control? false}) (subscription/grant-all-subscription-fixture {"provguid1" "PROV1" "provguid2" "PROV2" "provguid3" "PROV3"} [:read :update] [:read :update]) auto-index-fixture])) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Tests ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (deftest ^:oracle bulk-index-subscriptions-for-provider (mock-urs/create-users (system/context) [{:username "someSubId" :password "Password"}]) (testing "Bulk index subscriptions for a single provider" (system/only-with-real-database ;; The following is saved, but not indexed due to the above call (let [coll1 (d/ingest-umm-spec-collection "PROV1" (data-umm-c/collection {:EntryTitle "E1" :ShortName "S1" :Version "V1"})) sub1 (subscription/ingest-subscription-with-attrs {:provider-id "PROV1" :Query "instrument=POSEIDON-2" :CollectionConceptId (:concept-id coll1)} {} 1) create a subscription on a different provider PROV2 ;; and this subscription won't be indexed as a result of indexing subscriptions of PROV1 sub2 (subscription/ingest-subscription-with-attrs {:provider-id "PROV2" :Query "instrument=POSEIDON-3" :CollectionConceptId (:concept-id coll1)} {} 1)] ;; no index, no hits. (is (zero? (:hits (search/find-refs :subscription {})))) (bootstrap/bulk-index-subscriptions "PROV1") (index/wait-until-indexed) (testing "Subscription concepts are indexed." Note : only sub1 is indexed , sub2 is not . (let [{:keys [hits refs]} (search/find-refs :subscription {})] (is (= 1 hits)) (is (= (:concept-id sub1) (:id (first refs)))))) (testing "Bulk index multilpe subscriptions for a single provider" Ingest three more subscriptions (subscription/ingest-subscription-with-attrs {:provider-id "PROV1" :Query "instrument=POSEIDON-3B" :CollectionConceptId (:concept-id coll1)} {} 2) (subscription/ingest-subscription-with-attrs {:provider-id "PROV1" :Query "instrument=POSEIDON-4" :CollectionConceptId (:concept-id coll1)} {} 3) (subscription/ingest-subscription-with-attrs {:provider-id "PROV1" :Query "instrument=POSEIDON-4B" :CollectionConceptId (:concept-id coll1)} {} 4) The above three new subscriptions are not indexed , only sub1 is indexed . (is (= 1 (:hits (search/find-refs :subscription {})))) ;; bulk index again, using system token, all the subscriptions in PROV1 should be indexed. (bootstrap/bulk-index-subscriptions "PROV1") (index/wait-until-indexed) (let [{:keys [hits refs]} (search/find-refs :subscription {})] (is (= 4 hits)) (is (= 4 (count refs))))))))) (deftest ^:oracle bulk-index-subscriptions (mock-urs/create-users (system/context) [{:username "someSubId" :password "Password"}]) (testing "Bulk index subscriptions for multiple providers, explicitly" (system/only-with-real-database (let [coll1 (d/ingest-umm-spec-collection "PROV1" (data-umm-c/collection {:EntryTitle "E1" :ShortName "S1" :Version "V1"}))] ;; The following are saved, but not indexed due to the above call (subscription/ingest-subscription-with-attrs {:provider-id "PROV1" :Query "instrument=AVHRR" :CollectionConceptId (:concept-id coll1)} {} 1) (subscription/ingest-subscription-with-attrs {:provider-id "PROV1" :Query "instrument=AVHRR-2" :CollectionConceptId (:concept-id coll1)} {} 2) (subscription/ingest-subscription-with-attrs {:provider-id "PROV2" :Query "instrument=AVHRR-3" :CollectionConceptId (:concept-id coll1)} {} 3) (subscription/ingest-subscription-with-attrs {:provider-id "PROV2" :Query "instrument=AVHRR-4" :CollectionConceptId (:concept-id coll1)} {} 4) (subscription/ingest-subscription-with-attrs {:provider-id "PROV3" :Query "instrument=AVHRR-5" :CollectionConceptId (:concept-id coll1)} {} 5) (subscription/ingest-subscription-with-attrs {:provider-id "PROV3" :Query "instrument=AVHRR-6" :CollectionConceptId (:concept-id coll1)} {} 6) (is (= 0 (:hits (search/find-refs :subscription {})))) (bootstrap/bulk-index-subscriptions "PROV1") (bootstrap/bulk-index-subscriptions "PROV2") (bootstrap/bulk-index-subscriptions "PROV3") (index/wait-until-indexed) (testing "Subscription concepts are indexed." (let [{:keys [hits refs] :as response} (search/find-refs :subscription {})] (is (= 6 hits)) (is (= 6 (count refs))) )))))) (deftest ^:oracle bulk-index-all-subscriptions (mock-urs/create-users (system/context) [{:username "someSubId" :password "Password"}]) (testing "Bulk index subscriptions for multiple providers, implicitly" (system/only-with-real-database ;; The following are saved, but not indexed due to the above call (let [coll1 (d/ingest-umm-spec-collection "PROV1" (data-umm-c/collection {:EntryTitle "E1" :ShortName "S1" :Version "V1"}))] (subscription/ingest-subscription-with-attrs {:provider-id "PROV1" :CollectionConceptId (:concept-id coll1) :Query "platform=NOAA-7"} {} 1) (subscription/ingest-subscription-with-attrs {:provider-id "PROV2" :CollectionConceptId (:concept-id coll1) :Query "platform=NOAA-9"} {} 2) (subscription/ingest-subscription-with-attrs {:provider-id "PROV3" :CollectionConceptId (:concept-id coll1) :Query "platform=NOAA-10"} {} 3) (is (= 0 (:hits (search/find-refs :subscription {})))) (bootstrap/bulk-index-subscriptions) (index/wait-until-indexed) (testing "Subscription concepts are indexed." (let [{:keys [hits refs]} (search/find-refs :subscription {})] (is (= 3 hits)) (is (= 3 (count refs))))))))) (deftest ^:oracle bulk-index-subscription-revisions (testing "Bulk index subscriptions index all revisions index as well" (system/only-with-real-database (let [token (echo-util/login (system/context) "user1") coll1 (d/ingest-umm-spec-collection "PROV1" (data-umm-c/collection {:EntryTitle "E1" :ShortName "S1" :Version "V1"})) coll2 (d/ingest-umm-spec-collection "PROV2" (data-umm-c/collection {:EntryTitle "E2" :ShortName "S2" :Version "V2"})) coll3 (d/ingest-umm-spec-collection "PROV3" (data-umm-c/collection {:EntryTitle "E3" :ShortName "S3" :Version "V3"})) sub1-concept (subscription/make-subscription-concept {:native-id "SUB1" :Name "Sub1" :SubscriberId "user1" :CollectionConceptId (:concept-id coll1) :Query "platform=NOAA-7" :provider-id "PROV1"}) sub2-concept (subscription/make-subscription-concept {:native-id "SUB2" :Name "Sub2" :SubscriberId "user1" :CollectionConceptId (:concept-id coll2) :Query "platform=NOAA-9" :provider-id "PROV2"}) sub2-2-concept (subscription/make-subscription-concept {:native-id "SUB2" :Name "Sub2-2" :SubscriberId "user1" :CollectionConceptId (:concept-id coll2) :Query "platform=NOAA-10" :provider-id "PROV2"}) sub3-concept (subscription/make-subscription-concept {:native-id "SUB3" :Name "Sub1" :SubscriberId "user1" :CollectionConceptId (:concept-id coll3) :Query "platform=NOAA-11" :provider-id "PROV3"}) sub1-1 (subscription/ingest-subscription sub1-concept) sub1-2-tombstone (merge (ingest/delete-concept sub1-concept (subscription/token-opts token)) sub1-concept {:deleted true :user-id "user1"}) sub1-3 (subscription/ingest-subscription sub1-concept) sub2-1 (subscription/ingest-subscription sub2-concept) sub2-2 (subscription/ingest-subscription sub2-2-concept) sub2-3-tombstone (merge (ingest/delete-concept sub2-2-concept (subscription/token-opts token)) sub2-2-concept {:deleted true :user-id "user1"}) sub3 (subscription/ingest-subscription sub3-concept)] ;; Before bulk indexing, search for services found nothing (data-umm-json/assert-subscription-umm-jsons-match umm-version/current-subscription-version [] (search/find-concepts-umm-json :subscription {:all-revisions true})) ;; Just index PROV1 (bootstrap/bulk-index-subscriptions "PROV1") (index/wait-until-indexed) ;; After bulk indexing a provider, search found all subscription revisions for the provider ;; of that provider (data-umm-json/assert-subscription-umm-jsons-match umm-version/current-subscription-version [sub1-1 sub1-2-tombstone sub1-3] (search/find-concepts-umm-json :subscription {:all-revisions true})) ;; Now index all subscriptions (bootstrap/bulk-index-subscriptions) (index/wait-until-indexed) ;; After bulk indexing, search for subscriptions found all revisions (data-umm-json/assert-subscription-umm-jsons-match umm-version/current-subscription-version [sub1-1 sub1-2-tombstone sub1-3 sub2-1 sub2-2 sub2-3-tombstone sub3] (search/find-concepts-umm-json :subscription {:all-revisions true}))))))
null
https://raw.githubusercontent.com/nasa/Common-Metadata-Repository/0e64f0edcef65742c05b6ccf3da4d5c5586e814b/system-int-test/test/cmr/system_int_test/bootstrap/bulk_index/subscriptions_test.clj
clojure
Fixtures Tests The following is saved, but not indexed due to the above call and this subscription won't be indexed as a result of indexing subscriptions of PROV1 no index, no hits. bulk index again, using system token, all the subscriptions in PROV1 should be indexed. The following are saved, but not indexed due to the above call The following are saved, but not indexed due to the above call Before bulk indexing, search for services found nothing Just index PROV1 After bulk indexing a provider, search found all subscription revisions for the provider of that provider Now index all subscriptions After bulk indexing, search for subscriptions found all revisions
(ns cmr.system-int-test.bootstrap.bulk-index.subscriptions-test "Integration test for CMR bulk index subscription operations." (:require [cmr.system-int-test.data2.umm-spec-collection :as data-umm-c] [clojure.test :refer :all] [cmr.mock-echo.client.echo-util :as echo-util] [cmr.system-int-test.bootstrap.bulk-index.core :as core] [cmr.system-int-test.data2.core :as d] [cmr.system-int-test.data2.umm-json :as data-umm-json] [cmr.system-int-test.system :as system] [cmr.system-int-test.utils.bootstrap-util :as bootstrap] [cmr.system-int-test.utils.index-util :as index] [cmr.system-int-test.utils.ingest-util :as ingest] [cmr.system-int-test.utils.search-util :as search] [cmr.system-int-test.utils.subscription-util :as subscription] [cmr.umm-spec.versioning :as umm-version] [cmr.mock-echo.client.mock-urs-client :as mock-urs])) (defn auto-index-fixture "Disable automatic indexing during tests." [f] (core/disable-automatic-indexing) (f) (core/reenable-automatic-indexing)) (use-fixtures :each (join-fixtures [(ingest/reset-fixture {"provguid1" "PROV1" "provguid2" "PROV2" "provguid3" "PROV3"} {:grant-all-ingest? true :grant-all-search? true :grant-all-access-control? false}) (subscription/grant-all-subscription-fixture {"provguid1" "PROV1" "provguid2" "PROV2" "provguid3" "PROV3"} [:read :update] [:read :update]) auto-index-fixture])) (deftest ^:oracle bulk-index-subscriptions-for-provider (mock-urs/create-users (system/context) [{:username "someSubId" :password "Password"}]) (testing "Bulk index subscriptions for a single provider" (system/only-with-real-database (let [coll1 (d/ingest-umm-spec-collection "PROV1" (data-umm-c/collection {:EntryTitle "E1" :ShortName "S1" :Version "V1"})) sub1 (subscription/ingest-subscription-with-attrs {:provider-id "PROV1" :Query "instrument=POSEIDON-2" :CollectionConceptId (:concept-id coll1)} {} 1) create a subscription on a different provider PROV2 sub2 (subscription/ingest-subscription-with-attrs {:provider-id "PROV2" :Query "instrument=POSEIDON-3" :CollectionConceptId (:concept-id coll1)} {} 1)] (is (zero? (:hits (search/find-refs :subscription {})))) (bootstrap/bulk-index-subscriptions "PROV1") (index/wait-until-indexed) (testing "Subscription concepts are indexed." Note : only sub1 is indexed , sub2 is not . (let [{:keys [hits refs]} (search/find-refs :subscription {})] (is (= 1 hits)) (is (= (:concept-id sub1) (:id (first refs)))))) (testing "Bulk index multilpe subscriptions for a single provider" Ingest three more subscriptions (subscription/ingest-subscription-with-attrs {:provider-id "PROV1" :Query "instrument=POSEIDON-3B" :CollectionConceptId (:concept-id coll1)} {} 2) (subscription/ingest-subscription-with-attrs {:provider-id "PROV1" :Query "instrument=POSEIDON-4" :CollectionConceptId (:concept-id coll1)} {} 3) (subscription/ingest-subscription-with-attrs {:provider-id "PROV1" :Query "instrument=POSEIDON-4B" :CollectionConceptId (:concept-id coll1)} {} 4) The above three new subscriptions are not indexed , only sub1 is indexed . (is (= 1 (:hits (search/find-refs :subscription {})))) (bootstrap/bulk-index-subscriptions "PROV1") (index/wait-until-indexed) (let [{:keys [hits refs]} (search/find-refs :subscription {})] (is (= 4 hits)) (is (= 4 (count refs))))))))) (deftest ^:oracle bulk-index-subscriptions (mock-urs/create-users (system/context) [{:username "someSubId" :password "Password"}]) (testing "Bulk index subscriptions for multiple providers, explicitly" (system/only-with-real-database (let [coll1 (d/ingest-umm-spec-collection "PROV1" (data-umm-c/collection {:EntryTitle "E1" :ShortName "S1" :Version "V1"}))] (subscription/ingest-subscription-with-attrs {:provider-id "PROV1" :Query "instrument=AVHRR" :CollectionConceptId (:concept-id coll1)} {} 1) (subscription/ingest-subscription-with-attrs {:provider-id "PROV1" :Query "instrument=AVHRR-2" :CollectionConceptId (:concept-id coll1)} {} 2) (subscription/ingest-subscription-with-attrs {:provider-id "PROV2" :Query "instrument=AVHRR-3" :CollectionConceptId (:concept-id coll1)} {} 3) (subscription/ingest-subscription-with-attrs {:provider-id "PROV2" :Query "instrument=AVHRR-4" :CollectionConceptId (:concept-id coll1)} {} 4) (subscription/ingest-subscription-with-attrs {:provider-id "PROV3" :Query "instrument=AVHRR-5" :CollectionConceptId (:concept-id coll1)} {} 5) (subscription/ingest-subscription-with-attrs {:provider-id "PROV3" :Query "instrument=AVHRR-6" :CollectionConceptId (:concept-id coll1)} {} 6) (is (= 0 (:hits (search/find-refs :subscription {})))) (bootstrap/bulk-index-subscriptions "PROV1") (bootstrap/bulk-index-subscriptions "PROV2") (bootstrap/bulk-index-subscriptions "PROV3") (index/wait-until-indexed) (testing "Subscription concepts are indexed." (let [{:keys [hits refs] :as response} (search/find-refs :subscription {})] (is (= 6 hits)) (is (= 6 (count refs))) )))))) (deftest ^:oracle bulk-index-all-subscriptions (mock-urs/create-users (system/context) [{:username "someSubId" :password "Password"}]) (testing "Bulk index subscriptions for multiple providers, implicitly" (system/only-with-real-database (let [coll1 (d/ingest-umm-spec-collection "PROV1" (data-umm-c/collection {:EntryTitle "E1" :ShortName "S1" :Version "V1"}))] (subscription/ingest-subscription-with-attrs {:provider-id "PROV1" :CollectionConceptId (:concept-id coll1) :Query "platform=NOAA-7"} {} 1) (subscription/ingest-subscription-with-attrs {:provider-id "PROV2" :CollectionConceptId (:concept-id coll1) :Query "platform=NOAA-9"} {} 2) (subscription/ingest-subscription-with-attrs {:provider-id "PROV3" :CollectionConceptId (:concept-id coll1) :Query "platform=NOAA-10"} {} 3) (is (= 0 (:hits (search/find-refs :subscription {})))) (bootstrap/bulk-index-subscriptions) (index/wait-until-indexed) (testing "Subscription concepts are indexed." (let [{:keys [hits refs]} (search/find-refs :subscription {})] (is (= 3 hits)) (is (= 3 (count refs))))))))) (deftest ^:oracle bulk-index-subscription-revisions (testing "Bulk index subscriptions index all revisions index as well" (system/only-with-real-database (let [token (echo-util/login (system/context) "user1") coll1 (d/ingest-umm-spec-collection "PROV1" (data-umm-c/collection {:EntryTitle "E1" :ShortName "S1" :Version "V1"})) coll2 (d/ingest-umm-spec-collection "PROV2" (data-umm-c/collection {:EntryTitle "E2" :ShortName "S2" :Version "V2"})) coll3 (d/ingest-umm-spec-collection "PROV3" (data-umm-c/collection {:EntryTitle "E3" :ShortName "S3" :Version "V3"})) sub1-concept (subscription/make-subscription-concept {:native-id "SUB1" :Name "Sub1" :SubscriberId "user1" :CollectionConceptId (:concept-id coll1) :Query "platform=NOAA-7" :provider-id "PROV1"}) sub2-concept (subscription/make-subscription-concept {:native-id "SUB2" :Name "Sub2" :SubscriberId "user1" :CollectionConceptId (:concept-id coll2) :Query "platform=NOAA-9" :provider-id "PROV2"}) sub2-2-concept (subscription/make-subscription-concept {:native-id "SUB2" :Name "Sub2-2" :SubscriberId "user1" :CollectionConceptId (:concept-id coll2) :Query "platform=NOAA-10" :provider-id "PROV2"}) sub3-concept (subscription/make-subscription-concept {:native-id "SUB3" :Name "Sub1" :SubscriberId "user1" :CollectionConceptId (:concept-id coll3) :Query "platform=NOAA-11" :provider-id "PROV3"}) sub1-1 (subscription/ingest-subscription sub1-concept) sub1-2-tombstone (merge (ingest/delete-concept sub1-concept (subscription/token-opts token)) sub1-concept {:deleted true :user-id "user1"}) sub1-3 (subscription/ingest-subscription sub1-concept) sub2-1 (subscription/ingest-subscription sub2-concept) sub2-2 (subscription/ingest-subscription sub2-2-concept) sub2-3-tombstone (merge (ingest/delete-concept sub2-2-concept (subscription/token-opts token)) sub2-2-concept {:deleted true :user-id "user1"}) sub3 (subscription/ingest-subscription sub3-concept)] (data-umm-json/assert-subscription-umm-jsons-match umm-version/current-subscription-version [] (search/find-concepts-umm-json :subscription {:all-revisions true})) (bootstrap/bulk-index-subscriptions "PROV1") (index/wait-until-indexed) (data-umm-json/assert-subscription-umm-jsons-match umm-version/current-subscription-version [sub1-1 sub1-2-tombstone sub1-3] (search/find-concepts-umm-json :subscription {:all-revisions true})) (bootstrap/bulk-index-subscriptions) (index/wait-until-indexed) (data-umm-json/assert-subscription-umm-jsons-match umm-version/current-subscription-version [sub1-1 sub1-2-tombstone sub1-3 sub2-1 sub2-2 sub2-3-tombstone sub3] (search/find-concepts-umm-json :subscription {:all-revisions true}))))))
c5da95074c3d814d1b3f05a70035c911c49bcc052daffe9a397805b125827890
static-analysis-engineering/codehawk
jCHSystemUtils.mli
= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = CodeHawk Java Analyzer Author : ------------------------------------------------------------------------------ The MIT License ( MIT ) Copyright ( c ) 2005 - 2020 Kestrel Technology LLC Permission is hereby granted , free of charge , to any person obtaining a copy of this software and associated documentation files ( the " Software " ) , to deal in the Software without restriction , including without limitation the rights to use , copy , modify , merge , publish , distribute , sublicense , and/or sell copies of the Software , and to permit persons to whom the Software is furnished to do so , subject to the following conditions : The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software . THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR , INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY , FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT . IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM , DAMAGES OR OTHER LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING FROM , OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE . = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = CodeHawk Java Analyzer Author: Anca Browne ------------------------------------------------------------------------------ The MIT License (MIT) Copyright (c) 2005-2020 Kestrel Technology LLC Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ============================================================================= *) chlib open CHLanguage open CHPretty (* jchlib *) open JCHBasicTypesAPI (* jchpre *) open JCHPreAPI val is_number: variable_t -> bool val is_not_number: variable_t -> bool val is_constant: variable_t -> bool val is_loop_counter: variable_t -> bool val is_exception: variable_t -> bool val is_not_exception: variable_t -> bool val is_return: variable_t -> bool val is_not_exception_or_return: variable_t -> bool val is_temp: variable_t -> bool val is_register: variable_t -> bool val is_length: variable_t -> bool val is_stack: variable_t -> bool val make_length: variable_t -> variable_t val get_register_index: variable_t -> int val get_signature_vars: procedure_int -> variable_t list val get_signature_write_vars: procedure_int -> variable_t list val get_signature_read_vars: procedure_int -> variable_t list val get_return_var: procedure_int -> variable_t option val get_num_return_var: procedure_int -> variable_t option val add_cmds : cms:class_method_signature_int -> init_cmds:(code_int, cfg_int) command_t list -> final_cmds:(code_int, cfg_int) command_t list -> code:code_int -> code_int val get_CFG : procedure_int -> cfg_int val get_arg_var : string -> (string * variable_t * arg_mode_t) list -> variable_t val get_arg_var_opt : string -> (string * variable_t * arg_mode_t) list -> variable_t option val get_read_vars: ('a * 'b * arg_mode_t) list -> 'b list val get_just_read_vars: ('a * 'b * arg_mode_t) list -> 'b list val get_write_vars: ('a * 'b * arg_mode_t) list -> 'b list val get_just_write_vars: ('a * 'b * arg_mode_t) list -> 'b list val get_bytecode : symbol_t -> bytecode_int option val copy_system : system_int -> system_int val get_first_and_last_in_state : method_info_int -> state_int -> int option * int val get_prev_pcs : method_info_int -> cfg_int -> state_int -> int list val start_timing: unit -> unit val add_timing: string -> unit val start_total_time: unit -> unit val get_total_time: unit -> float val start_time: unit -> unit val get_time: unit -> float val sym_to_pc: symbol_t -> int val is_not_jdk_method: symbol_t -> bool val start_profiling_time: int -> unit val stop_profiling_time: int -> unit val report_profiling_times: unit -> unit val report_profiling_times_no_reset: unit -> unit val print_warning_message: pretty_t -> unit val print_exception_message: pretty_t -> unit
null
https://raw.githubusercontent.com/static-analysis-engineering/codehawk/98ced4d5e6d7989575092df232759afc2cb851f6/CodeHawk/CHJ/jchsys/jCHSystemUtils.mli
ocaml
jchlib jchpre
= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = CodeHawk Java Analyzer Author : ------------------------------------------------------------------------------ The MIT License ( MIT ) Copyright ( c ) 2005 - 2020 Kestrel Technology LLC Permission is hereby granted , free of charge , to any person obtaining a copy of this software and associated documentation files ( the " Software " ) , to deal in the Software without restriction , including without limitation the rights to use , copy , modify , merge , publish , distribute , sublicense , and/or sell copies of the Software , and to permit persons to whom the Software is furnished to do so , subject to the following conditions : The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software . THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR , INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY , FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT . IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM , DAMAGES OR OTHER LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING FROM , OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE . = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = CodeHawk Java Analyzer Author: Anca Browne ------------------------------------------------------------------------------ The MIT License (MIT) Copyright (c) 2005-2020 Kestrel Technology LLC Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ============================================================================= *) chlib open CHLanguage open CHPretty open JCHBasicTypesAPI open JCHPreAPI val is_number: variable_t -> bool val is_not_number: variable_t -> bool val is_constant: variable_t -> bool val is_loop_counter: variable_t -> bool val is_exception: variable_t -> bool val is_not_exception: variable_t -> bool val is_return: variable_t -> bool val is_not_exception_or_return: variable_t -> bool val is_temp: variable_t -> bool val is_register: variable_t -> bool val is_length: variable_t -> bool val is_stack: variable_t -> bool val make_length: variable_t -> variable_t val get_register_index: variable_t -> int val get_signature_vars: procedure_int -> variable_t list val get_signature_write_vars: procedure_int -> variable_t list val get_signature_read_vars: procedure_int -> variable_t list val get_return_var: procedure_int -> variable_t option val get_num_return_var: procedure_int -> variable_t option val add_cmds : cms:class_method_signature_int -> init_cmds:(code_int, cfg_int) command_t list -> final_cmds:(code_int, cfg_int) command_t list -> code:code_int -> code_int val get_CFG : procedure_int -> cfg_int val get_arg_var : string -> (string * variable_t * arg_mode_t) list -> variable_t val get_arg_var_opt : string -> (string * variable_t * arg_mode_t) list -> variable_t option val get_read_vars: ('a * 'b * arg_mode_t) list -> 'b list val get_just_read_vars: ('a * 'b * arg_mode_t) list -> 'b list val get_write_vars: ('a * 'b * arg_mode_t) list -> 'b list val get_just_write_vars: ('a * 'b * arg_mode_t) list -> 'b list val get_bytecode : symbol_t -> bytecode_int option val copy_system : system_int -> system_int val get_first_and_last_in_state : method_info_int -> state_int -> int option * int val get_prev_pcs : method_info_int -> cfg_int -> state_int -> int list val start_timing: unit -> unit val add_timing: string -> unit val start_total_time: unit -> unit val get_total_time: unit -> float val start_time: unit -> unit val get_time: unit -> float val sym_to_pc: symbol_t -> int val is_not_jdk_method: symbol_t -> bool val start_profiling_time: int -> unit val stop_profiling_time: int -> unit val report_profiling_times: unit -> unit val report_profiling_times_no_reset: unit -> unit val print_warning_message: pretty_t -> unit val print_exception_message: pretty_t -> unit
372b8eee8a564cf8d4bb8485945dbb9f97e9282b2d9528b338098180a44ca805
Oblosys/proxima
Parser.hs
module Parser where import Data.Maybe import UU.Parsing import UU.Parsing.Machine(RealParser(..),RealRecogn(..),anaDynE,mkPR) import ConcreteSyntax import CommonTypes import Patterns import UU.Pretty(text,PP_Doc,empty,(>-<)) import TokenDef import List (intersperse) import Char import Scanner (Input(..),scanLit,input) import List import Expression import UU.Scanner.Token import UU.Scanner.TokenParser import UU.Scanner.GenToken import UU.Scanner.GenTokenParser import UU.Scanner.Position import UU.Scanner.TokenShow() import System.Directory import HsTokenScanner import Options type AGParser = AnaParser Input Pair Token Pos pIdentifier, pIdentifierU :: AGParser Identifier pIdentifierU = uncurry Ident <$> pConidPos pIdentifier = uncurry Ident <$> pVaridPos parseAG :: Options -> [FilePath] -> String -> IO (AG,[Message Token Pos]) parseAG opts searchPath file = do (es,_,_,mesg) <- parseFile opts searchPath file return (AG es, mesg) depsAG :: Options -> [FilePath] -> String -> IO ([String], [Message Token Pos]) depsAG opts searchPath file = do (_,_,fs,mesgs) <- parseFile opts searchPath file return (fs, mesgs) parseFile :: Options -> [FilePath] -> String -> IO ([Elem],[String],[String],[Message Token Pos ]) parseFile opts searchPath file = do txt <- readFile file let litMode = ".lag" `isSuffixOf` file (files,text) = if litMode then scanLit txt else ([],txt) tokens = input opts (initPos file) text steps = parse (pElemsFiles opts) tokens stop (_,fs,_,_) = null fs cont (es,fs,allfs,msg) = do files <- mapM (resolveFile searchPath) fs res <- mapM (parseFile opts searchPath) files let (ess,fss,allfss, msgs) = unzip4 res return (es ++ concat ess, concat fss, concat allfss ++ allfs, msg ++ concat msgs) let (Pair (es,fls) _ ,mesg) = evalStepsMessages steps let allfs = files ++ fls loopp stop cont (es,allfs,allfs,mesg) resolveFile :: [FilePath] -> FilePath -> IO FilePath resolveFile path fname = search (path ++ ["."]) where search (p:ps) = do dExists <- doesDirectoryExist p if dExists then do let filename = p++pathSeparator++fname fExists <- doesFileExist filename if fExists then return filename else search ps else search ps search [] = error ("File: " ++ show fname ++ " not found in search path: " ++ show (concat (intersperse ";" (path ++ ["."]))) ) pathSeparator = "/" evalStepsMessages :: (Eq s, Show s, Show p) => Steps a s p -> (a,[Message s p]) evalStepsMessages steps = case steps of OkVal v rest -> let (arg,ms) = evalStepsMessages rest in (v arg,ms) Ok rest -> evalStepsMessages rest Cost _ rest -> evalStepsMessages rest StRepair _ msg rest -> let (v,ms) = evalStepsMessages rest in (v, msg:ms) Best _ rest _ -> evalStepsMessages rest NoMoreSteps v -> (v,[]) loopp ::(a->Bool) -> (a->IO a) -> a -> IO a loopp pred cont x | pred x = return x | otherwise = do x' <- cont x loopp pred cont x' pElemsFiles :: Options -> AGParser ([Elem],[String]) pElemsFiles opts = pFoldr (($),([],[])) pElem' where pElem' = addElem <$> pElem opts <|> pINCLUDE *> (addInc <$> pStringPos) addElem e (es,fs) = (e:es, fs) addInc (fn,_) (es,fs) = ( es,fn:fs) pCodescrapL opts = (\(ValToken _ str pos) -> (str, pos))<$> parseScrapL opts <?> "a code block" parseScrapL :: Options -> AGParser Token parseScrapL opts = let p acc = (\k (Input pos str next) -> let (sc,rest) = case next of Just (t@(ValToken TkTextln _ _), rs) -> (t,rs) _ -> let (tok,p2,inp2) = codescrapL pos str in (tok, input opts p2 inp2) steps = k ( rest) in (val (acc sc) steps) ) in anaDynE (mkPR (P (p ), R (p (const id)))) codescrapL p [] = (valueToken TkTextln "" p,p,[]) codescrapL p (x:xs) | isSpace x = (updPos' x p) codescrapL xs | otherwise = let refcol = column p (p',sc,rest) = scrapL refcol p (x:xs) in (valueToken TkTextln sc p,p',rest) scrapL ref p (x:xs) | isSpace x || column p >= ref = let (p'',sc,inp) = updPos' x p (scrapL ref) xs in (p'',x:sc,inp) | otherwise =(p,[],x:xs) scrapL ref p [] = (p,[],[]) pNontSet = set0 where set0 = pChainr (Intersect <$ pIntersect) set1 set1 = pChainl (Difference <$ pMinus) set2 set2 = pChainr (pSucceed Union) set3 set3 = pIdentifierU <**> opt (flip Path <$ pArrow <*> pIdentifierU) NamedSet <|> All <$ pStar <|> pParens set0 pNames :: AGParser [Identifier] pNames = pList1 pIdentifier pAG : : Options - > AGParser AG pAG opts = AG < $ > pElems opts pElems :: Options -> AGParser Elems pElems opts = pList_ng (pElem opts) pComplexType opts = List <$> pBracks pTypeEncapsulated <|> Maybe <$ pMAYBE <*> pType <|> Either <$ pEITHER <*> pType <*> pType <|> Map <$ pMAP <*> pTypePrimitive <*> pType <|> IntMap <$ pINTMAP <*> pType <|> tuple <$> pParens (pListSep pComma field) where field = (,) <$> ((Just <$> pIdentifier <* pTypeColon opts) `opt` Nothing) <*> pTypeEncapsulated tuple xs = Tuple [(fromMaybe (Ident ("x"++show n) noPos) f, t) | (n,(f,t)) <- zip [1..] xs ] pElem :: Options -> AGParser Elem pElem opts = Data <$> pDATA <*> pOptClassContext <*> pNontSet <*> pList pIdentifier <*> pOptAttrs opts <*> pAlts opts <*> pSucceed False <|> Attr <$> pATTR <*> pOptClassContext <*> pNontSet <*> pAttrs opts <|> Type <$> pTYPE <*> pOptClassContext <*> pIdentifierU <*> pList pIdentifier <* pEquals <*> pComplexType opts <|> Sem <$> pSEM <*> pOptClassContext <*> pNontSet <*> pOptAttrs opts <*> pSemAlts opts <|> Set <$> pSET <*> pIdentifierU <* pEquals <*> pNontSet <|> Deriving <$> pDERIVING <*> pNontSet <* pColon <*> pListSep pComma pIdentifierU <|> Wrapper <$> pWRAPPER <*> pNontSet <|> Pragma <$> pPRAGMA <*> pNames <|> Module <$> pMODULE <*> pCodescrap' <*> pCodescrap' <*> pCodescrap' <|> codeBlock <$> (pIdentifier <|> pSucceed (Ident "" noPos)) <*> ((Just <$ pATTACH <*> pIdentifierU) <|> pSucceed Nothing) <*> pCodeBlock <?> "a statement" where codeBlock nm mbNt (txt,pos) = Txt pos nm mbNt (lines txt) -- Insertion is expensive for pCodeBlock in order to prevent infinite inserts. pCodeBlock :: AGParser (String,Pos) pCodeBlock = pCostValToken 90 TkTextln "" <?> "a code block" pOptClassContext :: AGParser ClassContext pOptClassContext = pClassContext <* pDoubleArrow <|> pSucceed [] pClassContext :: AGParser ClassContext pClassContext = pListSep pComma ((,) <$> pIdentifierU <*> pList pTypeHaskellAnyAsString) pAttrs :: Options -> AGParser Attrs pAttrs opts = Attrs <$> pOBrackPos <*> (concat <$> pList (pInhAttrNames opts) <?> "inherited attribute declarations") <* pBar <*> (concat <$> pList (pAttrNames opts) <?> "chained attribute declarations" ) <* pBar <*> (concat <$> pList (pAttrNames opts) <?> "synthesised attribute declarations" ) <* pCBrack <|> (\ds -> Attrs (fst $ head ds) [n | (_,Left nms) <- ds, n <- nms] [] [n | (_,Right nms) <- ds, n <- nms]) <$> pList1 (pSingleAttrDefs opts) pSingleAttrDefs :: Options -> AGParser (Pos, Either AttrNames AttrNames) pSingleAttrDefs opts = (\p is -> (p, Left is)) <$> pINH <*> pList1Sep pComma (pSingleInhAttrDef opts) <|> (\p is -> (p, Right is)) <$> pSYN <*> pList1Sep pComma (pSingleSynAttrDef opts) pSingleInhAttrDef :: Options -> AGParser (Identifier,Type,(String,String,String)) pSingleInhAttrDef opts = (\v tp -> (v,tp,("","",""))) <$> pIdentifier <* pTypeColon opts <*> pType <?> "inh attribute declaration" pSingleSynAttrDef :: Options -> AGParser (Identifier,Type,(String,String,String)) pSingleSynAttrDef opts = (\v u tp -> (v,tp,u)) <$> pIdentifier <*> pUse <* pTypeColon opts <*> pType <?> "syn attribute declaration" pOptAttrs :: Options -> AGParser Attrs pOptAttrs opts = pAttrs opts `opt` Attrs noPos [] [] [] pTypeNt :: AGParser Type pTypeNt = ((\nt -> NT nt []) <$> pIdentifierU <?> "nonterminal name (no brackets)") <|> (pParens (NT <$> pIdentifierU <*> pList pTypeHaskellAnyAsString) <?> "nonterminal name with parameters (using parenthesis)") pTypeHaskellAnyAsString :: AGParser String pTypeHaskellAnyAsString = getName <$> pIdentifier <|> getName <$> pIdentifierU <|> pCodescrap' <?> "a type" -- if the type is within some kind of parentheses or brackets (then we allow lowercase identifiers as well) pTypeEncapsulated :: AGParser Type pTypeEncapsulated = pParens pTypeEncapsulated <|> NT <$> pIdentifierU <*> pList pTypeHaskellAnyAsString <|> (Haskell . getName) <$> pIdentifier <|> pTypePrimitive pTypePrimitive :: AGParser Type pTypePrimitive = Haskell <$> pCodescrap' <?> "a type" pType :: AGParser Type pType = pTypeNt <|> pTypePrimitive pInhAttrNames :: Options -> AGParser AttrNames pInhAttrNames opts = (\vs tp -> map (\v -> (v,tp,("","",""))) vs) <$> pIdentifiers <* pTypeColon opts <*> pType <?> "attribute declarations" pIdentifiers :: AGParser [Identifier] pIdentifiers = pList1Sep pComma pIdentifier <?> "lowercase identifiers" pAttrNames :: Options -> AGParser AttrNames pAttrNames opts = (\vs use tp -> map (\v -> (v,tp,use)) vs) <$> pIdentifiers <*> pUse <* pTypeColon opts <*> pType <?> "attribute declarations" pUse :: AGParser (String,String,String) pUse = ( (\u x y->(x,y,show u)) <$> pUSE <*> pCodescrap' <*> pCodescrap')` opt` ("","","") <?> "USE declaration" pAlt :: Options -> AGParser Alt pAlt opts = Alt <$> pBar <*> pSimpleConstructorSet <*> pFields opts <?> "a datatype alternative" pAlts :: Options -> AGParser Alts pAlts opts = pList_ng (pAlt opts) <?> "datatype alternatives" pFields :: Options -> AGParser Fields pFields opts = concat <$> pList_ng (pField opts) <?> "fields" pField :: Options -> AGParser Fields pField opts = (\nms tp -> map (flip (,) tp) nms) <$> pIdentifiers <* pTypeColon opts <*> pType <|> (\s -> [(Ident (mklower (getName s)) (getPos s) ,NT s [])]) <$> pIdentifierU mklower :: String -> String mklower (x:xs) = toLower x : xs mklower [] = [] pSemAlt :: Options -> AGParser SemAlt pSemAlt opts = SemAlt <$> pBar <*> pConstructorSet <*> pSemDefs opts <?> "SEM alternative" pSimpleConstructorSet :: AGParser ConstructorSet pSimpleConstructorSet = CName <$> pIdentifierU <|> CAll <$ pStar <|> pParens pConstructorSet pConstructorSet :: AGParser ConstructorSet pConstructorSet = pChainl (CDifference <$ pMinus) term2 where term2 = pChainr (pSucceed CUnion) term1 term1 = CName <$> pIdentifierU <|> CAll <$ pStar pSemAlts :: Options -> AGParser SemAlts pSemAlts opts = pList (pSemAlt opts) <?> "SEM alternatives" pFieldIdentifier :: AGParser Identifier pFieldIdentifier = pIdentifier <|> Ident "lhs" <$> pLHS <|> Ident "loc" <$> pLOC <|> Ident "inst" <$> pINST pSemDef :: Options -> AGParser [SemDef] pSemDef opts = (\x fs -> map ($ x) fs)<$> pFieldIdentifier <*> pList1 (pAttrDef opts) <|> pLOC *> pList1 (pLocDecl opts) <|> pINST *> pList1 (pInstDecl opts) <|> pSEMPRAGMA *> pList1 (SemPragma <$> pNames) <|> (\a b -> [AttrOrderBefore a [b]]) <$> pList1 pAttr <* pSmaller <*> pAttr <|> (\pat owrt exp -> [Def (pat ()) exp owrt]) <$> pPattern (const <$> pAttr) <*> pAssign <*> pExpr opts pAttr = (,) <$> pFieldIdentifier <* pDot <*> pIdentifier pAttrDef :: Options -> AGParser (Identifier -> SemDef) pAttrDef opts = (\pat owrt exp fld -> Def (pat fld) exp owrt) <$ pDot <*> pattern <*> pAssign <*> pExpr opts where pattern = pPattern pVar <|> (\ir a fld -> ir $ Alias fld a (Underscore noPos) []) <$> ((Irrefutable <$ pTilde) `opt` id) <*> pIdentifier nl2sp :: Char -> Char nl2sp '\n' = ' ' nl2sp '\r' = ' ' nl2sp x = x pLocDecl :: Options -> AGParser SemDef pLocDecl opts = pDot <**> (pIdentifier <**> (pTypeColon opts <**> ( (\tp _ ident _ -> TypeDef ident tp) <$> pLocType <|> (\ref _ ident _ -> UniqueDef ident ref) <$ pUNIQUEREF <*> pIdentifier ))) pLocType = (Haskell . getName) <$> pIdentifierU <|> Haskell <$> pCodescrap' <?> "a type" pInstDecl :: Options -> AGParser SemDef pInstDecl opts = (\ident tp -> TypeDef ident tp) <$ pDot <*> pIdentifier <* pTypeColon opts <*> pTypeNt pSemDefs :: Options -> AGParser SemDefs pSemDefs opts = concat <$> pList_ng (pSemDef opts) <?> "attribute rules" pVar :: AGParser (Identifier -> (Identifier, Identifier)) pVar = (\att fld -> (fld,att)) <$> pIdentifier pExpr :: Options -> AGParser Expression pExpr opts = (\(str,pos) -> Expression pos (lexTokens pos str)) <$> pCodescrapL opts <?> "an expression" pAssign :: AGParser Bool pAssign = False <$ pReserved "=" <|> True <$ pReserved ":=" pAttrDefs : : Options - > AGParser ( Identifier - > [ SemDef ] ) pAttrDefs opts = ( \fs field - > map ( $ field ) fs ) < $ > pList1 ( pAttrDef opts ) < ? > " attribute definitions " pPattern :: AGParser (a -> (Identifier,Identifier)) -> AGParser (a -> Pattern) pPattern pvar = pPattern2 where pPattern0 = (\i pats a -> Constr i (map ($ a) pats)) <$> pIdentifierU <*> pList pPattern1 <|> pPattern1 <?> "a pattern" pPattern1 = pvariable <|> pPattern2 pvariable = (\ir var pat a -> case var a of (fld,att) -> ir $ Alias fld att (pat a) []) <$> ((Irrefutable <$ pTilde) `opt` id) <*> pvar <*> ((pAt *> pPattern1) `opt` const (Underscore noPos)) pPattern2 = (mkTuple <$> pOParenPos <*> pListSep pComma pPattern0 <* pCParen ) <|> (const . Underscore) <$> pUScore <?> "a pattern" where mkTuple _ [x] a = x a mkTuple p xs a = Product p (map ($ a) xs) pCostSym' c t = pCostSym c t t pCodescrap' :: AGParser String pCodescrap' = fst <$> pCodescrap pCodescrap :: AGParser (String,Pos) pCodescrap = pCodeBlock pTypeColon :: Options -> AGParser Pos pTypeColon opts = if doubleColons opts then pDoubleColon else pColon pSEM, pATTR, pDATA, pUSE, pLOC,pINCLUDE, pTYPE, pEquals, pColonEquals, pTilde, pBar, pColon, pLHS,pINST,pSET,pDERIVING,pMinus,pIntersect,pDoubleArrow,pArrow, pDot, pUScore, pEXT,pAt,pStar, pSmaller, pWRAPPER, pPRAGMA, pMAYBE, pEITHER, pMAP, pINTMAP, pMODULE, pATTACH, pUNIQUEREF, pINH, pSYN :: AGParser Pos pSET = pCostReserved 90 "SET" <?> "SET" pDERIVING = pCostReserved 90 "DERIVING"<?> "DERIVING" pWRAPPER = pCostReserved 90 "WRAPPER" <?> "WRAPPER" pPRAGMA = pCostReserved 90 "PRAGMA" <?> "PRAGMA" pSEMPRAGMA = pCostReserved 90 "SEMPRAGMA" <?> "SEMPRAGMA" pATTACH = pCostReserved 90 "ATTACH" <?> "ATTACH" pDATA = pCostReserved 90 "DATA" <?> "DATA" pEXT = pCostReserved 90 "EXT" <?> "EXT" pATTR = pCostReserved 90 "ATTR" <?> "ATTR" pSEM = pCostReserved 90 "SEM" <?> "SEM" pINCLUDE = pCostReserved 90 "INCLUDE" <?> "INCLUDE" pTYPE = pCostReserved 90 "TYPE" <?> "TYPE" pINH = pCostReserved 90 "INH" <?> "INH" pSYN = pCostReserved 90 "SYN" <?> "SYN" pMAYBE = pCostReserved 5 "MAYBE" <?> "MAYBE" pEITHER = pCostReserved 5 "EITHER" <?> "EITHER" pMAP = pCostReserved 5 "MAP" <?> "MAP" pINTMAP = pCostReserved 5 "INTMAP" <?> "INTMAP" pUSE = pCostReserved 5 "USE" <?> "USE" pLOC = pCostReserved 5 "loc" <?> "loc" pLHS = pCostReserved 5 "lhs" <?> "loc" pINST = pCostReserved 5 "inst" <?> "inst" pAt = pCostReserved 5 "@" <?> "@" pDot = pCostReserved 5 "." <?> "." pUScore = pCostReserved 5 "_" <?> "_" pColon = pCostReserved 5 ":" <?> ":" pDoubleColon = pCostReserved 5 "::" <?> "::" pEquals = pCostReserved 5 "=" <?> "=" pColonEquals = pCostReserved 5 ":=" <?> ":=" pTilde = pCostReserved 5 "~" <?> "~" pBar = pCostReserved 5 "|" <?> "|" pIntersect = pCostReserved 5 "/\\" <?> "/\\" pMinus = pCostReserved 5 "-" <?> "-" pDoubleArrow = pCostReserved 5 "=>" <?> "=>" pArrow = pCostReserved 5 "->" <?> "->" pStar = pCostReserved 5 "*" <?> "*" pSmaller = pCostReserved 5 "<" <?> "<" pMODULE = pCostReserved 5 "MODULE" <?> "MODULE" pUNIQUEREF = pCostReserved 5 "UNIQUEREF" <?> "UNIQUEREF"
null
https://raw.githubusercontent.com/Oblosys/proxima/f154dff2ccb8afe00eeb325d9d06f5e2a5ee7589/uuagc/src/Parser.hs
haskell
Insertion is expensive for pCodeBlock in order to prevent infinite inserts. if the type is within some kind of parentheses or brackets (then we allow lowercase identifiers as well)
module Parser where import Data.Maybe import UU.Parsing import UU.Parsing.Machine(RealParser(..),RealRecogn(..),anaDynE,mkPR) import ConcreteSyntax import CommonTypes import Patterns import UU.Pretty(text,PP_Doc,empty,(>-<)) import TokenDef import List (intersperse) import Char import Scanner (Input(..),scanLit,input) import List import Expression import UU.Scanner.Token import UU.Scanner.TokenParser import UU.Scanner.GenToken import UU.Scanner.GenTokenParser import UU.Scanner.Position import UU.Scanner.TokenShow() import System.Directory import HsTokenScanner import Options type AGParser = AnaParser Input Pair Token Pos pIdentifier, pIdentifierU :: AGParser Identifier pIdentifierU = uncurry Ident <$> pConidPos pIdentifier = uncurry Ident <$> pVaridPos parseAG :: Options -> [FilePath] -> String -> IO (AG,[Message Token Pos]) parseAG opts searchPath file = do (es,_,_,mesg) <- parseFile opts searchPath file return (AG es, mesg) depsAG :: Options -> [FilePath] -> String -> IO ([String], [Message Token Pos]) depsAG opts searchPath file = do (_,_,fs,mesgs) <- parseFile opts searchPath file return (fs, mesgs) parseFile :: Options -> [FilePath] -> String -> IO ([Elem],[String],[String],[Message Token Pos ]) parseFile opts searchPath file = do txt <- readFile file let litMode = ".lag" `isSuffixOf` file (files,text) = if litMode then scanLit txt else ([],txt) tokens = input opts (initPos file) text steps = parse (pElemsFiles opts) tokens stop (_,fs,_,_) = null fs cont (es,fs,allfs,msg) = do files <- mapM (resolveFile searchPath) fs res <- mapM (parseFile opts searchPath) files let (ess,fss,allfss, msgs) = unzip4 res return (es ++ concat ess, concat fss, concat allfss ++ allfs, msg ++ concat msgs) let (Pair (es,fls) _ ,mesg) = evalStepsMessages steps let allfs = files ++ fls loopp stop cont (es,allfs,allfs,mesg) resolveFile :: [FilePath] -> FilePath -> IO FilePath resolveFile path fname = search (path ++ ["."]) where search (p:ps) = do dExists <- doesDirectoryExist p if dExists then do let filename = p++pathSeparator++fname fExists <- doesFileExist filename if fExists then return filename else search ps else search ps search [] = error ("File: " ++ show fname ++ " not found in search path: " ++ show (concat (intersperse ";" (path ++ ["."]))) ) pathSeparator = "/" evalStepsMessages :: (Eq s, Show s, Show p) => Steps a s p -> (a,[Message s p]) evalStepsMessages steps = case steps of OkVal v rest -> let (arg,ms) = evalStepsMessages rest in (v arg,ms) Ok rest -> evalStepsMessages rest Cost _ rest -> evalStepsMessages rest StRepair _ msg rest -> let (v,ms) = evalStepsMessages rest in (v, msg:ms) Best _ rest _ -> evalStepsMessages rest NoMoreSteps v -> (v,[]) loopp ::(a->Bool) -> (a->IO a) -> a -> IO a loopp pred cont x | pred x = return x | otherwise = do x' <- cont x loopp pred cont x' pElemsFiles :: Options -> AGParser ([Elem],[String]) pElemsFiles opts = pFoldr (($),([],[])) pElem' where pElem' = addElem <$> pElem opts <|> pINCLUDE *> (addInc <$> pStringPos) addElem e (es,fs) = (e:es, fs) addInc (fn,_) (es,fs) = ( es,fn:fs) pCodescrapL opts = (\(ValToken _ str pos) -> (str, pos))<$> parseScrapL opts <?> "a code block" parseScrapL :: Options -> AGParser Token parseScrapL opts = let p acc = (\k (Input pos str next) -> let (sc,rest) = case next of Just (t@(ValToken TkTextln _ _), rs) -> (t,rs) _ -> let (tok,p2,inp2) = codescrapL pos str in (tok, input opts p2 inp2) steps = k ( rest) in (val (acc sc) steps) ) in anaDynE (mkPR (P (p ), R (p (const id)))) codescrapL p [] = (valueToken TkTextln "" p,p,[]) codescrapL p (x:xs) | isSpace x = (updPos' x p) codescrapL xs | otherwise = let refcol = column p (p',sc,rest) = scrapL refcol p (x:xs) in (valueToken TkTextln sc p,p',rest) scrapL ref p (x:xs) | isSpace x || column p >= ref = let (p'',sc,inp) = updPos' x p (scrapL ref) xs in (p'',x:sc,inp) | otherwise =(p,[],x:xs) scrapL ref p [] = (p,[],[]) pNontSet = set0 where set0 = pChainr (Intersect <$ pIntersect) set1 set1 = pChainl (Difference <$ pMinus) set2 set2 = pChainr (pSucceed Union) set3 set3 = pIdentifierU <**> opt (flip Path <$ pArrow <*> pIdentifierU) NamedSet <|> All <$ pStar <|> pParens set0 pNames :: AGParser [Identifier] pNames = pList1 pIdentifier pAG : : Options - > AGParser AG pAG opts = AG < $ > pElems opts pElems :: Options -> AGParser Elems pElems opts = pList_ng (pElem opts) pComplexType opts = List <$> pBracks pTypeEncapsulated <|> Maybe <$ pMAYBE <*> pType <|> Either <$ pEITHER <*> pType <*> pType <|> Map <$ pMAP <*> pTypePrimitive <*> pType <|> IntMap <$ pINTMAP <*> pType <|> tuple <$> pParens (pListSep pComma field) where field = (,) <$> ((Just <$> pIdentifier <* pTypeColon opts) `opt` Nothing) <*> pTypeEncapsulated tuple xs = Tuple [(fromMaybe (Ident ("x"++show n) noPos) f, t) | (n,(f,t)) <- zip [1..] xs ] pElem :: Options -> AGParser Elem pElem opts = Data <$> pDATA <*> pOptClassContext <*> pNontSet <*> pList pIdentifier <*> pOptAttrs opts <*> pAlts opts <*> pSucceed False <|> Attr <$> pATTR <*> pOptClassContext <*> pNontSet <*> pAttrs opts <|> Type <$> pTYPE <*> pOptClassContext <*> pIdentifierU <*> pList pIdentifier <* pEquals <*> pComplexType opts <|> Sem <$> pSEM <*> pOptClassContext <*> pNontSet <*> pOptAttrs opts <*> pSemAlts opts <|> Set <$> pSET <*> pIdentifierU <* pEquals <*> pNontSet <|> Deriving <$> pDERIVING <*> pNontSet <* pColon <*> pListSep pComma pIdentifierU <|> Wrapper <$> pWRAPPER <*> pNontSet <|> Pragma <$> pPRAGMA <*> pNames <|> Module <$> pMODULE <*> pCodescrap' <*> pCodescrap' <*> pCodescrap' <|> codeBlock <$> (pIdentifier <|> pSucceed (Ident "" noPos)) <*> ((Just <$ pATTACH <*> pIdentifierU) <|> pSucceed Nothing) <*> pCodeBlock <?> "a statement" where codeBlock nm mbNt (txt,pos) = Txt pos nm mbNt (lines txt) pCodeBlock :: AGParser (String,Pos) pCodeBlock = pCostValToken 90 TkTextln "" <?> "a code block" pOptClassContext :: AGParser ClassContext pOptClassContext = pClassContext <* pDoubleArrow <|> pSucceed [] pClassContext :: AGParser ClassContext pClassContext = pListSep pComma ((,) <$> pIdentifierU <*> pList pTypeHaskellAnyAsString) pAttrs :: Options -> AGParser Attrs pAttrs opts = Attrs <$> pOBrackPos <*> (concat <$> pList (pInhAttrNames opts) <?> "inherited attribute declarations") <* pBar <*> (concat <$> pList (pAttrNames opts) <?> "chained attribute declarations" ) <* pBar <*> (concat <$> pList (pAttrNames opts) <?> "synthesised attribute declarations" ) <* pCBrack <|> (\ds -> Attrs (fst $ head ds) [n | (_,Left nms) <- ds, n <- nms] [] [n | (_,Right nms) <- ds, n <- nms]) <$> pList1 (pSingleAttrDefs opts) pSingleAttrDefs :: Options -> AGParser (Pos, Either AttrNames AttrNames) pSingleAttrDefs opts = (\p is -> (p, Left is)) <$> pINH <*> pList1Sep pComma (pSingleInhAttrDef opts) <|> (\p is -> (p, Right is)) <$> pSYN <*> pList1Sep pComma (pSingleSynAttrDef opts) pSingleInhAttrDef :: Options -> AGParser (Identifier,Type,(String,String,String)) pSingleInhAttrDef opts = (\v tp -> (v,tp,("","",""))) <$> pIdentifier <* pTypeColon opts <*> pType <?> "inh attribute declaration" pSingleSynAttrDef :: Options -> AGParser (Identifier,Type,(String,String,String)) pSingleSynAttrDef opts = (\v u tp -> (v,tp,u)) <$> pIdentifier <*> pUse <* pTypeColon opts <*> pType <?> "syn attribute declaration" pOptAttrs :: Options -> AGParser Attrs pOptAttrs opts = pAttrs opts `opt` Attrs noPos [] [] [] pTypeNt :: AGParser Type pTypeNt = ((\nt -> NT nt []) <$> pIdentifierU <?> "nonterminal name (no brackets)") <|> (pParens (NT <$> pIdentifierU <*> pList pTypeHaskellAnyAsString) <?> "nonterminal name with parameters (using parenthesis)") pTypeHaskellAnyAsString :: AGParser String pTypeHaskellAnyAsString = getName <$> pIdentifier <|> getName <$> pIdentifierU <|> pCodescrap' <?> "a type" pTypeEncapsulated :: AGParser Type pTypeEncapsulated = pParens pTypeEncapsulated <|> NT <$> pIdentifierU <*> pList pTypeHaskellAnyAsString <|> (Haskell . getName) <$> pIdentifier <|> pTypePrimitive pTypePrimitive :: AGParser Type pTypePrimitive = Haskell <$> pCodescrap' <?> "a type" pType :: AGParser Type pType = pTypeNt <|> pTypePrimitive pInhAttrNames :: Options -> AGParser AttrNames pInhAttrNames opts = (\vs tp -> map (\v -> (v,tp,("","",""))) vs) <$> pIdentifiers <* pTypeColon opts <*> pType <?> "attribute declarations" pIdentifiers :: AGParser [Identifier] pIdentifiers = pList1Sep pComma pIdentifier <?> "lowercase identifiers" pAttrNames :: Options -> AGParser AttrNames pAttrNames opts = (\vs use tp -> map (\v -> (v,tp,use)) vs) <$> pIdentifiers <*> pUse <* pTypeColon opts <*> pType <?> "attribute declarations" pUse :: AGParser (String,String,String) pUse = ( (\u x y->(x,y,show u)) <$> pUSE <*> pCodescrap' <*> pCodescrap')` opt` ("","","") <?> "USE declaration" pAlt :: Options -> AGParser Alt pAlt opts = Alt <$> pBar <*> pSimpleConstructorSet <*> pFields opts <?> "a datatype alternative" pAlts :: Options -> AGParser Alts pAlts opts = pList_ng (pAlt opts) <?> "datatype alternatives" pFields :: Options -> AGParser Fields pFields opts = concat <$> pList_ng (pField opts) <?> "fields" pField :: Options -> AGParser Fields pField opts = (\nms tp -> map (flip (,) tp) nms) <$> pIdentifiers <* pTypeColon opts <*> pType <|> (\s -> [(Ident (mklower (getName s)) (getPos s) ,NT s [])]) <$> pIdentifierU mklower :: String -> String mklower (x:xs) = toLower x : xs mklower [] = [] pSemAlt :: Options -> AGParser SemAlt pSemAlt opts = SemAlt <$> pBar <*> pConstructorSet <*> pSemDefs opts <?> "SEM alternative" pSimpleConstructorSet :: AGParser ConstructorSet pSimpleConstructorSet = CName <$> pIdentifierU <|> CAll <$ pStar <|> pParens pConstructorSet pConstructorSet :: AGParser ConstructorSet pConstructorSet = pChainl (CDifference <$ pMinus) term2 where term2 = pChainr (pSucceed CUnion) term1 term1 = CName <$> pIdentifierU <|> CAll <$ pStar pSemAlts :: Options -> AGParser SemAlts pSemAlts opts = pList (pSemAlt opts) <?> "SEM alternatives" pFieldIdentifier :: AGParser Identifier pFieldIdentifier = pIdentifier <|> Ident "lhs" <$> pLHS <|> Ident "loc" <$> pLOC <|> Ident "inst" <$> pINST pSemDef :: Options -> AGParser [SemDef] pSemDef opts = (\x fs -> map ($ x) fs)<$> pFieldIdentifier <*> pList1 (pAttrDef opts) <|> pLOC *> pList1 (pLocDecl opts) <|> pINST *> pList1 (pInstDecl opts) <|> pSEMPRAGMA *> pList1 (SemPragma <$> pNames) <|> (\a b -> [AttrOrderBefore a [b]]) <$> pList1 pAttr <* pSmaller <*> pAttr <|> (\pat owrt exp -> [Def (pat ()) exp owrt]) <$> pPattern (const <$> pAttr) <*> pAssign <*> pExpr opts pAttr = (,) <$> pFieldIdentifier <* pDot <*> pIdentifier pAttrDef :: Options -> AGParser (Identifier -> SemDef) pAttrDef opts = (\pat owrt exp fld -> Def (pat fld) exp owrt) <$ pDot <*> pattern <*> pAssign <*> pExpr opts where pattern = pPattern pVar <|> (\ir a fld -> ir $ Alias fld a (Underscore noPos) []) <$> ((Irrefutable <$ pTilde) `opt` id) <*> pIdentifier nl2sp :: Char -> Char nl2sp '\n' = ' ' nl2sp '\r' = ' ' nl2sp x = x pLocDecl :: Options -> AGParser SemDef pLocDecl opts = pDot <**> (pIdentifier <**> (pTypeColon opts <**> ( (\tp _ ident _ -> TypeDef ident tp) <$> pLocType <|> (\ref _ ident _ -> UniqueDef ident ref) <$ pUNIQUEREF <*> pIdentifier ))) pLocType = (Haskell . getName) <$> pIdentifierU <|> Haskell <$> pCodescrap' <?> "a type" pInstDecl :: Options -> AGParser SemDef pInstDecl opts = (\ident tp -> TypeDef ident tp) <$ pDot <*> pIdentifier <* pTypeColon opts <*> pTypeNt pSemDefs :: Options -> AGParser SemDefs pSemDefs opts = concat <$> pList_ng (pSemDef opts) <?> "attribute rules" pVar :: AGParser (Identifier -> (Identifier, Identifier)) pVar = (\att fld -> (fld,att)) <$> pIdentifier pExpr :: Options -> AGParser Expression pExpr opts = (\(str,pos) -> Expression pos (lexTokens pos str)) <$> pCodescrapL opts <?> "an expression" pAssign :: AGParser Bool pAssign = False <$ pReserved "=" <|> True <$ pReserved ":=" pAttrDefs : : Options - > AGParser ( Identifier - > [ SemDef ] ) pAttrDefs opts = ( \fs field - > map ( $ field ) fs ) < $ > pList1 ( pAttrDef opts ) < ? > " attribute definitions " pPattern :: AGParser (a -> (Identifier,Identifier)) -> AGParser (a -> Pattern) pPattern pvar = pPattern2 where pPattern0 = (\i pats a -> Constr i (map ($ a) pats)) <$> pIdentifierU <*> pList pPattern1 <|> pPattern1 <?> "a pattern" pPattern1 = pvariable <|> pPattern2 pvariable = (\ir var pat a -> case var a of (fld,att) -> ir $ Alias fld att (pat a) []) <$> ((Irrefutable <$ pTilde) `opt` id) <*> pvar <*> ((pAt *> pPattern1) `opt` const (Underscore noPos)) pPattern2 = (mkTuple <$> pOParenPos <*> pListSep pComma pPattern0 <* pCParen ) <|> (const . Underscore) <$> pUScore <?> "a pattern" where mkTuple _ [x] a = x a mkTuple p xs a = Product p (map ($ a) xs) pCostSym' c t = pCostSym c t t pCodescrap' :: AGParser String pCodescrap' = fst <$> pCodescrap pCodescrap :: AGParser (String,Pos) pCodescrap = pCodeBlock pTypeColon :: Options -> AGParser Pos pTypeColon opts = if doubleColons opts then pDoubleColon else pColon pSEM, pATTR, pDATA, pUSE, pLOC,pINCLUDE, pTYPE, pEquals, pColonEquals, pTilde, pBar, pColon, pLHS,pINST,pSET,pDERIVING,pMinus,pIntersect,pDoubleArrow,pArrow, pDot, pUScore, pEXT,pAt,pStar, pSmaller, pWRAPPER, pPRAGMA, pMAYBE, pEITHER, pMAP, pINTMAP, pMODULE, pATTACH, pUNIQUEREF, pINH, pSYN :: AGParser Pos pSET = pCostReserved 90 "SET" <?> "SET" pDERIVING = pCostReserved 90 "DERIVING"<?> "DERIVING" pWRAPPER = pCostReserved 90 "WRAPPER" <?> "WRAPPER" pPRAGMA = pCostReserved 90 "PRAGMA" <?> "PRAGMA" pSEMPRAGMA = pCostReserved 90 "SEMPRAGMA" <?> "SEMPRAGMA" pATTACH = pCostReserved 90 "ATTACH" <?> "ATTACH" pDATA = pCostReserved 90 "DATA" <?> "DATA" pEXT = pCostReserved 90 "EXT" <?> "EXT" pATTR = pCostReserved 90 "ATTR" <?> "ATTR" pSEM = pCostReserved 90 "SEM" <?> "SEM" pINCLUDE = pCostReserved 90 "INCLUDE" <?> "INCLUDE" pTYPE = pCostReserved 90 "TYPE" <?> "TYPE" pINH = pCostReserved 90 "INH" <?> "INH" pSYN = pCostReserved 90 "SYN" <?> "SYN" pMAYBE = pCostReserved 5 "MAYBE" <?> "MAYBE" pEITHER = pCostReserved 5 "EITHER" <?> "EITHER" pMAP = pCostReserved 5 "MAP" <?> "MAP" pINTMAP = pCostReserved 5 "INTMAP" <?> "INTMAP" pUSE = pCostReserved 5 "USE" <?> "USE" pLOC = pCostReserved 5 "loc" <?> "loc" pLHS = pCostReserved 5 "lhs" <?> "loc" pINST = pCostReserved 5 "inst" <?> "inst" pAt = pCostReserved 5 "@" <?> "@" pDot = pCostReserved 5 "." <?> "." pUScore = pCostReserved 5 "_" <?> "_" pColon = pCostReserved 5 ":" <?> ":" pDoubleColon = pCostReserved 5 "::" <?> "::" pEquals = pCostReserved 5 "=" <?> "=" pColonEquals = pCostReserved 5 ":=" <?> ":=" pTilde = pCostReserved 5 "~" <?> "~" pBar = pCostReserved 5 "|" <?> "|" pIntersect = pCostReserved 5 "/\\" <?> "/\\" pMinus = pCostReserved 5 "-" <?> "-" pDoubleArrow = pCostReserved 5 "=>" <?> "=>" pArrow = pCostReserved 5 "->" <?> "->" pStar = pCostReserved 5 "*" <?> "*" pSmaller = pCostReserved 5 "<" <?> "<" pMODULE = pCostReserved 5 "MODULE" <?> "MODULE" pUNIQUEREF = pCostReserved 5 "UNIQUEREF" <?> "UNIQUEREF"
4e8b913797d97b84c7631a8f7ad8bafd2de0773cffc10abc9f77d99fc91fdaf0
music-suite/music-suite
StaffNumber.hs
# LANGUAGE DefaultSignatures # # OPTIONS_GHC -fno - warn - unused - imports # module Music.Score.StaffNumber ( -- * StaffNumber HasStaffNumber (..), staffNumber, * * StaffNumber note transformer StaffNumberT (..), runStaffNumberT, ) where import Control.Applicative import Control.Comonad import Control.Lens hiding (transform) import Data.Foldable import Data.Functor.Couple import Data.Monoid import Data.Ratio import Data.Typeable import Music.Dynamics.Literal import Music.Pitch.Alterable import Music.Pitch.Augmentable import Music.Pitch.Literal import Music.Score.Articulation import Music.Score.Dynamics import Music.Score.Harmonics import Music.Score.Meta import Music.Score.Part import Music.Score.Phrases import Music.Score.Pitch import Music.Score.Slide import Music.Score.Text import Music.Score.Ties import Music.Time import Numeric.Natural -- | -- Class of types with a notion of staff number. -- -- ==== Laws -- -- [/set-set/] -- @'setStaffNumber ' n ( ' setStaffNumber ' n x ) = ' setStaffNumber ' n class HasStaffNumber a where setStaffNumber :: Natural -> a -> a default setStaffNumber :: forall f b. (a ~ f b, Functor f, HasStaffNumber b) => Natural -> a -> a setStaffNumber s = fmap (setStaffNumber s) instance HasStaffNumber a => HasStaffNumber (b, a) instance HasStaffNumber a => HasStaffNumber (Couple b a) instance HasStaffNumber a => HasStaffNumber [a] instance HasStaffNumber a => HasStaffNumber (Score a) staffNumber :: HasStaffNumber a => Natural -> a -> a staffNumber = setStaffNumber newtype StaffNumberT a = StaffNumberT {getStaffNumberT :: Couple (First Natural) a} deriving (Eq, Show, Ord, Functor, Foldable, Traversable, Typeable, Applicative, Monad, Comonad) instance Wrapped (StaffNumberT a) where type Unwrapped (StaffNumberT a) = Couple (First Natural) a _Wrapped' = iso getStaffNumberT StaffNumberT instance Rewrapped (StaffNumberT a) (StaffNumberT b) instance HasStaffNumber (StaffNumberT a) where setStaffNumber n = set (_Wrapped . _Wrapped . _1) (First $ Just n) deriving instance Num a => Num (StaffNumberT a) deriving instance Fractional a => Fractional (StaffNumberT a) deriving instance Floating a => Floating (StaffNumberT a) deriving instance Enum a => Enum (StaffNumberT a) deriving instance Bounded a => Bounded (StaffNumberT a) deriving instance (Num a, Ord a, Real a) => Real (StaffNumberT a) deriving instance (Real a, Enum a, Integral a) => Integral (StaffNumberT a) deriving instance IsPitch a => IsPitch (StaffNumberT a) deriving instance IsDynamics a => IsDynamics (StaffNumberT a) deriving instance Semigroup a => Semigroup (StaffNumberT a) deriving instance Tiable a => Tiable (StaffNumberT a) deriving instance HasHarmonic a => HasHarmonic (StaffNumberT a) deriving instance HasSlide a => HasSlide (StaffNumberT a) deriving instance HasText a => HasText (StaffNumberT a) deriving instance Transformable a => Transformable (StaffNumberT a) deriving instance Alterable a => Alterable (StaffNumberT a) deriving instance Augmentable a => Augmentable (StaffNumberT a) type instance GetPitch (StaffNumberT a) = GetPitch a type instance SetPitch g (StaffNumberT a) = StaffNumberT (SetPitch g a) type instance GetDynamic (StaffNumberT a) = GetDynamic a type instance SetDynamic g (StaffNumberT a) = StaffNumberT (SetDynamic g a) type instance GetArticulation (StaffNumberT a) = GetArticulation a type instance SetArticulation g (StaffNumberT a) = StaffNumberT (SetArticulation g a) instance (HasPitches a b) => HasPitches (StaffNumberT a) (StaffNumberT b) where pitches = _Wrapped . pitches instance (HasPitch a b) => HasPitch (StaffNumberT a) (StaffNumberT b) where pitch = _Wrapped . pitch instance (HasDynamics a b) => HasDynamics (StaffNumberT a) (StaffNumberT b) where dynamics = _Wrapped . dynamics instance (HasDynamic a b) => HasDynamic (StaffNumberT a) (StaffNumberT b) where dynamic = _Wrapped . dynamic instance (HasArticulations a b) => HasArticulations (StaffNumberT a) (StaffNumberT b) where articulations = _Wrapped . articulations instance (HasArticulation a b) => HasArticulation (StaffNumberT a) (StaffNumberT b) where articulation = _Wrapped . articulation runStaffNumberT :: StaffNumberT a -> (Natural, a) runStaffNumberT (StaffNumberT (Couple (First n, a))) = (maybe 0 id n, a)
null
https://raw.githubusercontent.com/music-suite/music-suite/7f01fd62334c66418043b7a2d662af127f98685d/src/Music/Score/StaffNumber.hs
haskell
* StaffNumber | Class of types with a notion of staff number. ==== Laws [/set-set/]
# LANGUAGE DefaultSignatures # # OPTIONS_GHC -fno - warn - unused - imports # module Music.Score.StaffNumber HasStaffNumber (..), staffNumber, * * StaffNumber note transformer StaffNumberT (..), runStaffNumberT, ) where import Control.Applicative import Control.Comonad import Control.Lens hiding (transform) import Data.Foldable import Data.Functor.Couple import Data.Monoid import Data.Ratio import Data.Typeable import Music.Dynamics.Literal import Music.Pitch.Alterable import Music.Pitch.Augmentable import Music.Pitch.Literal import Music.Score.Articulation import Music.Score.Dynamics import Music.Score.Harmonics import Music.Score.Meta import Music.Score.Part import Music.Score.Phrases import Music.Score.Pitch import Music.Score.Slide import Music.Score.Text import Music.Score.Ties import Music.Time import Numeric.Natural @'setStaffNumber ' n ( ' setStaffNumber ' n x ) = ' setStaffNumber ' n class HasStaffNumber a where setStaffNumber :: Natural -> a -> a default setStaffNumber :: forall f b. (a ~ f b, Functor f, HasStaffNumber b) => Natural -> a -> a setStaffNumber s = fmap (setStaffNumber s) instance HasStaffNumber a => HasStaffNumber (b, a) instance HasStaffNumber a => HasStaffNumber (Couple b a) instance HasStaffNumber a => HasStaffNumber [a] instance HasStaffNumber a => HasStaffNumber (Score a) staffNumber :: HasStaffNumber a => Natural -> a -> a staffNumber = setStaffNumber newtype StaffNumberT a = StaffNumberT {getStaffNumberT :: Couple (First Natural) a} deriving (Eq, Show, Ord, Functor, Foldable, Traversable, Typeable, Applicative, Monad, Comonad) instance Wrapped (StaffNumberT a) where type Unwrapped (StaffNumberT a) = Couple (First Natural) a _Wrapped' = iso getStaffNumberT StaffNumberT instance Rewrapped (StaffNumberT a) (StaffNumberT b) instance HasStaffNumber (StaffNumberT a) where setStaffNumber n = set (_Wrapped . _Wrapped . _1) (First $ Just n) deriving instance Num a => Num (StaffNumberT a) deriving instance Fractional a => Fractional (StaffNumberT a) deriving instance Floating a => Floating (StaffNumberT a) deriving instance Enum a => Enum (StaffNumberT a) deriving instance Bounded a => Bounded (StaffNumberT a) deriving instance (Num a, Ord a, Real a) => Real (StaffNumberT a) deriving instance (Real a, Enum a, Integral a) => Integral (StaffNumberT a) deriving instance IsPitch a => IsPitch (StaffNumberT a) deriving instance IsDynamics a => IsDynamics (StaffNumberT a) deriving instance Semigroup a => Semigroup (StaffNumberT a) deriving instance Tiable a => Tiable (StaffNumberT a) deriving instance HasHarmonic a => HasHarmonic (StaffNumberT a) deriving instance HasSlide a => HasSlide (StaffNumberT a) deriving instance HasText a => HasText (StaffNumberT a) deriving instance Transformable a => Transformable (StaffNumberT a) deriving instance Alterable a => Alterable (StaffNumberT a) deriving instance Augmentable a => Augmentable (StaffNumberT a) type instance GetPitch (StaffNumberT a) = GetPitch a type instance SetPitch g (StaffNumberT a) = StaffNumberT (SetPitch g a) type instance GetDynamic (StaffNumberT a) = GetDynamic a type instance SetDynamic g (StaffNumberT a) = StaffNumberT (SetDynamic g a) type instance GetArticulation (StaffNumberT a) = GetArticulation a type instance SetArticulation g (StaffNumberT a) = StaffNumberT (SetArticulation g a) instance (HasPitches a b) => HasPitches (StaffNumberT a) (StaffNumberT b) where pitches = _Wrapped . pitches instance (HasPitch a b) => HasPitch (StaffNumberT a) (StaffNumberT b) where pitch = _Wrapped . pitch instance (HasDynamics a b) => HasDynamics (StaffNumberT a) (StaffNumberT b) where dynamics = _Wrapped . dynamics instance (HasDynamic a b) => HasDynamic (StaffNumberT a) (StaffNumberT b) where dynamic = _Wrapped . dynamic instance (HasArticulations a b) => HasArticulations (StaffNumberT a) (StaffNumberT b) where articulations = _Wrapped . articulations instance (HasArticulation a b) => HasArticulation (StaffNumberT a) (StaffNumberT b) where articulation = _Wrapped . articulation runStaffNumberT :: StaffNumberT a -> (Natural, a) runStaffNumberT (StaffNumberT (Couple (First n, a))) = (maybe 0 id n, a)
8ff20a9cca573efc6cb05144863259c621a6ebd28f98a3da7ff987c58168fe42
soulomoon/haskell-katas
OddsAndEvens.hs
# LANGUAGE GADTs , DataKinds , TypeFamilies , UndecidableInstances # TypeFamilies, UndecidableInstances #-} module Kyu2.OddsAndEvens where -- | The natural numbers. data Nat = Z | S Nat -- | The axioms of even numbers. data Even (a :: Nat) :: * where -- | Zero is even. ZeroEven :: Even Z -- | If n is even, then n+2 is even. NextEven :: Even n -> Even (S (S n)) -- | The axioms of odd numbers. data Odd (a :: Nat) :: * where -- | One is odd. OneOdd :: Odd (S Z) -- | If n is odd, then n+2 is odd. NextOdd :: Odd n -> Odd (S (S n)) -- | Proves that if n is even, n+1 is odd. -- Notice how I use the axioms here. evenPlusOne :: Even n -> Odd (S n) evenPlusOne ZeroEven = OneOdd evenPlusOne (NextEven n) = NextOdd (evenPlusOne n) -- | Proves that if n is odd, n+1 is even. oddPlusOne :: Odd n -> Even (S n) oddPlusOne OneOdd = NextEven ZeroEven oddPlusOne (NextOdd n) = NextEven (oddPlusOne n) | Adds two natural numbers together . -- Notice how the definition pattern matches. type family Add (n :: Nat) (m :: Nat) :: Nat type instance Add Z m = m type instance Add (S n) m = S (Add n m) -- | Proves even + even = even -- Notice how the pattern matching mirrors `Add`s definition. evenPlusEven :: Even n -> Even m -> Even (Add n m) evenPlusEven ZeroEven m = m evenPlusEven (NextEven n) m = NextEven (evenPlusEven n m) -- | Proves odd + odd = even oddPlusOdd :: Odd n -> Odd m -> Even (Add n m) oddPlusOdd OneOdd m = oddPlusOne m oddPlusOdd (NextOdd n) m = NextEven (oddPlusOdd n m) -- | Proves even + odd = odd evenPlusOdd :: Even n -> Odd m -> Odd (Add n m) evenPlusOdd ZeroEven m = m evenPlusOdd (NextEven n) m = NextOdd (evenPlusOdd n m) -- | Proves odd + even = odd oddPlusEven :: Odd n -> Even m -> Odd (Add n m) oddPlusEven OneOdd m = evenPlusOne m oddPlusEven (NextOdd n) m = NextOdd (oddPlusEven n m) | Multiplies two natural numbers . type family Mult (n :: Nat) (m :: Nat) :: Nat type instance Mult Z m = Z type instance Mult (S n) m = Add m (Mult n m) -- -- | Proves even * even = even evenTimesEven :: Even n -> Even m -> Even (Mult n m) evenTimesEven ZeroEven m = ZeroEven evenTimesEven (NextEven n) m = evenPlusEven m $ evenPlusEven m $ evenTimesEven n m -- -- | Proves odd * odd = odd oddTimesOdd :: Odd n -> Odd m -> Odd (Mult n m) oddTimesOdd OneOdd m = oddPlusEven m ZeroEven oddTimesOdd (NextOdd n) m = oddPlusEven m $ oddPlusOdd m $ oddTimesOdd n m -- -- | Proves even * odd = even evenTimesOdd :: Even n -> Odd m -> Even (Mult n m) evenTimesOdd ZeroEven m = ZeroEven evenTimesOdd (NextEven n) m = oddPlusOdd m $ oddPlusEven m (evenTimesOdd n m) -- -- | Proves odd * even = even oddTimesEven :: Odd n -> Even m -> Even (Mult n m) oddTimesEven OneOdd m = evenPlusEven m ZeroEven oddTimesEven (NextOdd n) m = evenPlusEven m $ evenPlusEven m $ oddTimesEven n m
null
https://raw.githubusercontent.com/soulomoon/haskell-katas/0861338e945e5cbaadf98138cf8f5f24a6ca8bb3/src/Kyu2/OddsAndEvens.hs
haskell
| The natural numbers. | The axioms of even numbers. | Zero is even. | If n is even, then n+2 is even. | The axioms of odd numbers. | One is odd. | If n is odd, then n+2 is odd. | Proves that if n is even, n+1 is odd. Notice how I use the axioms here. | Proves that if n is odd, n+1 is even. Notice how the definition pattern matches. | Proves even + even = even Notice how the pattern matching mirrors `Add`s definition. | Proves odd + odd = even | Proves even + odd = odd | Proves odd + even = odd -- | Proves even * even = even -- | Proves odd * odd = odd -- | Proves even * odd = even -- | Proves odd * even = even
# LANGUAGE GADTs , DataKinds , TypeFamilies , UndecidableInstances # TypeFamilies, UndecidableInstances #-} module Kyu2.OddsAndEvens where data Nat = Z | S Nat data Even (a :: Nat) :: * where ZeroEven :: Even Z NextEven :: Even n -> Even (S (S n)) data Odd (a :: Nat) :: * where OneOdd :: Odd (S Z) NextOdd :: Odd n -> Odd (S (S n)) evenPlusOne :: Even n -> Odd (S n) evenPlusOne ZeroEven = OneOdd evenPlusOne (NextEven n) = NextOdd (evenPlusOne n) oddPlusOne :: Odd n -> Even (S n) oddPlusOne OneOdd = NextEven ZeroEven oddPlusOne (NextOdd n) = NextEven (oddPlusOne n) | Adds two natural numbers together . type family Add (n :: Nat) (m :: Nat) :: Nat type instance Add Z m = m type instance Add (S n) m = S (Add n m) evenPlusEven :: Even n -> Even m -> Even (Add n m) evenPlusEven ZeroEven m = m evenPlusEven (NextEven n) m = NextEven (evenPlusEven n m) oddPlusOdd :: Odd n -> Odd m -> Even (Add n m) oddPlusOdd OneOdd m = oddPlusOne m oddPlusOdd (NextOdd n) m = NextEven (oddPlusOdd n m) evenPlusOdd :: Even n -> Odd m -> Odd (Add n m) evenPlusOdd ZeroEven m = m evenPlusOdd (NextEven n) m = NextOdd (evenPlusOdd n m) oddPlusEven :: Odd n -> Even m -> Odd (Add n m) oddPlusEven OneOdd m = evenPlusOne m oddPlusEven (NextOdd n) m = NextOdd (oddPlusEven n m) | Multiplies two natural numbers . type family Mult (n :: Nat) (m :: Nat) :: Nat type instance Mult Z m = Z type instance Mult (S n) m = Add m (Mult n m) evenTimesEven :: Even n -> Even m -> Even (Mult n m) evenTimesEven ZeroEven m = ZeroEven evenTimesEven (NextEven n) m = evenPlusEven m $ evenPlusEven m $ evenTimesEven n m oddTimesOdd :: Odd n -> Odd m -> Odd (Mult n m) oddTimesOdd OneOdd m = oddPlusEven m ZeroEven oddTimesOdd (NextOdd n) m = oddPlusEven m $ oddPlusOdd m $ oddTimesOdd n m evenTimesOdd :: Even n -> Odd m -> Even (Mult n m) evenTimesOdd ZeroEven m = ZeroEven evenTimesOdd (NextEven n) m = oddPlusOdd m $ oddPlusEven m (evenTimesOdd n m) oddTimesEven :: Odd n -> Even m -> Even (Mult n m) oddTimesEven OneOdd m = evenPlusEven m ZeroEven oddTimesEven (NextOdd n) m = evenPlusEven m $ evenPlusEven m $ oddTimesEven n m
858f65ab6c56d6815ce07e25f7a46512e6ab3917035fe4118099fda717441c00
khmelevskii/duct-pedestal-reitit
routes.clj
(ns duct-pedestal-reitit.services.tasks.routes (:require [integrant.core :as ig] [duct-pedestal-reitit.interceptors.databases :refer [attach-db-interceptor]] [duct-pedestal-reitit.services.tasks.handlers.get :as handlers.get] [clojure.spec.alpha :as s])) ;; example of route validation (s/def ::archived boolean?) (s/def ::query (s/keys :req-un [::archived])) (defmethod ig/init-key :duct-pedestal-reitit.services.tasks/routes [_ {:keys [db]}] ["/tasks" {:get {:handler handlers.get/response :parameters {:query ::query} :interceptors [(attach-db-interceptor db)]}}])
null
https://raw.githubusercontent.com/khmelevskii/duct-pedestal-reitit/f1d27bc81f1ffa91633fc12771e316515b8de0df/src/duct_pedestal_reitit/services/tasks/routes.clj
clojure
example of route validation
(ns duct-pedestal-reitit.services.tasks.routes (:require [integrant.core :as ig] [duct-pedestal-reitit.interceptors.databases :refer [attach-db-interceptor]] [duct-pedestal-reitit.services.tasks.handlers.get :as handlers.get] [clojure.spec.alpha :as s])) (s/def ::archived boolean?) (s/def ::query (s/keys :req-un [::archived])) (defmethod ig/init-key :duct-pedestal-reitit.services.tasks/routes [_ {:keys [db]}] ["/tasks" {:get {:handler handlers.get/response :parameters {:query ::query} :interceptors [(attach-db-interceptor db)]}}])
073fe676f0c8769b5dab1411cf7813a33bb506d41de9060c200857cdddc315f9
wireapp/wire-server
Cassandra.hs
-- This file is part of the Wire Server implementation. -- Copyright ( C ) 2022 Wire Swiss GmbH < > -- -- This program 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. -- -- 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 Affero General Public License for more -- details. -- You should have received a copy of the GNU Affero General Public License along -- with this program. If not, see </>. module Wire.Sem.Paging.Cassandra ( CassandraPaging, LegacyPaging, InternalPaging, InternalPage (..), InternalPagingState (..), mkInternalPage, ipNext, ResultSet, mkResultSet, resultSetResult, resultSetType, ResultSetType (..), ) where import Cassandra import Data.Id import Data.Qualified import Data.Range import Imports import Wire.API.Team.Member (HardTruncationLimit, TeamMember) import qualified Wire.Sem.Paging as E | This paging system uses 's ' PagingState ' to keep track of state , -- and does not rely on ordering. This is the preferred way of paging across -- multiple tables, as in 'MultiTablePaging'. data CassandraPaging type instance E.PagingState CassandraPaging a = PagingState type instance E.Page CassandraPaging a = PageWithState a type instance E.PagingBounds CassandraPaging ConvId = Range 1 1000 Int32 type instance E.PagingBounds CassandraPaging (Remote ConvId) = Range 1 1000 Int32 type instance E.PagingBounds CassandraPaging TeamId = Range 1 100 Int32 -- | This paging system is based on ordering, and keeps track of state using -- the id of the next item to fetch. Implementations of this paging system also -- contain extra logic to detect if the last page has been fetched. data LegacyPaging type instance E.PagingState LegacyPaging a = a type instance E.Page LegacyPaging a = ResultSet a type instance E.PagingBounds LegacyPaging ConvId = Range 1 1000 Int32 type instance E.PagingBounds LegacyPaging TeamId = Range 1 100 Int32 data InternalPaging data InternalPagingState a = forall s. InternalPagingState (Page s, s -> Client a) deriving instance (Functor InternalPagingState) data InternalPage a = forall s. InternalPage (Page s, s -> Client a, [a]) deriving instance (Functor InternalPage) mkInternalPage :: Page s -> (s -> Client a) -> Client (InternalPage a) mkInternalPage p f = do items <- traverse f (result p) pure $ InternalPage (p, f, items) ipNext :: InternalPagingState a -> Client (InternalPage a) ipNext (InternalPagingState (p, f)) = do p' <- nextPage p mkInternalPage p' f type instance E.PagingState InternalPaging a = InternalPagingState a type instance E.Page InternalPaging a = InternalPage a type instance E.PagingBounds InternalPaging TeamMember = Range 1 HardTruncationLimit Int32 type instance E.PagingBounds CassandraPaging TeamMember = Range 1 HardTruncationLimit Int32 type instance E.PagingBounds InternalPaging TeamId = Range 1 100 Int32 instance E.Paging InternalPaging where pageItems (InternalPage (_, _, items)) = items pageHasMore (InternalPage (p, _, _)) = hasMore p pageState (InternalPage (p, f, _)) = InternalPagingState (p, f) -- We use this newtype to highlight the fact that the 'Page' wrapped in here -- can not reliably used for paging. -- The reason for this is that returns ' hasMore ' as true if the -- page size requested is equal to result size. To work around this we actually request for one additional element and drop the last value if -- necessary. This means however that 'nextPage' does not work properly as -- we would miss a value on every page size. Thus , and since we do n't want to expose the ResultSet constructor -- because it gives access to `nextPage`, we give accessors to the results -- and a more typed `hasMore` (ResultSetComplete | ResultSetTruncated) data ResultSet a = ResultSet { resultSetResult :: [a], resultSetType :: ResultSetType } deriving stock (Show, Functor, Foldable, Traversable) -- | A more descriptive type than using a simple bool to represent `hasMore` data ResultSetType = ResultSetComplete | ResultSetTruncated deriving stock (Eq, Show) mkResultSet :: Page a -> ResultSet a mkResultSet page = ResultSet (result page) typ where typ | hasMore page = ResultSetTruncated | otherwise = ResultSetComplete
null
https://raw.githubusercontent.com/wireapp/wire-server/342ed3a72344f6756bbc525dabccdc23a62a7d58/libs/polysemy-wire-zoo/src/Wire/Sem/Paging/Cassandra.hs
haskell
This file is part of the Wire Server implementation. This program is free software: you can redistribute it and/or modify it under 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 Affero General Public License for more details. with this program. If not, see </>. and does not rely on ordering. This is the preferred way of paging across multiple tables, as in 'MultiTablePaging'. | This paging system is based on ordering, and keeps track of state using the id of the next item to fetch. Implementations of this paging system also contain extra logic to detect if the last page has been fetched. We use this newtype to highlight the fact that the 'Page' wrapped in here can not reliably used for paging. page size requested is equal to result size. To work around this we necessary. This means however that 'nextPage' does not work properly as we would miss a value on every page size. because it gives access to `nextPage`, we give accessors to the results and a more typed `hasMore` (ResultSetComplete | ResultSetTruncated) | A more descriptive type than using a simple bool to represent `hasMore`
Copyright ( C ) 2022 Wire Swiss GmbH < > 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 You should have received a copy of the GNU Affero General Public License along module Wire.Sem.Paging.Cassandra ( CassandraPaging, LegacyPaging, InternalPaging, InternalPage (..), InternalPagingState (..), mkInternalPage, ipNext, ResultSet, mkResultSet, resultSetResult, resultSetType, ResultSetType (..), ) where import Cassandra import Data.Id import Data.Qualified import Data.Range import Imports import Wire.API.Team.Member (HardTruncationLimit, TeamMember) import qualified Wire.Sem.Paging as E | This paging system uses 's ' PagingState ' to keep track of state , data CassandraPaging type instance E.PagingState CassandraPaging a = PagingState type instance E.Page CassandraPaging a = PageWithState a type instance E.PagingBounds CassandraPaging ConvId = Range 1 1000 Int32 type instance E.PagingBounds CassandraPaging (Remote ConvId) = Range 1 1000 Int32 type instance E.PagingBounds CassandraPaging TeamId = Range 1 100 Int32 data LegacyPaging type instance E.PagingState LegacyPaging a = a type instance E.Page LegacyPaging a = ResultSet a type instance E.PagingBounds LegacyPaging ConvId = Range 1 1000 Int32 type instance E.PagingBounds LegacyPaging TeamId = Range 1 100 Int32 data InternalPaging data InternalPagingState a = forall s. InternalPagingState (Page s, s -> Client a) deriving instance (Functor InternalPagingState) data InternalPage a = forall s. InternalPage (Page s, s -> Client a, [a]) deriving instance (Functor InternalPage) mkInternalPage :: Page s -> (s -> Client a) -> Client (InternalPage a) mkInternalPage p f = do items <- traverse f (result p) pure $ InternalPage (p, f, items) ipNext :: InternalPagingState a -> Client (InternalPage a) ipNext (InternalPagingState (p, f)) = do p' <- nextPage p mkInternalPage p' f type instance E.PagingState InternalPaging a = InternalPagingState a type instance E.Page InternalPaging a = InternalPage a type instance E.PagingBounds InternalPaging TeamMember = Range 1 HardTruncationLimit Int32 type instance E.PagingBounds CassandraPaging TeamMember = Range 1 HardTruncationLimit Int32 type instance E.PagingBounds InternalPaging TeamId = Range 1 100 Int32 instance E.Paging InternalPaging where pageItems (InternalPage (_, _, items)) = items pageHasMore (InternalPage (p, _, _)) = hasMore p pageState (InternalPage (p, f, _)) = InternalPagingState (p, f) The reason for this is that returns ' hasMore ' as true if the actually request for one additional element and drop the last value if Thus , and since we do n't want to expose the ResultSet constructor data ResultSet a = ResultSet { resultSetResult :: [a], resultSetType :: ResultSetType } deriving stock (Show, Functor, Foldable, Traversable) data ResultSetType = ResultSetComplete | ResultSetTruncated deriving stock (Eq, Show) mkResultSet :: Page a -> ResultSet a mkResultSet page = ResultSet (result page) typ where typ | hasMore page = ResultSetTruncated | otherwise = ResultSetComplete
2e61c3c5e4322f3ff0946b92c5ab8749043cd74a28399bacb0d7b838ba9ca06a
vernemq/vernemq
vmq_webhooks_sup.erl
%%%------------------------------------------------------------------- %% @doc vmq_webhooks top level supervisor. %% @end %%%------------------------------------------------------------------- -module(vmq_webhooks_sup). -behaviour(supervisor). %% API -export([start_link/0]). %% Supervisor callbacks -export([init/1]). -define(SERVER, ?MODULE). %%==================================================================== %% API functions %%==================================================================== -spec start_link() -> 'ignore' | {'error', any()} | {'ok', pid()}. start_link() -> case supervisor:start_link({local, ?SERVER}, ?MODULE, []) of {ok, _} = Ret -> spawn(fun() -> Webhooks = application:get_env(vmq_webhooks, user_webhooks, []), register_webhooks(Webhooks) end), Ret; E -> E end. %%==================================================================== %% Supervisor callbacks %%==================================================================== Child : : { Id , StartFunc , Restart , Shutdown , Type , Modules } init([]) -> SupFlags = #{strategy => one_for_one, intensity => 1, period => 5}, ChildSpecs = [ #{ id => vmq_webhooks_plugin, start => {vmq_webhooks_plugin, start_link, []}, restart => permanent, type => worker, modules => [vmq_webhooks_plugin] } ], {ok, {SupFlags, ChildSpecs}}. %%==================================================================== Internal functions %%==================================================================== -spec register_webhooks([{_, map()}]) -> [any()]. register_webhooks(Webhooks) -> [register_webhook(Webhook) || Webhook <- Webhooks]. -spec register_webhook({_, #{'endpoint' := binary(), 'hook' := atom(), 'options' := _, _ => _}}) -> any(). register_webhook({Name, #{hook := HookName, endpoint := Endpoint, options := Opts}}) -> case vmq_webhooks_plugin:register_endpoint(Endpoint, HookName, Opts) of ok -> ok; {error, Reason} -> lager:error( "failed to register the ~p webhook ~p ~p ~p due to ~p", [Name, Endpoint, HookName, Opts, Reason] ) end.
null
https://raw.githubusercontent.com/vernemq/vernemq/234d253250cb5371b97ebb588622076fdabc6a5f/apps/vmq_webhooks/src/vmq_webhooks_sup.erl
erlang
------------------------------------------------------------------- @doc vmq_webhooks top level supervisor. @end ------------------------------------------------------------------- API Supervisor callbacks ==================================================================== API functions ==================================================================== ==================================================================== Supervisor callbacks ==================================================================== ==================================================================== ====================================================================
-module(vmq_webhooks_sup). -behaviour(supervisor). -export([start_link/0]). -export([init/1]). -define(SERVER, ?MODULE). -spec start_link() -> 'ignore' | {'error', any()} | {'ok', pid()}. start_link() -> case supervisor:start_link({local, ?SERVER}, ?MODULE, []) of {ok, _} = Ret -> spawn(fun() -> Webhooks = application:get_env(vmq_webhooks, user_webhooks, []), register_webhooks(Webhooks) end), Ret; E -> E end. Child : : { Id , StartFunc , Restart , Shutdown , Type , Modules } init([]) -> SupFlags = #{strategy => one_for_one, intensity => 1, period => 5}, ChildSpecs = [ #{ id => vmq_webhooks_plugin, start => {vmq_webhooks_plugin, start_link, []}, restart => permanent, type => worker, modules => [vmq_webhooks_plugin] } ], {ok, {SupFlags, ChildSpecs}}. Internal functions -spec register_webhooks([{_, map()}]) -> [any()]. register_webhooks(Webhooks) -> [register_webhook(Webhook) || Webhook <- Webhooks]. -spec register_webhook({_, #{'endpoint' := binary(), 'hook' := atom(), 'options' := _, _ => _}}) -> any(). register_webhook({Name, #{hook := HookName, endpoint := Endpoint, options := Opts}}) -> case vmq_webhooks_plugin:register_endpoint(Endpoint, HookName, Opts) of ok -> ok; {error, Reason} -> lager:error( "failed to register the ~p webhook ~p ~p ~p due to ~p", [Name, Endpoint, HookName, Opts, Reason] ) end.
f5fe0bd8f208566df0afdc06306d50981133e49e3f8dd720ed46cc508abfea35
cdornan/fmt
Main.hs
{-# LANGUAGE OverloadedStrings #-} # LANGUAGE QuasiQuotes # # LANGUAGE DeriveGeneric # # LANGUAGE FlexibleContexts # # LANGUAGE CPP # module Main where -- Monoid #if __GLASGOW_HASKELL__ < 804 import Data.Monoid ((<>)) #endif -- Text import Data.Text (Text) import qualified Data.Text as T import qualified Data.Text.Lazy as TL import NeatInterpolation -- Various data structures import qualified Data.Vector as V import Data.Vector (Vector) import qualified Data.Map as M import Data.Map (Map) import qualified Data.ByteString as BS import qualified Data.ByteString.Lazy as BSL import qualified Data.ByteString.Builder as BB -- Generics import GHC.Generics -- Call stacks import Data.CallStack -- Tests import Test.Hspec -- Fmt import Fmt ---------------------------------------------------------------------------- -- Constants for testing (to avoid “ambiguous type” errors) ---------------------------------------------------------------------------- n :: Integer n = 25 s :: String s = "!" ---------------------------------------------------------------------------- -- List of tests ---------------------------------------------------------------------------- main :: IO () main = hspec $ do test_operators test_outputTypes describe "formatters" $ do test_indent test_baseConversion test_floatingPoint test_hex test_ADTs test_conditionals test_padding test_lists test_maps test_tuples test_generic ---------------------------------------------------------------------------- -- Testing that operators work (when used as intended) ---------------------------------------------------------------------------- test_operators :: Spec test_operators = do it "simple examples" $ do ("a"+|n|+"b") ==%> "a25b" ("a"+|n|+"b"+|s|+"") ==%> "a25b!" (""+|n|++|s|+"") ==%> "25!" (""+|negate n|++|s|+"") ==%> "-25!" (""+|Just n|++|s|+"") ==%> "25!" describe "examples with Show/mixed" $ do it "copy of Buildable examples" $ do ("a"+||n||+"b") ==%> "a25b" ("a"+||n||++||n||+"b") ==%> "a2525b" -- These are mixed, i.e. both Buildable and Show versions are used ("a"+||n||+"b"+|s|+"") ==%> "a25b!" (""+||n||++|s|+"") ==%> "25!" (""+||negate n||++|s|+"") ==%> "-25!" it "examples that don't work with Buildable" $ do (""+||Just n||+"") ==%> "Just 25" (""+||(n,n)||+"") ==%> "(25,25)" it "plays nice with other operators" $ do -- If precedence is bad these won't compile (""+|n-1|++|n+1|+"") ==%> "2426" (id $ ""+|n-1|++|n+1|+"") ==%> "2426" it "works with <>" $ do ("number: "+|n|+"\n"<> "string: "+|s|+"") ==%> "number: 25\nstring: !" ---------------------------------------------------------------------------- -- Testing that different output types work ---------------------------------------------------------------------------- test_outputTypes :: Spec test_outputTypes = describe "output as" $ do it "String" $ ("a"+|n|+"b" :: String) `shouldBe` "a25b" it "Text" $ ("a"+|n|+"b" :: Text) `shouldBe` "a25b" it "Lazy Text" $ ("a"+|n|+"b" :: TL.Text) `shouldBe` "a25b" it "ByteString" $ ("a"+|n|+"b" :: BS.ByteString) `shouldBe` "a25b" it "Lazy ByteString" $ ("a"+|n|+"b" :: BSL.ByteString) `shouldBe` "a25b" it "Text Builder" $ ("a"+|n|+"b" :: Builder) `shouldBe` "a25b" it "ByteString Builder" $ BB.toLazyByteString ("a"+|n|+"b" :: BB.Builder) `shouldBe` "a25b" ---------------------------------------------------------------------------- -- Tests for various simple formatters ---------------------------------------------------------------------------- test_indent :: Spec test_indent = describe "'indentF'" $ do it "simple examples" $ do indentF 0 "hi" ==#> "hi\n" indentF 0 "\nhi\n\n" ==#> "\nhi\n\n" indentF 2 "hi" ==#> " hi\n" indentF 2 "hi\n" ==#> " hi\n" indentF 2 "" ==#> " \n" indentF 2 "hi\nbye" ==#> " hi\n bye\n" indentF 2 "hi\nbye\n" ==#> " hi\n bye\n" it "formatting a block" $ do ("Some numbers:\n"<> indentF 2 ( "odd: "+|n|+"\n"<> "even: "+|n+1|+"")) ==#> "Some numbers:\n odd: 25\n even: 26\n" test_baseConversion :: Spec test_baseConversion = describe "conversion to bases" $ do it "octF" $ do octF n ==#> "31" it "binF" $ do binF n ==#> "11001" it "baseF" $ do baseF 36 (n^n) ==#> "54kbbzw21jhueg5jb0ggr4p" it "-baseF" $ do baseF 36 (-(n^n)) ==#> "-54kbbzw21jhueg5jb0ggr4p" test_floatingPoint :: Spec test_floatingPoint = describe "floating-point" $ do let f1_3 = 1.2999999999999998 :: Double it "floatF" $ do floatF f1_3 ==#> "1.2999999999999998" it "exptF" $ do exptF 2 f1_3 ==#> "1.30e0" it "fixedF" $ do fixedF 2 f1_3 ==#> "1.30" test_hex :: Spec test_hex = describe "'hexF'" $ do it "Int" $ do hexF n ==#> "19" it "-Int" $ do hexF (-n) ==#> "-19" it "strict ByteString" $ do hexF (BS.pack [15,250]) ==#> "0ffa" it "lazy ByteString" $ do hexF (BSL.pack [15,250]) ==#> "0ffa" test_ADTs :: Spec test_ADTs = describe "ADTs" $ do it "maybeF" $ do maybeF (Nothing :: Maybe Int) ==#> "<Nothing>" maybeF (Just 3 :: Maybe Int) ==#> "3" it "eitherF" $ do eitherF (Left 1 :: Either Int Int) ==#> "<Left: 1>" eitherF (Right 1 :: Either Int Int) ==#> "<Right: 1>" test_conditionals :: Spec test_conditionals = describe "conditionals" $ do it "whenF" $ do whenF True "hi" ==#> "hi" whenF False "hi" ==#> "" it "unlessF" $ do unlessF True "hi" ==#> "" unlessF False "hi" ==#> "hi" ---------------------------------------------------------------------------- -- Tests for padding ---------------------------------------------------------------------------- test_padding :: Spec test_padding = describe "padding" $ do it "prefixF" $ do prefixF (-1) ("hello" :: Text) ==#> "" prefixF 0 ("hello" :: Text) ==#> "" prefixF 1 ("hello" :: Text) ==#> "h" prefixF 2 ("hello" :: Text) ==#> "he" prefixF 3 ("hello" :: Text) ==#> "hel" prefixF 5 ("hello" :: Text) ==#> "hello" prefixF 1000 ("hello" :: Text) ==#> "hello" prefixF 1000 ("" :: Text) ==#> "" it "suffixF" $ do suffixF (-1) ("hello" :: Text) ==#> "" suffixF 0 ("hello" :: Text) ==#> "" suffixF 1 ("hello" :: Text) ==#> "o" suffixF 2 ("hello" :: Text) ==#> "lo" suffixF 3 ("hello" :: Text) ==#> "llo" suffixF 5 ("hello" :: Text) ==#> "hello" suffixF 1000 ("hello" :: Text) ==#> "hello" suffixF 1000 ("" :: Text) ==#> "" it "padLeftF" $ do padLeftF (-1) '!' ("hello" :: Text) ==#> "hello" padLeftF 0 '!' ("hello" :: Text) ==#> "hello" padLeftF 1 '!' ("hello" :: Text) ==#> "hello" padLeftF 5 '!' ("hello" :: Text) ==#> "hello" padLeftF 6 '!' ("hello" :: Text) ==#> "!hello" padLeftF 7 '!' ("hello" :: Text) ==#> "!!hello" padLeftF 7 '!' ("" :: Text) ==#> "!!!!!!!" it "padRightF" $ do padRightF (-1) '!' ("hello" :: Text) ==#> "hello" padRightF 0 '!' ("hello" :: Text) ==#> "hello" padRightF 1 '!' ("hello" :: Text) ==#> "hello" padRightF 5 '!' ("hello" :: Text) ==#> "hello" padRightF 6 '!' ("hello" :: Text) ==#> "hello!" padRightF 7 '!' ("hello" :: Text) ==#> "hello!!" padRightF 7 '!' ("" :: Text) ==#> "!!!!!!!" it "padBothF" $ do padBothF (-1) '!' ("hello" :: Text) ==#> "hello" padBothF 0 '!' ("hello" :: Text) ==#> "hello" padBothF 1 '!' ("hello" :: Text) ==#> "hello" padBothF 5 '!' ("hello" :: Text) ==#> "hello" padBothF 6 '!' ("hello" :: Text) ==#> "!hello" padBothF 7 '!' ("hello" :: Text) ==#> "!hello!" padBothF 7 '!' ("hell" :: Text) ==#> "!!hell!" padBothF 7 '!' ("hel" :: Text) ==#> "!!hel!!" padBothF 8 '!' ("hell" :: Text) ==#> "!!hell!!" padBothF 8 '!' ("hel" :: Text) ==#> "!!!hel!!" padBothF 8 '!' ("" :: Text) ==#> "!!!!!!!!" ---------------------------------------------------------------------------- -- Tests for lists ---------------------------------------------------------------------------- test_lists :: Spec test_lists = describe "lists" $ do test_listF test_blockListF test_jsonListF test_listF :: Spec test_listF = describe "'listF'" $ do it "simple examples" $ do listF ([] :: [Int]) ==#> "[]" listF [n] ==#> "[25]" listF [n,n+1] ==#> "[25, 26]" listF [s,s<>s,"",s<>s<>s] ==#> "[!, !!, , !!!]" it "different Foldables" $ do listF ([1,2,3] :: [Int]) ==#> "[1, 2, 3]" listF (V.fromList [1,2,3] :: Vector Int) ==#> "[1, 2, 3]" listF (M.fromList [(1,2),(3,4),(5,6)] :: Map Int Int) ==#> "[2, 4, 6]" test_blockListF :: Spec test_blockListF = describe "'blockListF'" $ do emptyList nullElements singleLineElements multiLineElements mixed where emptyList = it "empty list" $ do blockListF ([] :: [Int]) ==#> "[]\n" nullElements = it "null elements" $ do blockListF ([""] :: [Text]) ==$> [text| - |] blockListF (["",""] :: [Text]) ==$> [text| - - |] blockListF (["","a",""] :: [Text]) ==$> [text| - - a - |] singleLineElements = it "single-line elements" $ do blockListF (["a"] :: [Text]) ==$> [text| - a |] blockListF (["a","b"] :: [Text]) ==$> [text| -_a -_b |] blockListF (["a","b","ccc"] :: [Text]) ==$> [text| - a - b - ccc |] multiLineElements = it "multi-line elements" $ do blockListF (["a\nx"] :: [Text]) ==$> [text| - a x |] blockListF (["a\n x"] :: [Text]) ==$> [text| - a x |] blockListF (["a\n x"," b\nxx\ny y ","c\n\n"] :: [Text]) ==$> [text| - a x - b xx y y_ - c __ |] mixed = it "mix of single-line and multi-line" $ do blockListF (["a\nx","b"] :: [Text]) ==$> [text| - a x - b |] blockListF (["a\nx","b\n"] :: [Text]) ==$> [text| - a x - b |] blockListF (["a"," b\nxx\ny y ","c\n\n"] :: [Text]) ==$> [text| - a - b xx y y_ - c __ |] test_jsonListF :: Spec test_jsonListF = describe "'jsonListF'" $ do emptyList nullElements singleLineElements multiLineElements mixed where emptyList = it "empty list" $ do jsonListF ([] :: [Int]) ==#> "[]\n" nullElements = it "null elements" $ do jsonListF ([""] :: [Text]) ==$> [text| [ ] |] jsonListF (["",""] :: [Text]) ==$> [text| [ , ] |] jsonListF (["","a",""] :: [Text]) ==$> [text| [ , a , ] |] singleLineElements = it "single-line elements" $ do jsonListF (["a"] :: [Text]) ==$> [text| [ a ] |] jsonListF (["a","b"] :: [Text]) ==$> [text| [ a , b ] |] jsonListF (["a","b","ccc"] :: [Text]) ==$> [text| [ a , b , ccc ] |] multiLineElements = it "multi-line elements" $ do jsonListF (["a\nx"] :: [Text]) ==$> [text| [ a x ] |] jsonListF (["a\n x"] :: [Text]) ==$> [text| [ a x ] |] jsonListF (["a\n x"," b\nxx\ny y ","c\n\n"] :: [Text]) ==$> [text| [ a x , b xx y y_ , c __ ] |] mixed = it "mix of single-line and multi-line" $ do jsonListF (["a\nx","b"] :: [Text]) ==$> [text| [ a x , b ] |] jsonListF (["a\nx","b\n"] :: [Text]) ==$> [text| [ a x , b ] |] jsonListF (["a"," b\nxx\ny y ","c\n\n"] :: [Text]) ==$> [text| [ a , b xx y y_ , c __ ] |] ---------------------------------------------------------------------------- -- Tests for maps ---------------------------------------------------------------------------- test_maps :: Spec test_maps = describe "maps" $ do test_mapF test_blockMapF test_jsonMapF test_mapF :: Spec test_mapF = describe "'mapF'" $ do it "simple examples" $ do mapF ([] :: [(Int, Int)]) ==#> "{}" mapF [(n,n+1)] ==#> "{25: 26}" mapF [(s,n)] ==#> "{!: 25}" mapF [('a',True),('b',False),('c',True)] ==#> "{a: True, b: False, c: True}" it "different map types" $ do let m = [('a',True),('b',False),('d',False),('c',True)] mapF m ==#> "{a: True, b: False, d: False, c: True}" mapF (M.fromList m) ==#> "{a: True, b: False, c: True, d: False}" test_blockMapF :: Spec test_blockMapF = describe "'blockMapF'" $ do it "empty map" $ do blockMapF ([] :: [(Int, Int)]) ==#> "{}\n" it "complex example" $ do blockMapF ([("hi", ""), ("foo"," a\n b"), ("bar","a"), ("baz","a\ng")] :: [(Text, Text)]) ==$> [text| hi: foo: a b bar: a baz: a g |] test_jsonMapF :: Spec test_jsonMapF = describe "'jsonMapF'" $ do it "empty map" $ do jsonMapF ([] :: [(Int, Int)]) ==#> "{}\n" it "complex example" $ do jsonMapF ([("hi", ""), ("foo"," a\n b"), ("bar","a"), ("baz","a\ng")] :: [(Text, Text)]) ==$> [text| { hi: , foo: a b , bar: a , baz: a g } |] ---------------------------------------------------------------------------- -- Tests for tuples ---------------------------------------------------------------------------- test_tuples :: Spec test_tuples = describe "tuples" $ do test_tupleSimple describe "tupleF on lists" $ do test_tupleOneLine test_tupleMultiline test_tupleSimple :: Spec test_tupleSimple = it "tupleF" $ do -- we don't need complicated tests here, they're all tested in -- "tupleF on lists" tests tupleF (n, s) ==#> "(25, !)" tupleF (n, s, n, s) ==#> "(25, !, 25, !)" tupleF (n, s, n, s, 'a', 'b', 'c', 'd') ==#> "(25, !, 25, !, a, b, c, d)" test_tupleOneLine :: Spec test_tupleOneLine = describe "one-line" $ do it "()" $ do tupleF ([] :: [Builder]) ==#> "()" it "('')" $ do tupleF ([""] :: [Builder]) ==#> "()" it "(a)" $ do tupleF (["a"] :: [Builder]) ==#> "(a)" it "(a,b)" $ do tupleF (["a", "b"] :: [Builder]) ==#> "(a, b)" it "(a,'')" $ do tupleF (["a", ""] :: [Builder]) ==#> "(a, )" it "('',b)" $ do tupleF (["", "b"] :: [Builder]) ==#> "(, b)" it "('','')" $ do tupleF (["", ""] :: [Builder]) ==#> "(, )" it "(a,b,c)" $ do tupleF (["a", "ba", "caba"] :: [Builder]) ==#> "(a, ba, caba)" test_tupleMultiline :: Spec test_tupleMultiline = describe "multiline" $ do allNonEmpty someEmpty it "weird case" $ do -- not sure whether I should fix it or not tupleF ["a\n" :: Builder] ==#> "(a\n)" where allNonEmpty = describe "all non-empty" $ do it "1 element (2 lines)" $ do tupleF ["a\nx" :: Builder] ==$> [text| ( a x ) |] tupleF ["a\n x" :: Builder] ==$> [text| ( a x ) |] tupleF [" a\nx\n" :: Builder] ==$> [text| ( a x ) |] it "1 element (3 lines)" $ do tupleF ["a\nb\nc" :: Builder] ==$> [text| ( a b c ) |] it "2 elements (1 line + 2 lines)" $ do tupleF ["a", "b\nc" :: Builder] ==$> [text| ( a , b c ) |] it "2 elements (2 lines + 1 line)" $ do tupleF ["a\nb", "c" :: Builder] ==$> [text| ( a b , c ) |] it "3 elements (each has 2 lines)" $ do tupleF ["a\nb", "c\nd", "e\nf" :: Builder] ==$> [text| ( a b , c d , e f ) |] someEmpty = describe "some empty" $ do it "2 elements (0 + 2)" $ do tupleF ["", "a\nb" :: Builder] ==$> [text| ( , a b ) |] it "2 elements (2 + 0)" $ do tupleF ["a\nb", "" :: Builder] ==$> [text| ( a b , ) |] it "3 elements (0 + 2 + 0)" $ do tupleF ["", "a\nb", "" :: Builder] ==$> [text| ( , a b , ) |] it "3 elements (2 + 0 + 2)" $ do tupleF ["a\nb", "", "c\nd" :: Builder] ==$> [text| ( a b , , c d ) |] it "4 elements (2 + 0 + 0 + 2)" $ do tupleF ["a\nb", "", "", "c\nd" :: Builder] ==$> [text| ( a b , , , c d ) |] ---------------------------------------------------------------------------- -- Tests for 'genericF' ---------------------------------------------------------------------------- data Foo a = Foo a deriving Generic data Bar a = Bar a a deriving Generic data Qux a = Qux {q1 :: Int, q2 :: a, q3 :: Text} deriving Generic data Op = (:|:) Int | (:||:) Int Int | (:|||:) Int Int Int | Int :-: Int | Int `O` Int deriving Generic test_generic :: Spec test_generic = describe "'genericF'" $ do it "Maybe" $ do genericF (Nothing :: Maybe Int) ==#> "Nothing" genericF (Just 25 :: Maybe Int) ==#> "<Just: 25>" it "Either" $ do genericF (Left 25 :: Either Int Bool) ==#> "<Left: 25>" genericF (Right True :: Either Int Bool) ==#> "<Right: True>" it "tuples" $ do genericF (n, s) ==#> "(25, !)" genericF (n, s, -n, s ++ s) ==#> "(25, !, -25, !!)" describe "custom types" $ do it "ordinary constructors" $ do genericF (Foo n) ==#> "<Foo: 25>" genericF (Bar (n-1) (n+1)) ==#> "<Bar: 24, 26>" it "records" $ do genericF (Qux 1 True "hi") ==$> [text| Qux: q1: 1 q2: True q3: hi |] it "operators and infix constructors" $ do genericF ((:|:) 1) ==#> "<(:|:): 1>" genericF ((:||:) 1 2) ==#> "<(:||:): 1, 2>" genericF ((:|||:) 1 2 3) ==#> "<(:|||:): 1, 2, 3>" genericF ((:-:) 1 2) ==#> "(1 :-: 2)" genericF (O 1 2) ==#> "(1 `O` 2)" describe "types with non-Buildables inside" $ do it "functions" $ do genericF (Foo not) ==#> "<Foo: <function>>" it "lists" $ do genericF (Foo [n, n+1]) ==#> "<Foo: [25, 26]>" it "maps" $ do genericF (Foo (M.singleton n s)) ==#> "<Foo: {25: !}>" it "tuples" $ do genericF (Foo (n, s)) ==#> "<Foo: (25, !)>" genericF (Foo (n, s, n+1)) ==#> "<Foo: (25, !, 26)>" it "tuple with a string inside" $ do -- strings have to be handled differently from lists -- so we test this case separately genericF (Foo (n, s)) ==#> "<Foo: (25, !)>" it "Either" $ do genericF (Foo (Left 25 :: Either Int Int)) ==#> "<Foo: <Left: 25>>" it "Maybe with a non-buildable" $ do genericF (Foo (Just [n])) ==#> "<Foo: [25]>" genericF (Foo (Nothing :: Maybe ())) ==#> "<Foo: <Nothing>>" ---------------------------------------------------------------------------- Utilities ---------------------------------------------------------------------------- (==%>) :: HasCallStack => Text -> Text -> Expectation (==%>) = shouldBe the RHS has @neat - interpolation@ string for which later versions ( > = 0.4 ) are discarding the final -- newline; we must detect when it is doing so and restore the newline (==$>) :: HasCallStack => Builder -> Text -> Expectation (==$>) a b0 = a ==#> b where b = case T.last b0 == '\n' of True -> b0 False -> b0 <> "\n" (==#>) :: HasCallStack => Builder -> Text -> Expectation (==#>) a b = a `shouldBe` build (T.replace "_" " " b)
null
https://raw.githubusercontent.com/cdornan/fmt/272c5b2d1c420ea1164067db47dfab952dbec854/tests/Main.hs
haskell
# LANGUAGE OverloadedStrings # Monoid Text Various data structures Generics Call stacks Tests Fmt -------------------------------------------------------------------------- Constants for testing (to avoid “ambiguous type” errors) -------------------------------------------------------------------------- -------------------------------------------------------------------------- List of tests -------------------------------------------------------------------------- -------------------------------------------------------------------------- Testing that operators work (when used as intended) -------------------------------------------------------------------------- These are mixed, i.e. both Buildable and Show versions are used If precedence is bad these won't compile -------------------------------------------------------------------------- Testing that different output types work -------------------------------------------------------------------------- -------------------------------------------------------------------------- Tests for various simple formatters -------------------------------------------------------------------------- -------------------------------------------------------------------------- Tests for padding -------------------------------------------------------------------------- -------------------------------------------------------------------------- Tests for lists -------------------------------------------------------------------------- -------------------------------------------------------------------------- Tests for maps -------------------------------------------------------------------------- -------------------------------------------------------------------------- Tests for tuples -------------------------------------------------------------------------- we don't need complicated tests here, they're all tested in "tupleF on lists" tests not sure whether I should fix it or not -------------------------------------------------------------------------- Tests for 'genericF' -------------------------------------------------------------------------- strings have to be handled differently from lists so we test this case separately -------------------------------------------------------------------------- -------------------------------------------------------------------------- newline; we must detect when it is doing so and restore the newline
# LANGUAGE QuasiQuotes # # LANGUAGE DeriveGeneric # # LANGUAGE FlexibleContexts # # LANGUAGE CPP # module Main where #if __GLASGOW_HASKELL__ < 804 import Data.Monoid ((<>)) #endif import Data.Text (Text) import qualified Data.Text as T import qualified Data.Text.Lazy as TL import NeatInterpolation import qualified Data.Vector as V import Data.Vector (Vector) import qualified Data.Map as M import Data.Map (Map) import qualified Data.ByteString as BS import qualified Data.ByteString.Lazy as BSL import qualified Data.ByteString.Builder as BB import GHC.Generics import Data.CallStack import Test.Hspec import Fmt n :: Integer n = 25 s :: String s = "!" main :: IO () main = hspec $ do test_operators test_outputTypes describe "formatters" $ do test_indent test_baseConversion test_floatingPoint test_hex test_ADTs test_conditionals test_padding test_lists test_maps test_tuples test_generic test_operators :: Spec test_operators = do it "simple examples" $ do ("a"+|n|+"b") ==%> "a25b" ("a"+|n|+"b"+|s|+"") ==%> "a25b!" (""+|n|++|s|+"") ==%> "25!" (""+|negate n|++|s|+"") ==%> "-25!" (""+|Just n|++|s|+"") ==%> "25!" describe "examples with Show/mixed" $ do it "copy of Buildable examples" $ do ("a"+||n||+"b") ==%> "a25b" ("a"+||n||++||n||+"b") ==%> "a2525b" ("a"+||n||+"b"+|s|+"") ==%> "a25b!" (""+||n||++|s|+"") ==%> "25!" (""+||negate n||++|s|+"") ==%> "-25!" it "examples that don't work with Buildable" $ do (""+||Just n||+"") ==%> "Just 25" (""+||(n,n)||+"") ==%> "(25,25)" it "plays nice with other operators" $ do (""+|n-1|++|n+1|+"") ==%> "2426" (id $ ""+|n-1|++|n+1|+"") ==%> "2426" it "works with <>" $ do ("number: "+|n|+"\n"<> "string: "+|s|+"") ==%> "number: 25\nstring: !" test_outputTypes :: Spec test_outputTypes = describe "output as" $ do it "String" $ ("a"+|n|+"b" :: String) `shouldBe` "a25b" it "Text" $ ("a"+|n|+"b" :: Text) `shouldBe` "a25b" it "Lazy Text" $ ("a"+|n|+"b" :: TL.Text) `shouldBe` "a25b" it "ByteString" $ ("a"+|n|+"b" :: BS.ByteString) `shouldBe` "a25b" it "Lazy ByteString" $ ("a"+|n|+"b" :: BSL.ByteString) `shouldBe` "a25b" it "Text Builder" $ ("a"+|n|+"b" :: Builder) `shouldBe` "a25b" it "ByteString Builder" $ BB.toLazyByteString ("a"+|n|+"b" :: BB.Builder) `shouldBe` "a25b" test_indent :: Spec test_indent = describe "'indentF'" $ do it "simple examples" $ do indentF 0 "hi" ==#> "hi\n" indentF 0 "\nhi\n\n" ==#> "\nhi\n\n" indentF 2 "hi" ==#> " hi\n" indentF 2 "hi\n" ==#> " hi\n" indentF 2 "" ==#> " \n" indentF 2 "hi\nbye" ==#> " hi\n bye\n" indentF 2 "hi\nbye\n" ==#> " hi\n bye\n" it "formatting a block" $ do ("Some numbers:\n"<> indentF 2 ( "odd: "+|n|+"\n"<> "even: "+|n+1|+"")) ==#> "Some numbers:\n odd: 25\n even: 26\n" test_baseConversion :: Spec test_baseConversion = describe "conversion to bases" $ do it "octF" $ do octF n ==#> "31" it "binF" $ do binF n ==#> "11001" it "baseF" $ do baseF 36 (n^n) ==#> "54kbbzw21jhueg5jb0ggr4p" it "-baseF" $ do baseF 36 (-(n^n)) ==#> "-54kbbzw21jhueg5jb0ggr4p" test_floatingPoint :: Spec test_floatingPoint = describe "floating-point" $ do let f1_3 = 1.2999999999999998 :: Double it "floatF" $ do floatF f1_3 ==#> "1.2999999999999998" it "exptF" $ do exptF 2 f1_3 ==#> "1.30e0" it "fixedF" $ do fixedF 2 f1_3 ==#> "1.30" test_hex :: Spec test_hex = describe "'hexF'" $ do it "Int" $ do hexF n ==#> "19" it "-Int" $ do hexF (-n) ==#> "-19" it "strict ByteString" $ do hexF (BS.pack [15,250]) ==#> "0ffa" it "lazy ByteString" $ do hexF (BSL.pack [15,250]) ==#> "0ffa" test_ADTs :: Spec test_ADTs = describe "ADTs" $ do it "maybeF" $ do maybeF (Nothing :: Maybe Int) ==#> "<Nothing>" maybeF (Just 3 :: Maybe Int) ==#> "3" it "eitherF" $ do eitherF (Left 1 :: Either Int Int) ==#> "<Left: 1>" eitherF (Right 1 :: Either Int Int) ==#> "<Right: 1>" test_conditionals :: Spec test_conditionals = describe "conditionals" $ do it "whenF" $ do whenF True "hi" ==#> "hi" whenF False "hi" ==#> "" it "unlessF" $ do unlessF True "hi" ==#> "" unlessF False "hi" ==#> "hi" test_padding :: Spec test_padding = describe "padding" $ do it "prefixF" $ do prefixF (-1) ("hello" :: Text) ==#> "" prefixF 0 ("hello" :: Text) ==#> "" prefixF 1 ("hello" :: Text) ==#> "h" prefixF 2 ("hello" :: Text) ==#> "he" prefixF 3 ("hello" :: Text) ==#> "hel" prefixF 5 ("hello" :: Text) ==#> "hello" prefixF 1000 ("hello" :: Text) ==#> "hello" prefixF 1000 ("" :: Text) ==#> "" it "suffixF" $ do suffixF (-1) ("hello" :: Text) ==#> "" suffixF 0 ("hello" :: Text) ==#> "" suffixF 1 ("hello" :: Text) ==#> "o" suffixF 2 ("hello" :: Text) ==#> "lo" suffixF 3 ("hello" :: Text) ==#> "llo" suffixF 5 ("hello" :: Text) ==#> "hello" suffixF 1000 ("hello" :: Text) ==#> "hello" suffixF 1000 ("" :: Text) ==#> "" it "padLeftF" $ do padLeftF (-1) '!' ("hello" :: Text) ==#> "hello" padLeftF 0 '!' ("hello" :: Text) ==#> "hello" padLeftF 1 '!' ("hello" :: Text) ==#> "hello" padLeftF 5 '!' ("hello" :: Text) ==#> "hello" padLeftF 6 '!' ("hello" :: Text) ==#> "!hello" padLeftF 7 '!' ("hello" :: Text) ==#> "!!hello" padLeftF 7 '!' ("" :: Text) ==#> "!!!!!!!" it "padRightF" $ do padRightF (-1) '!' ("hello" :: Text) ==#> "hello" padRightF 0 '!' ("hello" :: Text) ==#> "hello" padRightF 1 '!' ("hello" :: Text) ==#> "hello" padRightF 5 '!' ("hello" :: Text) ==#> "hello" padRightF 6 '!' ("hello" :: Text) ==#> "hello!" padRightF 7 '!' ("hello" :: Text) ==#> "hello!!" padRightF 7 '!' ("" :: Text) ==#> "!!!!!!!" it "padBothF" $ do padBothF (-1) '!' ("hello" :: Text) ==#> "hello" padBothF 0 '!' ("hello" :: Text) ==#> "hello" padBothF 1 '!' ("hello" :: Text) ==#> "hello" padBothF 5 '!' ("hello" :: Text) ==#> "hello" padBothF 6 '!' ("hello" :: Text) ==#> "!hello" padBothF 7 '!' ("hello" :: Text) ==#> "!hello!" padBothF 7 '!' ("hell" :: Text) ==#> "!!hell!" padBothF 7 '!' ("hel" :: Text) ==#> "!!hel!!" padBothF 8 '!' ("hell" :: Text) ==#> "!!hell!!" padBothF 8 '!' ("hel" :: Text) ==#> "!!!hel!!" padBothF 8 '!' ("" :: Text) ==#> "!!!!!!!!" test_lists :: Spec test_lists = describe "lists" $ do test_listF test_blockListF test_jsonListF test_listF :: Spec test_listF = describe "'listF'" $ do it "simple examples" $ do listF ([] :: [Int]) ==#> "[]" listF [n] ==#> "[25]" listF [n,n+1] ==#> "[25, 26]" listF [s,s<>s,"",s<>s<>s] ==#> "[!, !!, , !!!]" it "different Foldables" $ do listF ([1,2,3] :: [Int]) ==#> "[1, 2, 3]" listF (V.fromList [1,2,3] :: Vector Int) ==#> "[1, 2, 3]" listF (M.fromList [(1,2),(3,4),(5,6)] :: Map Int Int) ==#> "[2, 4, 6]" test_blockListF :: Spec test_blockListF = describe "'blockListF'" $ do emptyList nullElements singleLineElements multiLineElements mixed where emptyList = it "empty list" $ do blockListF ([] :: [Int]) ==#> "[]\n" nullElements = it "null elements" $ do blockListF ([""] :: [Text]) ==$> [text| - |] blockListF (["",""] :: [Text]) ==$> [text| - - |] blockListF (["","a",""] :: [Text]) ==$> [text| - - a - |] singleLineElements = it "single-line elements" $ do blockListF (["a"] :: [Text]) ==$> [text| - a |] blockListF (["a","b"] :: [Text]) ==$> [text| -_a -_b |] blockListF (["a","b","ccc"] :: [Text]) ==$> [text| - a - b - ccc |] multiLineElements = it "multi-line elements" $ do blockListF (["a\nx"] :: [Text]) ==$> [text| - a x |] blockListF (["a\n x"] :: [Text]) ==$> [text| - a x |] blockListF (["a\n x"," b\nxx\ny y ","c\n\n"] :: [Text]) ==$> [text| - a x - b xx y y_ - c __ |] mixed = it "mix of single-line and multi-line" $ do blockListF (["a\nx","b"] :: [Text]) ==$> [text| - a x - b |] blockListF (["a\nx","b\n"] :: [Text]) ==$> [text| - a x - b |] blockListF (["a"," b\nxx\ny y ","c\n\n"] :: [Text]) ==$> [text| - a - b xx y y_ - c __ |] test_jsonListF :: Spec test_jsonListF = describe "'jsonListF'" $ do emptyList nullElements singleLineElements multiLineElements mixed where emptyList = it "empty list" $ do jsonListF ([] :: [Int]) ==#> "[]\n" nullElements = it "null elements" $ do jsonListF ([""] :: [Text]) ==$> [text| [ ] |] jsonListF (["",""] :: [Text]) ==$> [text| [ , ] |] jsonListF (["","a",""] :: [Text]) ==$> [text| [ , a , ] |] singleLineElements = it "single-line elements" $ do jsonListF (["a"] :: [Text]) ==$> [text| [ a ] |] jsonListF (["a","b"] :: [Text]) ==$> [text| [ a , b ] |] jsonListF (["a","b","ccc"] :: [Text]) ==$> [text| [ a , b , ccc ] |] multiLineElements = it "multi-line elements" $ do jsonListF (["a\nx"] :: [Text]) ==$> [text| [ a x ] |] jsonListF (["a\n x"] :: [Text]) ==$> [text| [ a x ] |] jsonListF (["a\n x"," b\nxx\ny y ","c\n\n"] :: [Text]) ==$> [text| [ a x , b xx y y_ , c __ ] |] mixed = it "mix of single-line and multi-line" $ do jsonListF (["a\nx","b"] :: [Text]) ==$> [text| [ a x , b ] |] jsonListF (["a\nx","b\n"] :: [Text]) ==$> [text| [ a x , b ] |] jsonListF (["a"," b\nxx\ny y ","c\n\n"] :: [Text]) ==$> [text| [ a , b xx y y_ , c __ ] |] test_maps :: Spec test_maps = describe "maps" $ do test_mapF test_blockMapF test_jsonMapF test_mapF :: Spec test_mapF = describe "'mapF'" $ do it "simple examples" $ do mapF ([] :: [(Int, Int)]) ==#> "{}" mapF [(n,n+1)] ==#> "{25: 26}" mapF [(s,n)] ==#> "{!: 25}" mapF [('a',True),('b',False),('c',True)] ==#> "{a: True, b: False, c: True}" it "different map types" $ do let m = [('a',True),('b',False),('d',False),('c',True)] mapF m ==#> "{a: True, b: False, d: False, c: True}" mapF (M.fromList m) ==#> "{a: True, b: False, c: True, d: False}" test_blockMapF :: Spec test_blockMapF = describe "'blockMapF'" $ do it "empty map" $ do blockMapF ([] :: [(Int, Int)]) ==#> "{}\n" it "complex example" $ do blockMapF ([("hi", ""), ("foo"," a\n b"), ("bar","a"), ("baz","a\ng")] :: [(Text, Text)]) ==$> [text| hi: foo: a b bar: a baz: a g |] test_jsonMapF :: Spec test_jsonMapF = describe "'jsonMapF'" $ do it "empty map" $ do jsonMapF ([] :: [(Int, Int)]) ==#> "{}\n" it "complex example" $ do jsonMapF ([("hi", ""), ("foo"," a\n b"), ("bar","a"), ("baz","a\ng")] :: [(Text, Text)]) ==$> [text| { hi: , foo: a b , bar: a , baz: a g } |] test_tuples :: Spec test_tuples = describe "tuples" $ do test_tupleSimple describe "tupleF on lists" $ do test_tupleOneLine test_tupleMultiline test_tupleSimple :: Spec test_tupleSimple = it "tupleF" $ do tupleF (n, s) ==#> "(25, !)" tupleF (n, s, n, s) ==#> "(25, !, 25, !)" tupleF (n, s, n, s, 'a', 'b', 'c', 'd') ==#> "(25, !, 25, !, a, b, c, d)" test_tupleOneLine :: Spec test_tupleOneLine = describe "one-line" $ do it "()" $ do tupleF ([] :: [Builder]) ==#> "()" it "('')" $ do tupleF ([""] :: [Builder]) ==#> "()" it "(a)" $ do tupleF (["a"] :: [Builder]) ==#> "(a)" it "(a,b)" $ do tupleF (["a", "b"] :: [Builder]) ==#> "(a, b)" it "(a,'')" $ do tupleF (["a", ""] :: [Builder]) ==#> "(a, )" it "('',b)" $ do tupleF (["", "b"] :: [Builder]) ==#> "(, b)" it "('','')" $ do tupleF (["", ""] :: [Builder]) ==#> "(, )" it "(a,b,c)" $ do tupleF (["a", "ba", "caba"] :: [Builder]) ==#> "(a, ba, caba)" test_tupleMultiline :: Spec test_tupleMultiline = describe "multiline" $ do allNonEmpty someEmpty it "weird case" $ do tupleF ["a\n" :: Builder] ==#> "(a\n)" where allNonEmpty = describe "all non-empty" $ do it "1 element (2 lines)" $ do tupleF ["a\nx" :: Builder] ==$> [text| ( a x ) |] tupleF ["a\n x" :: Builder] ==$> [text| ( a x ) |] tupleF [" a\nx\n" :: Builder] ==$> [text| ( a x ) |] it "1 element (3 lines)" $ do tupleF ["a\nb\nc" :: Builder] ==$> [text| ( a b c ) |] it "2 elements (1 line + 2 lines)" $ do tupleF ["a", "b\nc" :: Builder] ==$> [text| ( a , b c ) |] it "2 elements (2 lines + 1 line)" $ do tupleF ["a\nb", "c" :: Builder] ==$> [text| ( a b , c ) |] it "3 elements (each has 2 lines)" $ do tupleF ["a\nb", "c\nd", "e\nf" :: Builder] ==$> [text| ( a b , c d , e f ) |] someEmpty = describe "some empty" $ do it "2 elements (0 + 2)" $ do tupleF ["", "a\nb" :: Builder] ==$> [text| ( , a b ) |] it "2 elements (2 + 0)" $ do tupleF ["a\nb", "" :: Builder] ==$> [text| ( a b , ) |] it "3 elements (0 + 2 + 0)" $ do tupleF ["", "a\nb", "" :: Builder] ==$> [text| ( , a b , ) |] it "3 elements (2 + 0 + 2)" $ do tupleF ["a\nb", "", "c\nd" :: Builder] ==$> [text| ( a b , , c d ) |] it "4 elements (2 + 0 + 0 + 2)" $ do tupleF ["a\nb", "", "", "c\nd" :: Builder] ==$> [text| ( a b , , , c d ) |] data Foo a = Foo a deriving Generic data Bar a = Bar a a deriving Generic data Qux a = Qux {q1 :: Int, q2 :: a, q3 :: Text} deriving Generic data Op = (:|:) Int | (:||:) Int Int | (:|||:) Int Int Int | Int :-: Int | Int `O` Int deriving Generic test_generic :: Spec test_generic = describe "'genericF'" $ do it "Maybe" $ do genericF (Nothing :: Maybe Int) ==#> "Nothing" genericF (Just 25 :: Maybe Int) ==#> "<Just: 25>" it "Either" $ do genericF (Left 25 :: Either Int Bool) ==#> "<Left: 25>" genericF (Right True :: Either Int Bool) ==#> "<Right: True>" it "tuples" $ do genericF (n, s) ==#> "(25, !)" genericF (n, s, -n, s ++ s) ==#> "(25, !, -25, !!)" describe "custom types" $ do it "ordinary constructors" $ do genericF (Foo n) ==#> "<Foo: 25>" genericF (Bar (n-1) (n+1)) ==#> "<Bar: 24, 26>" it "records" $ do genericF (Qux 1 True "hi") ==$> [text| Qux: q1: 1 q2: True q3: hi |] it "operators and infix constructors" $ do genericF ((:|:) 1) ==#> "<(:|:): 1>" genericF ((:||:) 1 2) ==#> "<(:||:): 1, 2>" genericF ((:|||:) 1 2 3) ==#> "<(:|||:): 1, 2, 3>" genericF ((:-:) 1 2) ==#> "(1 :-: 2)" genericF (O 1 2) ==#> "(1 `O` 2)" describe "types with non-Buildables inside" $ do it "functions" $ do genericF (Foo not) ==#> "<Foo: <function>>" it "lists" $ do genericF (Foo [n, n+1]) ==#> "<Foo: [25, 26]>" it "maps" $ do genericF (Foo (M.singleton n s)) ==#> "<Foo: {25: !}>" it "tuples" $ do genericF (Foo (n, s)) ==#> "<Foo: (25, !)>" genericF (Foo (n, s, n+1)) ==#> "<Foo: (25, !, 26)>" it "tuple with a string inside" $ do genericF (Foo (n, s)) ==#> "<Foo: (25, !)>" it "Either" $ do genericF (Foo (Left 25 :: Either Int Int)) ==#> "<Foo: <Left: 25>>" it "Maybe with a non-buildable" $ do genericF (Foo (Just [n])) ==#> "<Foo: [25]>" genericF (Foo (Nothing :: Maybe ())) ==#> "<Foo: <Nothing>>" Utilities (==%>) :: HasCallStack => Text -> Text -> Expectation (==%>) = shouldBe the RHS has @neat - interpolation@ string for which later versions ( > = 0.4 ) are discarding the final (==$>) :: HasCallStack => Builder -> Text -> Expectation (==$>) a b0 = a ==#> b where b = case T.last b0 == '\n' of True -> b0 False -> b0 <> "\n" (==#>) :: HasCallStack => Builder -> Text -> Expectation (==#>) a b = a `shouldBe` build (T.replace "_" " " b)
9376cdb4b568233f37d12b1cdfcc05a8c3eb3c210392efd56a7a9bf051bd97a1
PuercoPop/Movitz
bignums.lisp
;;;;------------------------------------------------------------------ ;;;; Copyright ( C ) 2003 - 2005 , Department of Computer Science , University of Tromso , Norway . ;;;; ;;;; For distribution policy, see the accompanying file COPYING. ;;;; ;;;; Filename: bignums.lisp ;;;; Description: Author : < > Created at : Sat Jul 17 19:42:57 2004 ;;;; $ I d : bignums.lisp , v 1.18 2008/02/04 15:11:16 Exp $ ;;;; ;;;;------------------------------------------------------------------ (require :muerte/basic-macros) (require :muerte/typep) (require :muerte/arithmetic-macros) (provide :muerte/bignums) (in-package muerte) (defun %bignum-bigits (x) (%bignum-bigits x)) (defun bignum-canonicalize (x) "Assuming x is a bignum, return the canonical integer value. That is, either return a fixnum, or destructively modify the bignum's length so that the msb isn't zero. DO NOT APPLY TO NON-BIGNUM VALUES!" (check-type x bignum) (macrolet ((do-it () `(with-inline-assembly (:returns :eax) (:load-lexical (:lexical-binding x) :eax) (:movl (:eax ,movitz:+other-type-offset+) :ecx) (:shrl 16 :ecx) (:jz '(:sub-program (should-never-happen) (:int 63))) shrink-loop (:cmpl 4 :ecx) (:je 'shrink-no-more) (:cmpl 0 (:eax :ecx ,(+ -4 (binary-types:slot-offset 'movitz:movitz-bignum 'movitz::bigit0)))) (:jnz 'shrink-done) (:subl 4 :ecx) (:jmp 'shrink-loop) shrink-no-more (:cmpl ,(1+ movitz:+movitz-most-positive-fixnum+) (:eax ,(binary-types:slot-offset 'movitz:movitz-bignum 'movitz::bigit0))) (:jc '(:sub-program (fixnum-result) (:movl (:eax ,(binary-types:slot-offset 'movitz:movitz-bignum 'movitz::bigit0)) :ecx) (:leal ((:ecx ,movitz:+movitz-fixnum-factor+)) :eax) (:jmp 'done))) shrink-done (:testb 3 :cl) (:jnz '(:sub-program () (:int 63))) (:testw :cx :cx) (:jz '(:sub-program () (:int 63))) (:movw :cx (:eax ,(binary-types:slot-offset 'movitz:movitz-bignum 'movitz::length))) done ))) (do-it))) (defun copy-bignum (old) (check-type old bignum) (%shallow-copy-object old (1+ (%bignum-bigits old)))) (defun %make-bignum (bigits &optional fill) (numargs-case (1 (bigits) (check-type bigits (unsigned-byte 14)) (macrolet ((do-it () `(let ((words (1+ bigits))) (with-non-pointer-allocation-assembly (words :fixed-size-p t :object-register :eax) (:load-lexical (:lexical-binding bigits) :ecx) (:shll 16 :ecx) (:orl ,(movitz:tag :bignum 0) :ecx) (:movl :ecx (:eax (:offset movitz-bignum type))))))) (do-it))) (t (bigits &optional fill) (let ((bignum (%make-bignum bigits))) (when fill (check-type fill (unsigned-byte 8)) (dotimes (i (* 4 bigits)) (setf (memref bignum (movitz-type-slot-offset 'movitz-bignum 'bigit0) :index i :type :unsigned-byte8) fill))) bignum)))) (defun print-bignum (x) (check-type x bignum) (dotimes (i (1+ (%bignum-bigits x))) (format t "~8,'0X " (memref x -6 :index i :type :unsigned-byte32))) (terpri) (values)) (defun bignum-add-fixnum (bignum delta) "Non-destructively add an unsigned fixnum delta to an (unsigned) bignum." (check-type bignum bignum) (check-type delta fixnum) (macrolet ((do-it () `(with-inline-assembly (:returns :eax :labels (not-size1 copy-bignum-loop add-bignum-loop add-bignum-done no-expansion pfix-pbig-done)) (:compile-two-forms (:eax :ebx) bignum delta) (:testl :ebx :ebx) (:jz 'pfix-pbig-done) ; EBX=0 => nothing to do. (:movzxw (:eax (:offset movitz-bignum length)) :ecx) (:cmpl ,movitz:+movitz-fixnum-factor+ :ecx) (:jne 'not-size1) (:compile-form (:result-mode :ecx) delta) (:shrl ,movitz:+movitz-fixnum-shift+ :ecx) (:addl (:eax (:offset movitz-bignum bigit0)) :ecx) (:jc 'not-size1) (:call-local-pf box-u32-ecx) (:jmp 'pfix-pbig-done) not-size1 ;; Set up atomically continuation. (:declare-label-set restart-jumper (restart-addition)) (:locally (:pushl (:edi (:edi-offset :dynamic-env)))) (:pushl 'restart-jumper) ;; ..this allows us to detect recursive atomicallies. (:locally (:pushl (:edi (:edi-offset :atomically-continuation)))) (:pushl :ebp) restart-addition (:movl (:esp) :ebp) (:compile-form (:result-mode :eax) bignum) (:movzxw (:eax (:offset movitz-bignum length)) :ecx) (:locally (:movl :esp (:edi (:edi-offset :atomically-continuation)))) ;; Now inside atomically section. (:leal ((:ecx 1) ,(* 2 movitz:+movitz-fixnum-factor+)) :eax) ; Number of words (:call-local-pf cons-non-pointer) (:load-lexical (:lexical-binding bignum) :ebx) ; bignum (:movzxw (:ebx (:offset movitz-bignum length)) :ecx) (:leal ((:ecx 1) ,movitz:+movitz-fixnum-factor+) :edx) MSB copy-bignum-loop (:subl ,movitz:+movitz-fixnum-factor+ :edx) (:movl (:ebx :edx ,movitz:+other-type-offset+) :ecx) (:movl :ecx (:eax :edx ,movitz:+other-type-offset+)) (:jnz 'copy-bignum-loop) (:load-lexical (:lexical-binding delta) :ecx) (:shrl ,movitz:+movitz-fixnum-shift+ :ecx) (:xorl :ebx :ebx) (:addl :ecx (:eax (:offset movitz-bignum bigit0))) (:jnc 'add-bignum-done) add-bignum-loop (:addl 4 :ebx) (:addl 1 (:eax :ebx (:offset movitz-bignum bigit0))) (:jc 'add-bignum-loop) add-bignum-done (:movzxw (:eax (:offset movitz-bignum length)) :ecx) (:leal ((:ecx 1) ,movitz:+movitz-fixnum-factor+) :ecx) (:cmpl 0 (:eax :ecx (:offset movitz-bignum bigit0 -4))) (:je 'no-expansion) (:addl #x40000 (:eax ,movitz:+other-type-offset+)) (:addl ,movitz:+movitz-fixnum-factor+ :ecx) no-expansion (:call-local-pf cons-commit-non-pointer) Exit atomically block . (:locally (:movl 0 (:edi (:edi-offset atomically-continuation)))) (:leal (:esp 16) :esp) pfix-pbig-done))) (do-it))) (defun bignum-addf-fixnum (bignum delta) "Destructively add a fixnum delta (negative or positive) to an (unsigned) bignum." (check-type delta fixnum) (check-type bignum bignum) (macrolet ((do-it () `(with-inline-assembly (:returns :eax :labels (add-bignum-loop add-bignum-done)) (:load-lexical (:lexical-binding delta) :ecx) (:load-lexical (:lexical-binding bignum) :eax) (:movzxw (:eax ,(binary-types:slot-offset 'movitz::movitz-bignum 'movitz::length)) :ebx) ; length (:xorl :edx :edx) ; counter (:sarl ,movitz:+movitz-fixnum-shift+ :ecx) (:jns 'positive-delta) ;; negative-delta (:negl :ecx) (:subl :ecx (:eax ,(binary-types:slot-offset 'movitz::movitz-bignum 'movitz::bigit0))) (:jnc 'add-bignum-done) sub-bignum-loop (:addl 4 :edx) (:cmpl :edx :ebx) (:je '(:sub-program (overflow) (:int 4))) (:subl 1 (:eax :edx ,(binary-types:slot-offset 'movitz::movitz-bignum 'movitz::bigit0))) (:jc 'sub-bignum-loop) (:jmp 'add-bignum-done) positive-delta (:addl :ecx (:eax ,(binary-types:slot-offset 'movitz::movitz-bignum 'movitz::bigit0))) (:jnc 'add-bignum-done) add-bignum-loop (:addl 4 :edx) (:cmpl :edx :ebx) (:je '(:sub-program (overflow) (:int 4))) (:addl 1 (:eax :edx ,(binary-types:slot-offset 'movitz::movitz-bignum 'movitz::bigit0))) (:jc 'add-bignum-loop) add-bignum-done))) (do-it))) (defun bignum-addf (bignum delta) "Destructively add (abs delta) to bignum." (check-type bignum bignum) (etypecase delta (positive-fixnum (bignum-addf-fixnum bignum delta)) (negative-fixnum (bignum-addf-fixnum bignum (- delta))) (bignum (macrolet ((do-it () `(with-inline-assembly (:returns :eax) not-size1 EAX = bignum EBX = delta (:xorl :edx :edx) ; Counter (:xorl :ecx :ecx) ; Carry add-bignum-loop (:addl (:ebx :edx (:offset movitz-bignum :bigit0)) :ecx) (:jz 'carry+digit-overflowed) ; If CF=1, then ECX=0. (:cmpw :dx (:eax (:offset movitz-bignum length))) (:jbe '(:sub-program (overflow) (:int 4))) (:addl :ecx (:eax :edx (:offset movitz-bignum bigit0))) carry+digit-overflowed (:sbbl :ecx :ecx) ECX = Add 's Carry . (:addl 4 :edx) (:cmpw :dx (:ebx (:offset movitz-bignum length))) (:ja 'add-bignum-loop) ;; Now, if there's a carry we must propagate it. (:jecxz 'add-bignum-done) carry-propagate-loop (:cmpw :dx (:eax (:offset movitz-bignum length))) (:jbe '(:sub-program (overflow) (:int 4))) (:addl 4 :edx) (:addl 1 (:eax :edx (:offset movitz-bignum bigit0 -4))) (:jc 'carry-propagate-loop) add-bignum-done))) (do-it))))) (defun bignum-subf (bignum delta) "Destructively subtract (abs delta) from bignum." (check-type bignum bignum) (etypecase delta (positive-fixnum (bignum-addf-fixnum bignum (- delta))) (negative-fixnum (bignum-addf-fixnum bignum delta)) (bignum (macrolet ((do-it () `(with-inline-assembly (:returns :eax) not-size1 EAX = bignum EBX = delta (:xorl :edx :edx) ; Counter (:xorl :ecx :ecx) ; Carry sub-bignum-loop (:cmpw :dx (:eax (:offset movitz-bignum length))) (:jbe '(:sub-program (overflow) (:int 4))) (:addl (:ebx :edx (:offset movitz-bignum :bigit0)) :ecx) (:jz 'carry+digit-overflowed) ; If CF=1, then ECX=0. (:subl :ecx (:eax :edx (:offset movitz-bignum bigit0))) carry+digit-overflowed (:sbbl :ecx :ecx) ECX = Add 's Carry . (:addl 4 :edx) (:cmpw :dx (:ebx (:offset movitz-bignum length))) (:ja 'sub-bignum-loop) ;; Now, if there's a carry we must propagate it. (:jecxz 'sub-bignum-done) carry-propagate-loop (:cmpw :dx (:eax (:offset movitz-bignum length))) (:jbe '(:sub-program (overflow) (:int 4))) (:addl 4 :edx) (:subl 1 (:eax :edx (:offset movitz-bignum bigit0 -4))) (:jc 'carry-propagate-loop) sub-bignum-done))) (do-it))))) (defun bignum-shift-rightf (bignum count) "Destructively right-shift bignum by count bits." (check-type bignum bignum) (check-type count positive-fixnum) (multiple-value-bind (long-shift short-shift) (truncate count 32) (macrolet ((do-it () `(with-inline-assembly (:returns :ebx) (:compile-two-forms (:edx :ebx) long-shift bignum) (:xorl :eax :eax) shift-long-loop (:cmpw :dx (:ebx (:offset movitz-bignum length))) (:jbe 'zero-msb-loop) (:movl (:ebx :edx (:offset movitz-bignum bigit0)) :ecx) (:movl :ecx (:ebx :eax (:offset movitz-bignum bigit0))) (:addl 4 :eax) (:addl 4 :edx) (:jmp 'shift-long-loop) zero-msb-loop (:cmpw :ax (:ebx (:offset movitz-bignum length))) (:jbe 'long-shift-done) (:movl 0 (:ebx :eax (:offset movitz-bignum bigit0))) (:addl 4 :eax) (:jmp 'zero-msb-loop) long-shift-done (:compile-form (:result-mode :ecx) short-shift) (:xorl :edx :edx) ; counter We need to use EAX for u32 storage . (:shrl ,movitz:+movitz-fixnum-shift+ :ecx) (:std) shift-short-loop (:addl 4 :edx) (:cmpw :dx (:ebx (:offset movitz-bignum length))) (:jbe 'end-shift-short-loop) (:movl (:ebx :edx (:offset movitz-bignum bigit0)) :eax) (:shrdl :cl :eax (:ebx :edx (:offset movitz-bignum bigit0 -4))) (:jmp 'shift-short-loop) end-shift-short-loop (:movl :edx :eax) ; Safe EAX (:shrl :cl (:ebx :edx (:offset movitz-bignum bigit0 -4))) (:cld)))) (do-it)))) (defun bignum-shift-leftf (bignum count) "Destructively left-shift bignum by count bits." (check-type bignum bignum) (check-type count positive-fixnum) (multiple-value-bind (long-shift short-shift) (truncate count 32) (macrolet ((do-it () `(with-inline-assembly (:returns :ebx) (:compile-two-forms (:ecx :ebx) long-shift bignum) (:jecxz 'long-shift-done) (:xorl :eax :eax) (:movw (:ebx (:offset movitz-bignum length)) :ax) (:subl 4 :eax) ; destination pointer (:movl :eax :edx) ;; Overflow check overflow-check-loop (:cmpl 0 (:ebx :edx (:offset movitz-bignum bigit0))) (:jne '(:sub-program (overflow) (:int 4))) (:subl 4 :edx) (:subl 4 :ecx) (:jnz 'overflow-check-loop) ;; (:subl :ecx :edx) ; source = EDX = (- dest long-shift) (:jc '(:sub-program (overflow) (:int 4))) shift-long-loop (:movl (:ebx :edx (:offset movitz-bignum bigit0)) :ecx) (:movl :ecx (:ebx :eax (:offset movitz-bignum bigit0))) (:subl 4 :eax) (:subl 4 :edx) (:jnc 'shift-long-loop) zero-lsb-loop (:movl 0 (:ebx :eax (:offset movitz-bignum bigit0))) ; EDX=0 (:subl 4 :eax) (:jnc 'zero-lsb-loop) long-shift-done (:compile-form (:result-mode :ecx) short-shift) (:shrl ,movitz:+movitz-fixnum-shift+ :ecx) (:jz 'done) (:xorl :esi :esi) ; counter (:movw (:ebx (:offset movitz-bignum length)) :si) (:subl 4 :esi) (:jz 'shift-short-lsb) (:xorl :eax :eax) (:std) ;; Overflow check (:movl (:ebx :esi (:offset movitz-bignum bigit0)) :eax) (:xorl :edx :edx) (:shldl :cl :eax :edx) (:jnz 'overflow) shift-short-loop (:movl (:ebx :esi (:offset movitz-bignum bigit0 -4)) :eax) (:shldl :cl :eax (:ebx :esi (:offset movitz-bignum bigit0))) (:subl 4 :esi) (:jnz 'shift-short-loop) (:movl :edi :edx) (:movl :edi :eax) ; Safe EAX (:cld) shift-short-lsb (:shll :cl (:ebx (:offset movitz-bignum bigit0))) done (:movl (:ebp -4) :esi) ))) (do-it)))) (defun bignum-mulf (bignum factor) "Destructively multiply bignum by (abs factor)." (check-type bignum bignum) (etypecase factor (bignum (error "not yet")) (negative-fixnum (bignum-mulf bignum (- factor))) (positive-fixnum (macrolet ((do-it () `(with-inline-assembly (:returns :ebx) (:load-lexical (:lexical-binding bignum) :ebx) ; bignum (:compile-form (:result-mode :ecx) factor) (:sarl ,movitz:+movitz-fixnum-shift+ :ecx) (:locally (:movl :ecx (:edi (:edi-offset raw-scratch0)))) Counter ( by 4 ) (:xorl :edx :edx) ; Initial carry Make EAX , EDX non - GC - roots . multiply-loop (:movl (:ebx :esi (:offset movitz-bignum bigit0)) :eax) Save carry in ECX EDX : EAX = scratch0*EAX (:addl :ecx :eax) ; Add carry Compute next carry (:jc '(:sub-program (should-not-happen) (:int 63))) (:movl :eax (:ebx :esi (:offset movitz-bignum bigit0))) (:addl 4 :esi) (:cmpw :si (:ebx (:offset movitz-bignum length))) (:ja 'multiply-loop) Carry into ECX (:movl :edi :eax) (:movl :edi :edx) (:cld) (:movl (:ebp -4) :esi) (:testl :ecx :ecx) ; Carry overflow? (:jnz '(:sub-program (overflow) (:int 4))) ))) (do-it))))) (defun bignum-truncatef (bignum divisor) (etypecase divisor (positive-fixnum (macrolet ((do-it () `(with-inline-assembly (:returns :ebx) (:compile-two-forms (:ebx :ecx) bignum divisor) (:xorl :edx :edx) ; hi-digit (:sarl ,movitz:+movitz-fixnum-shift+ :ecx) ESI is counter by 4 (:movw (:ebx (:offset movitz-bignum length)) :si) (:std) divide-loop (:movl (:ebx :esi (:offset movitz-bignum bigit0 -4)) :eax) ; lo-digit EDX : EAX = EDX : EAX / ECX (:movl :eax (:ebx :esi (:offset movitz-bignum bigit0 -4))) (:subl 4 :esi) (:jnz 'divide-loop) (:movl (:ebp -4) :esi) (:movl :edi :edx) (:movl :ebx :eax) (:cld)))) (do-it))))) (defun bignum-set-zerof (bignum) (check-type bignum bignum) (dotimes (i (%bignum-bigits bignum)) (setf (memref bignum (movitz-type-slot-offset 'movitz-bignum 'bigit0) :index i :type :unsigned-byte32) 0)) bignum) (defun %bignum= (x y) (check-type x bignum) (check-type y bignum) (compiler-macro-call %bignum= x y)) (defun %bignum< (x y) (check-type x bignum) (check-type y bignum) (compiler-macro-call %bignum< x y)) (defun %bignum-zerop (x) (compiler-macro-call %bignum-zerop x)) (defun bignum-integer-length (x) "Compute (integer-length (abs x))." (check-type x bignum) (macrolet ((do-it () `(with-inline-assembly (:returns :eax) (:compile-form (:result-mode :ebx) x) (:movzxw (:ebx (:offset movitz-bignum length)) :edx) (:xorl :eax :eax) bigit-scan-loop (:subl 4 :edx) (:jc 'done) (:cmpl 0 (:ebx :edx (:offset movitz-bignum bigit0))) (:jz 'bigit-scan-loop) Now , EAX must be loaded with ( + ( * EDX 32 ) bit - index 1 ) . Factor 8 (:bsrl (:ebx :edx (:offset movitz-bignum bigit0)) :ecx) Factor 4 (:leal ((:ecx 4) :eax 4) :eax) done))) (do-it))) (defun bignum-logcount (x) "Compute (logcount (abs x))." (check-type x bignum) (macrolet ((do-it () `(with-inline-assembly (:returns :eax) (:compile-form (:result-mode :ebx) x) (:xorl :eax :eax) (:xorl :edx :edx) (:movw (:ebx (:offset movitz-bignum length)) :dx) word-loop (:movl (:ebx :edx (:offset movitz-bignum bigit0 -4)) :ecx) bit-loop (:jecxz 'end-bit-loop) (:shrl 1 :ecx) (:jnc 'bit-loop) (:addl ,movitz:+movitz-fixnum-factor+ :eax) (:jmp 'bit-loop) end-bit-loop (:subl 4 :edx) (:jnz 'word-loop)))) (do-it))) (defun %bignum-negate (x) (compiler-macro-call %bignum-negate x)) (defun %bignum-plus-fixnum-size (x fixnum-delta) (compiler-macro-call %bignum-plus-fixnum-size x fixnum-delta)) (defun bignum-notf (x) (check-type x bignum) (macrolet ((do-it () `(with-inline-assembly (:returns :eax) (:load-lexical (:lexical-binding x) :eax) (:xorl :edx :edx) (:xorl :ecx :ecx) (:movw (:eax (:offset movitz-bignum length)) :cx) loop (:notl (:eax :edx (:offset movitz-bignum bigit0))) (:addl 4 :edx) (:cmpl :edx :ecx) (:ja 'loop)))) (do-it)))
null
https://raw.githubusercontent.com/PuercoPop/Movitz/7ffc41896c1e054aa43f44d64bbe9eaf3fcfa777/losp/muerte/bignums.lisp
lisp
------------------------------------------------------------------ For distribution policy, see the accompanying file COPYING. Filename: bignums.lisp Description: ------------------------------------------------------------------ EBX=0 => nothing to do. Set up atomically continuation. ..this allows us to detect recursive atomicallies. Now inside atomically section. Number of words bignum length counter negative-delta Counter Carry If CF=1, then ECX=0. Now, if there's a carry we must propagate it. Counter Carry If CF=1, then ECX=0. Now, if there's a carry we must propagate it. counter Safe EAX destination pointer Overflow check (:subl :ecx :edx) ; source = EDX = (- dest long-shift) EDX=0 counter Overflow check Safe EAX bignum Initial carry Add carry Carry overflow? hi-digit lo-digit
Copyright ( C ) 2003 - 2005 , Department of Computer Science , University of Tromso , Norway . Author : < > Created at : Sat Jul 17 19:42:57 2004 $ I d : bignums.lisp , v 1.18 2008/02/04 15:11:16 Exp $ (require :muerte/basic-macros) (require :muerte/typep) (require :muerte/arithmetic-macros) (provide :muerte/bignums) (in-package muerte) (defun %bignum-bigits (x) (%bignum-bigits x)) (defun bignum-canonicalize (x) "Assuming x is a bignum, return the canonical integer value. That is, either return a fixnum, or destructively modify the bignum's length so that the msb isn't zero. DO NOT APPLY TO NON-BIGNUM VALUES!" (check-type x bignum) (macrolet ((do-it () `(with-inline-assembly (:returns :eax) (:load-lexical (:lexical-binding x) :eax) (:movl (:eax ,movitz:+other-type-offset+) :ecx) (:shrl 16 :ecx) (:jz '(:sub-program (should-never-happen) (:int 63))) shrink-loop (:cmpl 4 :ecx) (:je 'shrink-no-more) (:cmpl 0 (:eax :ecx ,(+ -4 (binary-types:slot-offset 'movitz:movitz-bignum 'movitz::bigit0)))) (:jnz 'shrink-done) (:subl 4 :ecx) (:jmp 'shrink-loop) shrink-no-more (:cmpl ,(1+ movitz:+movitz-most-positive-fixnum+) (:eax ,(binary-types:slot-offset 'movitz:movitz-bignum 'movitz::bigit0))) (:jc '(:sub-program (fixnum-result) (:movl (:eax ,(binary-types:slot-offset 'movitz:movitz-bignum 'movitz::bigit0)) :ecx) (:leal ((:ecx ,movitz:+movitz-fixnum-factor+)) :eax) (:jmp 'done))) shrink-done (:testb 3 :cl) (:jnz '(:sub-program () (:int 63))) (:testw :cx :cx) (:jz '(:sub-program () (:int 63))) (:movw :cx (:eax ,(binary-types:slot-offset 'movitz:movitz-bignum 'movitz::length))) done ))) (do-it))) (defun copy-bignum (old) (check-type old bignum) (%shallow-copy-object old (1+ (%bignum-bigits old)))) (defun %make-bignum (bigits &optional fill) (numargs-case (1 (bigits) (check-type bigits (unsigned-byte 14)) (macrolet ((do-it () `(let ((words (1+ bigits))) (with-non-pointer-allocation-assembly (words :fixed-size-p t :object-register :eax) (:load-lexical (:lexical-binding bigits) :ecx) (:shll 16 :ecx) (:orl ,(movitz:tag :bignum 0) :ecx) (:movl :ecx (:eax (:offset movitz-bignum type))))))) (do-it))) (t (bigits &optional fill) (let ((bignum (%make-bignum bigits))) (when fill (check-type fill (unsigned-byte 8)) (dotimes (i (* 4 bigits)) (setf (memref bignum (movitz-type-slot-offset 'movitz-bignum 'bigit0) :index i :type :unsigned-byte8) fill))) bignum)))) (defun print-bignum (x) (check-type x bignum) (dotimes (i (1+ (%bignum-bigits x))) (format t "~8,'0X " (memref x -6 :index i :type :unsigned-byte32))) (terpri) (values)) (defun bignum-add-fixnum (bignum delta) "Non-destructively add an unsigned fixnum delta to an (unsigned) bignum." (check-type bignum bignum) (check-type delta fixnum) (macrolet ((do-it () `(with-inline-assembly (:returns :eax :labels (not-size1 copy-bignum-loop add-bignum-loop add-bignum-done no-expansion pfix-pbig-done)) (:compile-two-forms (:eax :ebx) bignum delta) (:testl :ebx :ebx) (:movzxw (:eax (:offset movitz-bignum length)) :ecx) (:cmpl ,movitz:+movitz-fixnum-factor+ :ecx) (:jne 'not-size1) (:compile-form (:result-mode :ecx) delta) (:shrl ,movitz:+movitz-fixnum-shift+ :ecx) (:addl (:eax (:offset movitz-bignum bigit0)) :ecx) (:jc 'not-size1) (:call-local-pf box-u32-ecx) (:jmp 'pfix-pbig-done) not-size1 (:declare-label-set restart-jumper (restart-addition)) (:locally (:pushl (:edi (:edi-offset :dynamic-env)))) (:pushl 'restart-jumper) (:locally (:pushl (:edi (:edi-offset :atomically-continuation)))) (:pushl :ebp) restart-addition (:movl (:esp) :ebp) (:compile-form (:result-mode :eax) bignum) (:movzxw (:eax (:offset movitz-bignum length)) :ecx) (:locally (:movl :esp (:edi (:edi-offset :atomically-continuation)))) (:leal ((:ecx 1) ,(* 2 movitz:+movitz-fixnum-factor+)) (:call-local-pf cons-non-pointer) (:movzxw (:ebx (:offset movitz-bignum length)) :ecx) (:leal ((:ecx 1) ,movitz:+movitz-fixnum-factor+) :edx) MSB copy-bignum-loop (:subl ,movitz:+movitz-fixnum-factor+ :edx) (:movl (:ebx :edx ,movitz:+other-type-offset+) :ecx) (:movl :ecx (:eax :edx ,movitz:+other-type-offset+)) (:jnz 'copy-bignum-loop) (:load-lexical (:lexical-binding delta) :ecx) (:shrl ,movitz:+movitz-fixnum-shift+ :ecx) (:xorl :ebx :ebx) (:addl :ecx (:eax (:offset movitz-bignum bigit0))) (:jnc 'add-bignum-done) add-bignum-loop (:addl 4 :ebx) (:addl 1 (:eax :ebx (:offset movitz-bignum bigit0))) (:jc 'add-bignum-loop) add-bignum-done (:movzxw (:eax (:offset movitz-bignum length)) :ecx) (:leal ((:ecx 1) ,movitz:+movitz-fixnum-factor+) :ecx) (:cmpl 0 (:eax :ecx (:offset movitz-bignum bigit0 -4))) (:je 'no-expansion) (:addl #x40000 (:eax ,movitz:+other-type-offset+)) (:addl ,movitz:+movitz-fixnum-factor+ :ecx) no-expansion (:call-local-pf cons-commit-non-pointer) Exit atomically block . (:locally (:movl 0 (:edi (:edi-offset atomically-continuation)))) (:leal (:esp 16) :esp) pfix-pbig-done))) (do-it))) (defun bignum-addf-fixnum (bignum delta) "Destructively add a fixnum delta (negative or positive) to an (unsigned) bignum." (check-type delta fixnum) (check-type bignum bignum) (macrolet ((do-it () `(with-inline-assembly (:returns :eax :labels (add-bignum-loop add-bignum-done)) (:load-lexical (:lexical-binding delta) :ecx) (:load-lexical (:lexical-binding bignum) :eax) (:sarl ,movitz:+movitz-fixnum-shift+ :ecx) (:jns 'positive-delta) (:negl :ecx) (:subl :ecx (:eax ,(binary-types:slot-offset 'movitz::movitz-bignum 'movitz::bigit0))) (:jnc 'add-bignum-done) sub-bignum-loop (:addl 4 :edx) (:cmpl :edx :ebx) (:je '(:sub-program (overflow) (:int 4))) (:subl 1 (:eax :edx ,(binary-types:slot-offset 'movitz::movitz-bignum 'movitz::bigit0))) (:jc 'sub-bignum-loop) (:jmp 'add-bignum-done) positive-delta (:addl :ecx (:eax ,(binary-types:slot-offset 'movitz::movitz-bignum 'movitz::bigit0))) (:jnc 'add-bignum-done) add-bignum-loop (:addl 4 :edx) (:cmpl :edx :ebx) (:je '(:sub-program (overflow) (:int 4))) (:addl 1 (:eax :edx ,(binary-types:slot-offset 'movitz::movitz-bignum 'movitz::bigit0))) (:jc 'add-bignum-loop) add-bignum-done))) (do-it))) (defun bignum-addf (bignum delta) "Destructively add (abs delta) to bignum." (check-type bignum bignum) (etypecase delta (positive-fixnum (bignum-addf-fixnum bignum delta)) (negative-fixnum (bignum-addf-fixnum bignum (- delta))) (bignum (macrolet ((do-it () `(with-inline-assembly (:returns :eax) not-size1 EAX = bignum EBX = delta add-bignum-loop (:addl (:ebx :edx (:offset movitz-bignum :bigit0)) :ecx) (:cmpw :dx (:eax (:offset movitz-bignum length))) (:jbe '(:sub-program (overflow) (:int 4))) (:addl :ecx (:eax :edx (:offset movitz-bignum bigit0))) carry+digit-overflowed (:sbbl :ecx :ecx) ECX = Add 's Carry . (:addl 4 :edx) (:cmpw :dx (:ebx (:offset movitz-bignum length))) (:ja 'add-bignum-loop) (:jecxz 'add-bignum-done) carry-propagate-loop (:cmpw :dx (:eax (:offset movitz-bignum length))) (:jbe '(:sub-program (overflow) (:int 4))) (:addl 4 :edx) (:addl 1 (:eax :edx (:offset movitz-bignum bigit0 -4))) (:jc 'carry-propagate-loop) add-bignum-done))) (do-it))))) (defun bignum-subf (bignum delta) "Destructively subtract (abs delta) from bignum." (check-type bignum bignum) (etypecase delta (positive-fixnum (bignum-addf-fixnum bignum (- delta))) (negative-fixnum (bignum-addf-fixnum bignum delta)) (bignum (macrolet ((do-it () `(with-inline-assembly (:returns :eax) not-size1 EAX = bignum EBX = delta sub-bignum-loop (:cmpw :dx (:eax (:offset movitz-bignum length))) (:jbe '(:sub-program (overflow) (:int 4))) (:addl (:ebx :edx (:offset movitz-bignum :bigit0)) :ecx) (:subl :ecx (:eax :edx (:offset movitz-bignum bigit0))) carry+digit-overflowed (:sbbl :ecx :ecx) ECX = Add 's Carry . (:addl 4 :edx) (:cmpw :dx (:ebx (:offset movitz-bignum length))) (:ja 'sub-bignum-loop) (:jecxz 'sub-bignum-done) carry-propagate-loop (:cmpw :dx (:eax (:offset movitz-bignum length))) (:jbe '(:sub-program (overflow) (:int 4))) (:addl 4 :edx) (:subl 1 (:eax :edx (:offset movitz-bignum bigit0 -4))) (:jc 'carry-propagate-loop) sub-bignum-done))) (do-it))))) (defun bignum-shift-rightf (bignum count) "Destructively right-shift bignum by count bits." (check-type bignum bignum) (check-type count positive-fixnum) (multiple-value-bind (long-shift short-shift) (truncate count 32) (macrolet ((do-it () `(with-inline-assembly (:returns :ebx) (:compile-two-forms (:edx :ebx) long-shift bignum) (:xorl :eax :eax) shift-long-loop (:cmpw :dx (:ebx (:offset movitz-bignum length))) (:jbe 'zero-msb-loop) (:movl (:ebx :edx (:offset movitz-bignum bigit0)) :ecx) (:movl :ecx (:ebx :eax (:offset movitz-bignum bigit0))) (:addl 4 :eax) (:addl 4 :edx) (:jmp 'shift-long-loop) zero-msb-loop (:cmpw :ax (:ebx (:offset movitz-bignum length))) (:jbe 'long-shift-done) (:movl 0 (:ebx :eax (:offset movitz-bignum bigit0))) (:addl 4 :eax) (:jmp 'zero-msb-loop) long-shift-done (:compile-form (:result-mode :ecx) short-shift) We need to use EAX for u32 storage . (:shrl ,movitz:+movitz-fixnum-shift+ :ecx) (:std) shift-short-loop (:addl 4 :edx) (:cmpw :dx (:ebx (:offset movitz-bignum length))) (:jbe 'end-shift-short-loop) (:movl (:ebx :edx (:offset movitz-bignum bigit0)) :eax) (:shrdl :cl :eax (:ebx :edx (:offset movitz-bignum bigit0 -4))) (:jmp 'shift-short-loop) end-shift-short-loop (:shrl :cl (:ebx :edx (:offset movitz-bignum bigit0 -4))) (:cld)))) (do-it)))) (defun bignum-shift-leftf (bignum count) "Destructively left-shift bignum by count bits." (check-type bignum bignum) (check-type count positive-fixnum) (multiple-value-bind (long-shift short-shift) (truncate count 32) (macrolet ((do-it () `(with-inline-assembly (:returns :ebx) (:compile-two-forms (:ecx :ebx) long-shift bignum) (:jecxz 'long-shift-done) (:xorl :eax :eax) (:movw (:ebx (:offset movitz-bignum length)) :ax) (:movl :eax :edx) overflow-check-loop (:cmpl 0 (:ebx :edx (:offset movitz-bignum bigit0))) (:jne '(:sub-program (overflow) (:int 4))) (:subl 4 :edx) (:subl 4 :ecx) (:jnz 'overflow-check-loop) (:jc '(:sub-program (overflow) (:int 4))) shift-long-loop (:movl (:ebx :edx (:offset movitz-bignum bigit0)) :ecx) (:movl :ecx (:ebx :eax (:offset movitz-bignum bigit0))) (:subl 4 :eax) (:subl 4 :edx) (:jnc 'shift-long-loop) zero-lsb-loop (:subl 4 :eax) (:jnc 'zero-lsb-loop) long-shift-done (:compile-form (:result-mode :ecx) short-shift) (:shrl ,movitz:+movitz-fixnum-shift+ :ecx) (:jz 'done) (:movw (:ebx (:offset movitz-bignum length)) :si) (:subl 4 :esi) (:jz 'shift-short-lsb) (:xorl :eax :eax) (:std) (:movl (:ebx :esi (:offset movitz-bignum bigit0)) :eax) (:xorl :edx :edx) (:shldl :cl :eax :edx) (:jnz 'overflow) shift-short-loop (:movl (:ebx :esi (:offset movitz-bignum bigit0 -4)) :eax) (:shldl :cl :eax (:ebx :esi (:offset movitz-bignum bigit0))) (:subl 4 :esi) (:jnz 'shift-short-loop) (:movl :edi :edx) (:cld) shift-short-lsb (:shll :cl (:ebx (:offset movitz-bignum bigit0))) done (:movl (:ebp -4) :esi) ))) (do-it)))) (defun bignum-mulf (bignum factor) "Destructively multiply bignum by (abs factor)." (check-type bignum bignum) (etypecase factor (bignum (error "not yet")) (negative-fixnum (bignum-mulf bignum (- factor))) (positive-fixnum (macrolet ((do-it () `(with-inline-assembly (:returns :ebx) (:compile-form (:result-mode :ecx) factor) (:sarl ,movitz:+movitz-fixnum-shift+ :ecx) (:locally (:movl :ecx (:edi (:edi-offset raw-scratch0)))) Counter ( by 4 ) Make EAX , EDX non - GC - roots . multiply-loop (:movl (:ebx :esi (:offset movitz-bignum bigit0)) :eax) Save carry in ECX EDX : EAX = scratch0*EAX Compute next carry (:jc '(:sub-program (should-not-happen) (:int 63))) (:movl :eax (:ebx :esi (:offset movitz-bignum bigit0))) (:addl 4 :esi) (:cmpw :si (:ebx (:offset movitz-bignum length))) (:ja 'multiply-loop) Carry into ECX (:movl :edi :eax) (:movl :edi :edx) (:cld) (:movl (:ebp -4) :esi) (:jnz '(:sub-program (overflow) (:int 4))) ))) (do-it))))) (defun bignum-truncatef (bignum divisor) (etypecase divisor (positive-fixnum (macrolet ((do-it () `(with-inline-assembly (:returns :ebx) (:compile-two-forms (:ebx :ecx) bignum divisor) (:sarl ,movitz:+movitz-fixnum-shift+ :ecx) ESI is counter by 4 (:movw (:ebx (:offset movitz-bignum length)) :si) (:std) divide-loop (:movl (:ebx :esi (:offset movitz-bignum bigit0 -4)) EDX : EAX = EDX : EAX / ECX (:movl :eax (:ebx :esi (:offset movitz-bignum bigit0 -4))) (:subl 4 :esi) (:jnz 'divide-loop) (:movl (:ebp -4) :esi) (:movl :edi :edx) (:movl :ebx :eax) (:cld)))) (do-it))))) (defun bignum-set-zerof (bignum) (check-type bignum bignum) (dotimes (i (%bignum-bigits bignum)) (setf (memref bignum (movitz-type-slot-offset 'movitz-bignum 'bigit0) :index i :type :unsigned-byte32) 0)) bignum) (defun %bignum= (x y) (check-type x bignum) (check-type y bignum) (compiler-macro-call %bignum= x y)) (defun %bignum< (x y) (check-type x bignum) (check-type y bignum) (compiler-macro-call %bignum< x y)) (defun %bignum-zerop (x) (compiler-macro-call %bignum-zerop x)) (defun bignum-integer-length (x) "Compute (integer-length (abs x))." (check-type x bignum) (macrolet ((do-it () `(with-inline-assembly (:returns :eax) (:compile-form (:result-mode :ebx) x) (:movzxw (:ebx (:offset movitz-bignum length)) :edx) (:xorl :eax :eax) bigit-scan-loop (:subl 4 :edx) (:jc 'done) (:cmpl 0 (:ebx :edx (:offset movitz-bignum bigit0))) (:jz 'bigit-scan-loop) Now , EAX must be loaded with ( + ( * EDX 32 ) bit - index 1 ) . Factor 8 (:bsrl (:ebx :edx (:offset movitz-bignum bigit0)) :ecx) Factor 4 (:leal ((:ecx 4) :eax 4) :eax) done))) (do-it))) (defun bignum-logcount (x) "Compute (logcount (abs x))." (check-type x bignum) (macrolet ((do-it () `(with-inline-assembly (:returns :eax) (:compile-form (:result-mode :ebx) x) (:xorl :eax :eax) (:xorl :edx :edx) (:movw (:ebx (:offset movitz-bignum length)) :dx) word-loop (:movl (:ebx :edx (:offset movitz-bignum bigit0 -4)) :ecx) bit-loop (:jecxz 'end-bit-loop) (:shrl 1 :ecx) (:jnc 'bit-loop) (:addl ,movitz:+movitz-fixnum-factor+ :eax) (:jmp 'bit-loop) end-bit-loop (:subl 4 :edx) (:jnz 'word-loop)))) (do-it))) (defun %bignum-negate (x) (compiler-macro-call %bignum-negate x)) (defun %bignum-plus-fixnum-size (x fixnum-delta) (compiler-macro-call %bignum-plus-fixnum-size x fixnum-delta)) (defun bignum-notf (x) (check-type x bignum) (macrolet ((do-it () `(with-inline-assembly (:returns :eax) (:load-lexical (:lexical-binding x) :eax) (:xorl :edx :edx) (:xorl :ecx :ecx) (:movw (:eax (:offset movitz-bignum length)) :cx) loop (:notl (:eax :edx (:offset movitz-bignum bigit0))) (:addl 4 :edx) (:cmpl :edx :ecx) (:ja 'loop)))) (do-it)))
db87895c53711bc25187669aa8c4f89601a3ef3137dc71bc07535df74dc65ed3
elli-lib/elli
elli_middleware_tests.erl
-module(elli_middleware_tests). -include_lib("eunit/include/eunit.hrl"). -include("elli_test.hrl"). elli_test_() -> {setup, fun setup/0, fun teardown/1, [ ?_test(hello_world()), ?_test(short_circuit()), ?_test(compress()), ?_test(no_callbacks()) ]}. %% %% TESTS %% short_circuit() -> URL = ":3002/middleware/short-circuit", Response = hackney:get(URL), ?assertMatch(<<"short circuit!">>, body(Response)). hello_world() -> URL = ":3002/hello/world", Response = hackney:get(URL), ?assertMatch(<<"Hello World!">>, body(Response)). compress() -> Url = ":3002/compressed", Headers = [{<<"Accept-Encoding">>, <<"gzip">>}], Response = hackney:get(Url, Headers), ?assertHeadersEqual([{<<"Connection">>, <<"Keep-Alive">>}, {<<"Content-Encoding">>, <<"gzip">>}, {<<"Content-Length">>, <<"41">>}], headers(Response)), ?assertEqual(binary:copy(<<"Hello World!">>, 86), zlib:gunzip(body(Response))), Response1 = hackney:get(":3002/compressed"), ?assertHeadersEqual([{<<"Connection">>, <<"Keep-Alive">>}, {<<"Content-Length">>, <<"1032">>}], headers(Response1)), ?assertEqual(iolist_to_binary(lists:duplicate(86, "Hello World!")), body(Response1)), Url2 = ":3002/compressed-io_list", Headers2 = [{<<"Accept-Encoding">>, <<"gzip">>}], Response2 = hackney:get(Url2, Headers2), ?assertMatch(200, status(Response2)), ?assertHeadersEqual([{<<"Connection">>, <<"Keep-Alive">>}, {<<"Content-Encoding">>, <<"gzip">>}, {<<"Content-Length">>, <<"41">>}], headers(Response2)), ?assertEqual(binary:copy(<<"Hello World!">>, 86), zlib:gunzip(body(Response2))), Response3 = hackney:request(":3002/compressed-io_list"), ?assertMatch(200, status(Response3)), ?assertHeadersEqual([{<<"Connection">>, <<"Keep-Alive">>}, {<<"Content-Length">>, <<"1032">>}], headers(Response3)), ?assertEqual(iolist_to_binary(lists:duplicate(86, "Hello World!")), body(Response3)). no_callbacks() -> Response = hackney:get(":3004/whatever"), ?assertMatch(404, status(Response)), ?assertMatch(<<"Not Found">>, body(Response)). %% %% HELPERS %% setup() -> application:start(crypto), application:start(public_key), application:start(ssl), {ok, _} = application:ensure_all_started(hackney), Config = [ {mods, [ {elli_access_log, [{name, elli_syslog}, {ip, "127.0.0.1"}, {port, 514}]}, {elli_example_middleware, []}, {elli_middleware_compress, []}, {elli_example_callback, []} ]} ], {ok, P1} = elli:start_link([{callback, elli_middleware}, {callback_args, Config}, {port, 3002}]), unlink(P1), {ok, P2} = elli:start_link([{callback, elli_middleware}, {callback_args, [{mods, []}]}, {port, 3004}]), unlink(P2), [P1, P2]. teardown(Pids) -> [elli:stop(P) || P <- Pids].
null
https://raw.githubusercontent.com/elli-lib/elli/2f2fafb77c67244ba6237ca6b3c7238ff886c478/test/elli_middleware_tests.erl
erlang
TESTS HELPERS
-module(elli_middleware_tests). -include_lib("eunit/include/eunit.hrl"). -include("elli_test.hrl"). elli_test_() -> {setup, fun setup/0, fun teardown/1, [ ?_test(hello_world()), ?_test(short_circuit()), ?_test(compress()), ?_test(no_callbacks()) ]}. short_circuit() -> URL = ":3002/middleware/short-circuit", Response = hackney:get(URL), ?assertMatch(<<"short circuit!">>, body(Response)). hello_world() -> URL = ":3002/hello/world", Response = hackney:get(URL), ?assertMatch(<<"Hello World!">>, body(Response)). compress() -> Url = ":3002/compressed", Headers = [{<<"Accept-Encoding">>, <<"gzip">>}], Response = hackney:get(Url, Headers), ?assertHeadersEqual([{<<"Connection">>, <<"Keep-Alive">>}, {<<"Content-Encoding">>, <<"gzip">>}, {<<"Content-Length">>, <<"41">>}], headers(Response)), ?assertEqual(binary:copy(<<"Hello World!">>, 86), zlib:gunzip(body(Response))), Response1 = hackney:get(":3002/compressed"), ?assertHeadersEqual([{<<"Connection">>, <<"Keep-Alive">>}, {<<"Content-Length">>, <<"1032">>}], headers(Response1)), ?assertEqual(iolist_to_binary(lists:duplicate(86, "Hello World!")), body(Response1)), Url2 = ":3002/compressed-io_list", Headers2 = [{<<"Accept-Encoding">>, <<"gzip">>}], Response2 = hackney:get(Url2, Headers2), ?assertMatch(200, status(Response2)), ?assertHeadersEqual([{<<"Connection">>, <<"Keep-Alive">>}, {<<"Content-Encoding">>, <<"gzip">>}, {<<"Content-Length">>, <<"41">>}], headers(Response2)), ?assertEqual(binary:copy(<<"Hello World!">>, 86), zlib:gunzip(body(Response2))), Response3 = hackney:request(":3002/compressed-io_list"), ?assertMatch(200, status(Response3)), ?assertHeadersEqual([{<<"Connection">>, <<"Keep-Alive">>}, {<<"Content-Length">>, <<"1032">>}], headers(Response3)), ?assertEqual(iolist_to_binary(lists:duplicate(86, "Hello World!")), body(Response3)). no_callbacks() -> Response = hackney:get(":3004/whatever"), ?assertMatch(404, status(Response)), ?assertMatch(<<"Not Found">>, body(Response)). setup() -> application:start(crypto), application:start(public_key), application:start(ssl), {ok, _} = application:ensure_all_started(hackney), Config = [ {mods, [ {elli_access_log, [{name, elli_syslog}, {ip, "127.0.0.1"}, {port, 514}]}, {elli_example_middleware, []}, {elli_middleware_compress, []}, {elli_example_callback, []} ]} ], {ok, P1} = elli:start_link([{callback, elli_middleware}, {callback_args, Config}, {port, 3002}]), unlink(P1), {ok, P2} = elli:start_link([{callback, elli_middleware}, {callback_args, [{mods, []}]}, {port, 3004}]), unlink(P2), [P1, P2]. teardown(Pids) -> [elli:stop(P) || P <- Pids].
504ed5b0712addaf9af4ac124ff2511331cd491e68542ddb892bffd5fd0439bf
weldr/bdcs
ReqType.hs
# LANGUAGE TemplateHaskell # -- | -- Module: BDCS.ReqType Copyright : ( c ) 2016 - 2017 Red Hat , Inc. -- License: LGPL -- Maintainer : -- Stability: alpha -- Portability: portable -- -- Data types for working with 'Requirements'. module BDCS.ReqType(ReqContext(..), ReqLanguage(..), ReqStrength(..)) where import Database.Persist.TH # ANN module ( " HLint : ignore Use module export list " : : String ) # -- | The type of a requirements language - this basically maps to a packaging -- system. For now, only RPM is supported. data ReqLanguage = RPM deriving(Eq, Read, Show) -- | The type for specifying when a requirement should be enforced. data ReqContext = Build -- ^ Applies when building | Runtime -- ^ Applies when the package is on the system | Test -- ^ Applies to running tests | ScriptPre -- ^ Before a package install | ScriptPost -- ^ After a package install | ScriptPreUn -- ^ Before a package uninstall | ScriptPostUn -- ^ After a package uninstall | ScriptPreTrans -- ^ Before a package transaction | ScriptPostTrans -- ^ After a package transaction | ScriptVerify -- ^ Package verification script | Feature -- ^ Feature requirement, e.g. rpmlib features deriving(Eq, Read, Show) -- | The type for specifying how strictly a requirement should be enforced. data ReqStrength = Must -- ^ A requirement must be satisfied | Should -- ^ A requirement should be satisfied, but it is -- not an error if it cannot be. | May -- ^ A requirement should only be satisfied at the -- user's option. Typically, automated processes -- will ignore this. | ShouldIfInstalled -- ^ Like 'Should', but looks at packages that are -- already installed. | MayIfInstalled -- ^ Like 'May', but looks at packages that are -- already installed. deriving(Eq, Read, Show) derivePersistField "ReqLanguage" derivePersistField "ReqContext" derivePersistField "ReqStrength"
null
https://raw.githubusercontent.com/weldr/bdcs/cf360c3240644b4847336b9d58b2067f3aa1ec50/src/BDCS/ReqType.hs
haskell
| Module: BDCS.ReqType License: LGPL Stability: alpha Portability: portable Data types for working with 'Requirements'. | The type of a requirements language - this basically maps to a packaging system. For now, only RPM is supported. | The type for specifying when a requirement should be enforced. ^ Applies when building ^ Applies when the package is on the system ^ Applies to running tests ^ Before a package install ^ After a package install ^ Before a package uninstall ^ After a package uninstall ^ Before a package transaction ^ After a package transaction ^ Package verification script ^ Feature requirement, e.g. rpmlib features | The type for specifying how strictly a requirement should be enforced. ^ A requirement must be satisfied ^ A requirement should be satisfied, but it is not an error if it cannot be. ^ A requirement should only be satisfied at the user's option. Typically, automated processes will ignore this. ^ Like 'Should', but looks at packages that are already installed. ^ Like 'May', but looks at packages that are already installed.
# LANGUAGE TemplateHaskell # Copyright : ( c ) 2016 - 2017 Red Hat , Inc. Maintainer : module BDCS.ReqType(ReqContext(..), ReqLanguage(..), ReqStrength(..)) where import Database.Persist.TH # ANN module ( " HLint : ignore Use module export list " : : String ) # data ReqLanguage = RPM deriving(Eq, Read, Show) deriving(Eq, Read, Show) deriving(Eq, Read, Show) derivePersistField "ReqLanguage" derivePersistField "ReqContext" derivePersistField "ReqStrength"
a28ace0b71c6dbfe86595575d124bacdaa57332915326df960c99f8a833d5ec7
finnishtransportagency/harja
maksuera_sanoma_test.clj
(ns harja.palvelin.integraatiot.sampo.sanomat.maksuera-sanoma-test (:require [clojure.test :refer [deftest is use-fixtures]] [harja.palvelin.integraatiot.sampo.sanomat.maksuera_sanoma :as maksuera_sanoma] [hiccup.core :refer [html]] [clojure.xml :refer [parse]] [clojure.zip :refer [xml-zip]] [clojure.data.zip.xml :as z] [harja.testi :refer :all] [harja.tyokalut.xml :as xml] [harja.pvm :as pvm]) (:import (java.io ByteArrayInputStream) (java.text SimpleDateFormat))) (def +xsd-polku+ "xsd/sampo/outbound/") (def +maksuera+ {:numero 123456789 :maksuera {:nimi "Testimaksuera" :tyyppi "kokonaishintainen" :summa 1304.89} :toimenpideinstanssi {:alkupvm #inst"2015-10-01T00:00:00.000+03:00" :vastuuhenkilo "A009717" :talousosasto "talousosasto" :talousosastopolku "polku/talousosasto" :tuotepolku "polku/tuote" :sampoid "SAMPOID"} :urakka {:sampoid "PR00020606" :loppupvm #inst"2017-09-30T00:00:00.000+03:00"} :sopimus {:sampoid "00LZM-0033600"}}) (deftest tarkista-maksueran-validius (let [maksuera (html (maksuera_sanoma/maksuera-xml +maksuera+)) xsd "nikuxog_product.xsd"] (is (xml/validi-xml? +xsd-polku+ xsd maksuera) "Muodostettu XML-tiedosto on XSD-skeeman mukainen"))) Varmistetaan erityisesti , koska maksimi on 2076 ja Taloushallinnon kanssa on sovittu , että siihen päivä . (deftest tarkista-maksueran-validius2 (let [maksuera (slurp "test/resurssit/sampo/validoitava_maksuera.xml") xsd "nikuxog_product.xsd"] (is (xml/validi-xml? +xsd-polku+ xsd maksuera) "Muodostettu XML-tiedosto on XSD-skeeman mukainen"))) (defn kuluvuosi [] (str "kulu" (pvm/vuosi (pvm/nyt)))) (deftest tarkista-maksueran-sisalto (let [maksuera-xml (xml-zip (parse (ByteArrayInputStream. (.getBytes (html (maksuera_sanoma/maksuera-xml +maksuera+)) "UTF-8"))))] (is (= "2015-10-01T00:00:00" (z/xml1-> maksuera-xml :Products :Product (z/attr :start)))) : puskuri (is (= "L934498" (z/xml1-> maksuera-xml :Products :Product (z/attr :managerUserName)))) (is (= "Testimaksuera" (z/xml1-> maksuera-xml :Products :Product (z/attr :name)))) (is (= "HA123456789" (z/xml1-> maksuera-xml :Products :Product (z/attr :objectID)))) (is (= "SAMPOID" (z/xml1-> maksuera-xml :Products :Product :InvestmentAssociations :Allocations :ParentInvestment (z/attr :InvestmentID)))) (is (= (kuluvuosi) (z/xml1-> maksuera-xml :Products :Product :InvestmentResources :Resource (z/attr :resourceID)))) (is (= (kuluvuosi) (z/xml1-> maksuera-xml :Products :Product :InvestmentTasks :Task :Assignments :TaskLabor (z/attr :resourceID)))) (is (= "Testimaksuera" (z/xml1-> maksuera-xml :Products :Product :InvestmentTasks :Task (z/attr :name)))) (is (= "polku/talousosasto" (z/xml1-> maksuera-xml :Products :Product :OBSAssocs :OBSAssoc (z/attr= :id "LiiviKP") (z/attr :unitPath)))) (is (= "polku/tuote" (z/xml1-> maksuera-xml :Products :Product :OBSAssocs :OBSAssoc (z/attr= :id "tuote2013") (z/attr :unitPath)))) (is (= "00LZM-0033600" (z/xml1-> maksuera-xml :Products :Product :CustomInformation :ColumnValue (z/attr= :name "vv_tilaus") z/text))) (is (= "2" (z/xml1-> maksuera-xml :Products :Product :CustomInformation :ColumnValue (z/attr= :name "vv_me_type") z/text))) (is (= "123456789" (z/xml1-> maksuera-xml :Products :Product :CustomInformation :ColumnValue (z/attr= :name "vv_inst_no") z/text))) (is (= "AL123456789" (z/xml1-> maksuera-xml :Products :Product :CustomInformation :instance (z/attr :instanceCode)))) (is (= "1304.89" (z/xml1-> maksuera-xml :Products :Product :CustomInformation :instance :CustomInformation :ColumnValue (z/attr= :name "vv_paym_sum") z/text)))))
null
https://raw.githubusercontent.com/finnishtransportagency/harja/c56d06472dcccecfd73921261c483ea904970635/test/clj/harja/palvelin/integraatiot/sampo/sanomat/maksuera_sanoma_test.clj
clojure
(ns harja.palvelin.integraatiot.sampo.sanomat.maksuera-sanoma-test (:require [clojure.test :refer [deftest is use-fixtures]] [harja.palvelin.integraatiot.sampo.sanomat.maksuera_sanoma :as maksuera_sanoma] [hiccup.core :refer [html]] [clojure.xml :refer [parse]] [clojure.zip :refer [xml-zip]] [clojure.data.zip.xml :as z] [harja.testi :refer :all] [harja.tyokalut.xml :as xml] [harja.pvm :as pvm]) (:import (java.io ByteArrayInputStream) (java.text SimpleDateFormat))) (def +xsd-polku+ "xsd/sampo/outbound/") (def +maksuera+ {:numero 123456789 :maksuera {:nimi "Testimaksuera" :tyyppi "kokonaishintainen" :summa 1304.89} :toimenpideinstanssi {:alkupvm #inst"2015-10-01T00:00:00.000+03:00" :vastuuhenkilo "A009717" :talousosasto "talousosasto" :talousosastopolku "polku/talousosasto" :tuotepolku "polku/tuote" :sampoid "SAMPOID"} :urakka {:sampoid "PR00020606" :loppupvm #inst"2017-09-30T00:00:00.000+03:00"} :sopimus {:sampoid "00LZM-0033600"}}) (deftest tarkista-maksueran-validius (let [maksuera (html (maksuera_sanoma/maksuera-xml +maksuera+)) xsd "nikuxog_product.xsd"] (is (xml/validi-xml? +xsd-polku+ xsd maksuera) "Muodostettu XML-tiedosto on XSD-skeeman mukainen"))) Varmistetaan erityisesti , koska maksimi on 2076 ja Taloushallinnon kanssa on sovittu , että siihen päivä . (deftest tarkista-maksueran-validius2 (let [maksuera (slurp "test/resurssit/sampo/validoitava_maksuera.xml") xsd "nikuxog_product.xsd"] (is (xml/validi-xml? +xsd-polku+ xsd maksuera) "Muodostettu XML-tiedosto on XSD-skeeman mukainen"))) (defn kuluvuosi [] (str "kulu" (pvm/vuosi (pvm/nyt)))) (deftest tarkista-maksueran-sisalto (let [maksuera-xml (xml-zip (parse (ByteArrayInputStream. (.getBytes (html (maksuera_sanoma/maksuera-xml +maksuera+)) "UTF-8"))))] (is (= "2015-10-01T00:00:00" (z/xml1-> maksuera-xml :Products :Product (z/attr :start)))) : puskuri (is (= "L934498" (z/xml1-> maksuera-xml :Products :Product (z/attr :managerUserName)))) (is (= "Testimaksuera" (z/xml1-> maksuera-xml :Products :Product (z/attr :name)))) (is (= "HA123456789" (z/xml1-> maksuera-xml :Products :Product (z/attr :objectID)))) (is (= "SAMPOID" (z/xml1-> maksuera-xml :Products :Product :InvestmentAssociations :Allocations :ParentInvestment (z/attr :InvestmentID)))) (is (= (kuluvuosi) (z/xml1-> maksuera-xml :Products :Product :InvestmentResources :Resource (z/attr :resourceID)))) (is (= (kuluvuosi) (z/xml1-> maksuera-xml :Products :Product :InvestmentTasks :Task :Assignments :TaskLabor (z/attr :resourceID)))) (is (= "Testimaksuera" (z/xml1-> maksuera-xml :Products :Product :InvestmentTasks :Task (z/attr :name)))) (is (= "polku/talousosasto" (z/xml1-> maksuera-xml :Products :Product :OBSAssocs :OBSAssoc (z/attr= :id "LiiviKP") (z/attr :unitPath)))) (is (= "polku/tuote" (z/xml1-> maksuera-xml :Products :Product :OBSAssocs :OBSAssoc (z/attr= :id "tuote2013") (z/attr :unitPath)))) (is (= "00LZM-0033600" (z/xml1-> maksuera-xml :Products :Product :CustomInformation :ColumnValue (z/attr= :name "vv_tilaus") z/text))) (is (= "2" (z/xml1-> maksuera-xml :Products :Product :CustomInformation :ColumnValue (z/attr= :name "vv_me_type") z/text))) (is (= "123456789" (z/xml1-> maksuera-xml :Products :Product :CustomInformation :ColumnValue (z/attr= :name "vv_inst_no") z/text))) (is (= "AL123456789" (z/xml1-> maksuera-xml :Products :Product :CustomInformation :instance (z/attr :instanceCode)))) (is (= "1304.89" (z/xml1-> maksuera-xml :Products :Product :CustomInformation :instance :CustomInformation :ColumnValue (z/attr= :name "vv_paym_sum") z/text)))))
16c40faa9283711605e24cf6014533e39e26b441bc2dac8dafb6b68f8f76f328
lambdaclass/erlang-katana
ktn_date.erl
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% ktn_date : functions useful for handling dates and time values %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -module(ktn_date). -export([ now_human_readable/0 ]). -type date() :: {date, {non_neg_integer(), 1..12, 1..31}}. -type datetime() :: { datetime , {{integer(), 1..12, 1..31} , {1..24, 1..60, 1..60}} }. -export_type( [ date/0 , datetime/0 ]). %% @doc Returns the current date in a human readable format binary. -spec now_human_readable() -> binary(). now_human_readable() -> TimeStamp = {_, _, Micro} = os:timestamp(), {{Year, Month, Day}, {Hour, Minute, Second}} = calendar:now_to_universal_time(TimeStamp), DateList = io_lib:format("~p-~2..0B-~2..0BT~p:~p:~p.~6..0wZ", [Year, Month, Day, Hour, Minute, Second, Micro]), list_to_binary(DateList).
null
https://raw.githubusercontent.com/lambdaclass/erlang-katana/ebb6b1358c974b5e3b16f5e95422061385ae34ac/src/ktn_date.erl
erlang
@doc Returns the current date in a human readable format binary.
ktn_date : functions useful for handling dates and time values -module(ktn_date). -export([ now_human_readable/0 ]). -type date() :: {date, {non_neg_integer(), 1..12, 1..31}}. -type datetime() :: { datetime , {{integer(), 1..12, 1..31} , {1..24, 1..60, 1..60}} }. -export_type( [ date/0 , datetime/0 ]). -spec now_human_readable() -> binary(). now_human_readable() -> TimeStamp = {_, _, Micro} = os:timestamp(), {{Year, Month, Day}, {Hour, Minute, Second}} = calendar:now_to_universal_time(TimeStamp), DateList = io_lib:format("~p-~2..0B-~2..0BT~p:~p:~p.~6..0wZ", [Year, Month, Day, Hour, Minute, Second, Micro]), list_to_binary(DateList).
1932f99d76bacbce69cedfcc074dc730cef328b00ab7657e2065f7ecc738e3b8
gadfly361/reagent-figwheel
core_cards.cljs
(ns {{ns-name}}.core-cards (:require-macros [devcards.core :as dc]) (:require [{{ns-name}}.pages.home.cards] [{{ns-name}}.pages.about.cards] )) (dc/start-devcard-ui!)
null
https://raw.githubusercontent.com/gadfly361/reagent-figwheel/4c40657b31a2b358be5697add2e96e8cac6f8535/src/leiningen/new/reagent_figwheel/gadfly/src/app/core_cards.cljs
clojure
(ns {{ns-name}}.core-cards (:require-macros [devcards.core :as dc]) (:require [{{ns-name}}.pages.home.cards] [{{ns-name}}.pages.about.cards] )) (dc/start-devcard-ui!)
645a640fde9c0c1dcaaf6f50ddde74ad6c888d5149004f79d914969e7f76d4bc
valderman/haste-compiler
haste-cat.hs
# LANGUAGE OverloadedStrings , TupleSections # module Main where import System.Environment import Haste.Module import Haste.Config import Haste.AST import Haste.AST.PP import Data.Maybe import qualified Data.Map as M import qualified Data.ByteString.Lazy.Char8 as BSL import qualified Data.ByteString.Char8 as BS main = do as <- getArgs if null as then putStrLn "Usage: haste-cat package-id:Module.To.Inspect" else mapM_ printModule as printModule mpkg = do let (pkg, (_:mn)) = break (== ':') mpkg paths = "." : libPaths defaultConfig mods <- mapM (\p -> (p, ) `fmap` readModule p pkg mn) paths case filter (isJust . snd) mods of ((p, Just m):_) -> printDefs p pkg mn m _ -> return () printDefs :: FilePath -> String -> String -> Module -> IO () printDefs path pkg mn m = do putStrLn $ "Package: " ++ pkg putStrLn $ "Module: " ++ mn putStrLn $ "Path: " ++ path putStrLn "---\n" mapM_ printDef $ M.toList $ modDefs m printDef (name, d) = do let cfg = defaultConfig { ppOpts = withPretty . withExtAnnotation $ withAnnotations defaultPPOpts } BS.putStrLn $ niceName name BSL.putStrLn $ pretty cfg d putStrLn "" niceName (Name n (Just (pkg, m))) = BS.concat [pkg, ":", m, ".", n] niceName (Name n _) = n
null
https://raw.githubusercontent.com/valderman/haste-compiler/47d942521570eb4b8b6828b0aa38e1f6b9c3e8a8/src/haste-cat.hs
haskell
# LANGUAGE OverloadedStrings , TupleSections # module Main where import System.Environment import Haste.Module import Haste.Config import Haste.AST import Haste.AST.PP import Data.Maybe import qualified Data.Map as M import qualified Data.ByteString.Lazy.Char8 as BSL import qualified Data.ByteString.Char8 as BS main = do as <- getArgs if null as then putStrLn "Usage: haste-cat package-id:Module.To.Inspect" else mapM_ printModule as printModule mpkg = do let (pkg, (_:mn)) = break (== ':') mpkg paths = "." : libPaths defaultConfig mods <- mapM (\p -> (p, ) `fmap` readModule p pkg mn) paths case filter (isJust . snd) mods of ((p, Just m):_) -> printDefs p pkg mn m _ -> return () printDefs :: FilePath -> String -> String -> Module -> IO () printDefs path pkg mn m = do putStrLn $ "Package: " ++ pkg putStrLn $ "Module: " ++ mn putStrLn $ "Path: " ++ path putStrLn "---\n" mapM_ printDef $ M.toList $ modDefs m printDef (name, d) = do let cfg = defaultConfig { ppOpts = withPretty . withExtAnnotation $ withAnnotations defaultPPOpts } BS.putStrLn $ niceName name BSL.putStrLn $ pretty cfg d putStrLn "" niceName (Name n (Just (pkg, m))) = BS.concat [pkg, ":", m, ".", n] niceName (Name n _) = n
300c0037993176e43fce4c7f9490a17920bd37708b654b5e01369cb2b7125b55
mransan/raft
raft_log.ml
type log_entry = { index : int; term : int; data : bytes; id : string; } let pp_log_entry fmt {index; term; id; _} = Format.fprintf fmt "{index: %i; term: %i, id: %s}" index term id module IntMap = Map.Make(struct type t = int let compare (x:int) (y:int) = Pervasives.compare x y end) type size = | Number of int | Bytes of int * int let add size sum log_entry = match size with | Number _ -> (sum + 1) | Bytes (_, overhead) -> let {data; id; _} = log_entry in sum + overhead + 16 (* 2x64bits for index/term *) + (String.length id) + (Bytes.length data) let has_reach_max size sum = match size with | Number n -> sum >= n | Bytes (b,_) -> sum >= b type max_log_size = { upper_bound : int; lower_bound : int; } type t = { recent_entries : log_entry IntMap.t; max_log_size : max_log_size; } type log_diff = { added_logs : log_entry list; deleted_logs : log_entry list; } let empty_diff = { added_logs = []; deleted_logs = [] } let empty max_log_size = { recent_entries = IntMap.empty; max_log_size; } let last_log_index_and_term {recent_entries; _ } = match IntMap.max_binding recent_entries with | (_ , {index;term; _}) -> (index, term) | exception Not_found -> (0, 0) let last_log_index {recent_entries; _} = match IntMap.max_binding recent_entries with | (_ , {index; _}) -> index | exception Not_found -> 0 exception Done of (log_entry list * int) let log_entries_since ~since ~max log = let {recent_entries ; _} = log in if recent_entries = IntMap.empty then ([], 0) TODO questionable , shoudl all cases go to the sub function else let _, prev, sub = IntMap.split since recent_entries in let prev_term = match prev with | None -> assert (since = 0); 0 | Some {term; _} -> term in let log_entries, _ = try IntMap.fold (fun _ log_entry (log_entries, sum) -> let sum' = add max sum log_entry in if has_reach_max max sum' then raise (Done (log_entries, sum)) else (log_entry :: log_entries, sum') ) sub ([], 0) with | Done x -> x in (List.rev log_entries, prev_term) let sub , _ , _ = IntMap.split ( since + max + 1 ) sub in ( List.map snd ( IntMap.bindings sub ) , prev_term ) (List.map snd (IntMap.bindings sub), prev_term) *) Enforce that the size of the recent_entries stays within the * max log size configuration * max log size configuration *) let truncate add_size ({recent_entries; max_log_size; _} as t) = let {upper_bound; lower_bound} = max_log_size in match IntMap.min_binding recent_entries with | exception Not_found -> t (* when empty, no need for size limitation *) | (lower_index, _) -> let (upper_index, _) = IntMap.max_binding recent_entries in let size = upper_index - lower_index + 1 in if size + add_size > upper_bound then let over = size - lower_bound in let lower_index = lower_index + over + add_size - 1 in let _, _, recent_entries = IntMap.split lower_index recent_entries in {t with recent_entries} else t let add_log_datas current_term datas log = let log = truncate (List.length datas) log in let rec aux term last_log_index recent_entries added_logs = function | [] -> (recent_entries, (List.rev added_logs)) | (data, id)::tl -> let last_log_index = last_log_index + 1 in let new_log_entry = { index = last_log_index; term; data; id; } in let added_logs = new_log_entry :: added_logs in let recent_entries = IntMap.add last_log_index new_log_entry recent_entries in aux term last_log_index recent_entries added_logs tl in let term = current_term in let last_log_index = last_log_index log in let recent_entries = log.recent_entries in let recent_entries, added_logs = aux term last_log_index recent_entries [] datas in let log_diff = { deleted_logs = []; added_logs; } in ({log with recent_entries}, log_diff) let add_log_entries ~log_entries log = let log = truncate (List.length log_entries) log in let rec aux recent_entries = function | [] -> {log with recent_entries} | hd::tl -> let recent_entries = IntMap.add hd.index hd recent_entries in aux recent_entries tl in let log_diff = { added_logs = log_entries; deleted_logs = []; } in (aux log.recent_entries log_entries, log_diff) let remove_log_since ~prev_log_index ~prev_log_term log = let {recent_entries; max_log_size = _ } = log in if prev_log_index > (last_log_index log) then raise Not_found else let before, e, after = IntMap.split prev_log_index recent_entries in let recent_entries, deleted_logs_map = match e with | None -> if prev_log_index = 0 then (before, after) else raise Not_found | Some ({term; index; _} as log_entry) -> if term = prev_log_term then (IntMap.add index log_entry before, after) else raise Not_found in let deleted_logs = List.map snd @@ IntMap.bindings deleted_logs_map in ( {log with recent_entries;}, {deleted_logs; added_logs = []} ) let merge_diff lhs rhs = match lhs, rhs with | {added_logs = []; deleted_logs = []}, rhs -> rhs | lhs, {added_logs = []; deleted_logs = []} -> lhs | {added_logs; deleted_logs = []}, {added_logs = []; deleted_logs} | {added_logs = []; deleted_logs}, {added_logs; deleted_logs = []} -> {added_logs; deleted_logs} | _ -> assert(false) module Builder = struct type builder = t let make max_log_size = empty max_log_size let add_log_entry log log_entry = let log = truncate 1 log in (* assert(log_entry.index > (last_log_index log)); *) { log with recent_entries = IntMap.add log_entry.index log_entry log.recent_entries; } let to_log x = x end (* Builder *)
null
https://raw.githubusercontent.com/mransan/raft/292f99475183d67e960b3a199ed4fc01b1f183e2/src/raft_log.ml
ocaml
2x64bits for index/term when empty, no need for size limitation assert(log_entry.index > (last_log_index log)); Builder
type log_entry = { index : int; term : int; data : bytes; id : string; } let pp_log_entry fmt {index; term; id; _} = Format.fprintf fmt "{index: %i; term: %i, id: %s}" index term id module IntMap = Map.Make(struct type t = int let compare (x:int) (y:int) = Pervasives.compare x y end) type size = | Number of int | Bytes of int * int let add size sum log_entry = match size with | Number _ -> (sum + 1) | Bytes (_, overhead) -> let {data; id; _} = log_entry in + (String.length id) + (Bytes.length data) let has_reach_max size sum = match size with | Number n -> sum >= n | Bytes (b,_) -> sum >= b type max_log_size = { upper_bound : int; lower_bound : int; } type t = { recent_entries : log_entry IntMap.t; max_log_size : max_log_size; } type log_diff = { added_logs : log_entry list; deleted_logs : log_entry list; } let empty_diff = { added_logs = []; deleted_logs = [] } let empty max_log_size = { recent_entries = IntMap.empty; max_log_size; } let last_log_index_and_term {recent_entries; _ } = match IntMap.max_binding recent_entries with | (_ , {index;term; _}) -> (index, term) | exception Not_found -> (0, 0) let last_log_index {recent_entries; _} = match IntMap.max_binding recent_entries with | (_ , {index; _}) -> index | exception Not_found -> 0 exception Done of (log_entry list * int) let log_entries_since ~since ~max log = let {recent_entries ; _} = log in if recent_entries = IntMap.empty then ([], 0) TODO questionable , shoudl all cases go to the sub function else let _, prev, sub = IntMap.split since recent_entries in let prev_term = match prev with | None -> assert (since = 0); 0 | Some {term; _} -> term in let log_entries, _ = try IntMap.fold (fun _ log_entry (log_entries, sum) -> let sum' = add max sum log_entry in if has_reach_max max sum' then raise (Done (log_entries, sum)) else (log_entry :: log_entries, sum') ) sub ([], 0) with | Done x -> x in (List.rev log_entries, prev_term) let sub , _ , _ = IntMap.split ( since + max + 1 ) sub in ( List.map snd ( IntMap.bindings sub ) , prev_term ) (List.map snd (IntMap.bindings sub), prev_term) *) Enforce that the size of the recent_entries stays within the * max log size configuration * max log size configuration *) let truncate add_size ({recent_entries; max_log_size; _} as t) = let {upper_bound; lower_bound} = max_log_size in match IntMap.min_binding recent_entries with | exception Not_found -> t | (lower_index, _) -> let (upper_index, _) = IntMap.max_binding recent_entries in let size = upper_index - lower_index + 1 in if size + add_size > upper_bound then let over = size - lower_bound in let lower_index = lower_index + over + add_size - 1 in let _, _, recent_entries = IntMap.split lower_index recent_entries in {t with recent_entries} else t let add_log_datas current_term datas log = let log = truncate (List.length datas) log in let rec aux term last_log_index recent_entries added_logs = function | [] -> (recent_entries, (List.rev added_logs)) | (data, id)::tl -> let last_log_index = last_log_index + 1 in let new_log_entry = { index = last_log_index; term; data; id; } in let added_logs = new_log_entry :: added_logs in let recent_entries = IntMap.add last_log_index new_log_entry recent_entries in aux term last_log_index recent_entries added_logs tl in let term = current_term in let last_log_index = last_log_index log in let recent_entries = log.recent_entries in let recent_entries, added_logs = aux term last_log_index recent_entries [] datas in let log_diff = { deleted_logs = []; added_logs; } in ({log with recent_entries}, log_diff) let add_log_entries ~log_entries log = let log = truncate (List.length log_entries) log in let rec aux recent_entries = function | [] -> {log with recent_entries} | hd::tl -> let recent_entries = IntMap.add hd.index hd recent_entries in aux recent_entries tl in let log_diff = { added_logs = log_entries; deleted_logs = []; } in (aux log.recent_entries log_entries, log_diff) let remove_log_since ~prev_log_index ~prev_log_term log = let {recent_entries; max_log_size = _ } = log in if prev_log_index > (last_log_index log) then raise Not_found else let before, e, after = IntMap.split prev_log_index recent_entries in let recent_entries, deleted_logs_map = match e with | None -> if prev_log_index = 0 then (before, after) else raise Not_found | Some ({term; index; _} as log_entry) -> if term = prev_log_term then (IntMap.add index log_entry before, after) else raise Not_found in let deleted_logs = List.map snd @@ IntMap.bindings deleted_logs_map in ( {log with recent_entries;}, {deleted_logs; added_logs = []} ) let merge_diff lhs rhs = match lhs, rhs with | {added_logs = []; deleted_logs = []}, rhs -> rhs | lhs, {added_logs = []; deleted_logs = []} -> lhs | {added_logs; deleted_logs = []}, {added_logs = []; deleted_logs} | {added_logs = []; deleted_logs}, {added_logs; deleted_logs = []} -> {added_logs; deleted_logs} | _ -> assert(false) module Builder = struct type builder = t let make max_log_size = empty max_log_size let add_log_entry log log_entry = let log = truncate 1 log in { log with recent_entries = IntMap.add log_entry.index log_entry log.recent_entries; } let to_log x = x
23d4765598ff986790633e03508bc37d75c9c40357d6343b17790541960296c5
lemmih/lhc
Exceptions.hs
module Data.Bedrock.Exceptions ( runGen , cpsTransformation , stdContinuation , isCatchFrame ) where import Control.Applicative (pure, (<$>), (<*>)) import Control.Monad.State import Data.Map (Map) import qualified Data.Map as Map import Data . Bedrock . PrettyPrint ( pretty ) import Data.Bedrock import Data.Bedrock.Transform import qualified LLVM.AST as LLVM (Type (..)) import LLVM.AST.Type as LLVM -- stackFrameName :: Name -- stackFrameName = Name ["bedrock"] "StackFrame" 0 cpsTransformation :: Gen () cpsTransformation = do -- pushNode $ NodeDefinition stackFrameName [] fs <- gets (Map.elems . envFunctions) mapM_ cpsFunction fs cpsFunction :: Function -> Gen () cpsFunction fn | NoCPS `elem` fnAttributes fn = pushFunction fn cpsFunction fn = do let size = frameSize (fnBody fn) frameVar <- newVariable "bedrock.stackframe" FramePtr body <- cpsBlock size Map.empty fn frameVar (fnBody fn) let bodyWithFrame = Bind [] (Alloc size) $ -- Bind [frameVar] (Store (ConstructorName stackFrameName 0) []) $ Bind [frameVar] (ReadRegister "hp") $ Bind [] (BumpHeapPtr size) $ Bind [] (Write frameVar 1 stdContinuation) $ body let fn' = fn{fnArguments = fnArguments fn ++ [stdContinuation] ,fnResults = [] ,fnBody = if size > 0 then bodyWithFrame else body} pushFunction fn' cpsBlock :: NodeSize -> StackLayout -> Function -> Variable -> Block -> Gen Block cpsBlock size slots origin frameVar block = case block of Bind binds simple rest -> cpsExpression size slots origin frameVar binds simple rest Return args -> do node <- newVariable "returnAddr" IWord let fn_size = case fnResults origin of [StaticNode n] -> n _ -> length args -- We need to invoke with at least 1+'size' arguments. -- 'node' is repeated here. Could be Undefined as well. Doesn't matter. return $ Bind [node] (Load stdContinuation 0) $ Invoke node (stdContinuation : take fn_size (args ++ repeat node)) Case scrut defaultBranch alternatives -> Case scrut <$> maybe (return Nothing) (fmap Just . cpsBlock size slots origin frameVar) defaultBranch <*> mapM (cpsAlternative size slots origin frameVar) alternatives -- Raise exception -> do -- node <- newVariable "contNode" Node -- return $ -- Bind [node] (Fetch (stdContinuation size)) $ -- InvokeHandler node exception TailCall fn args -> do noCPS <- hasAttribute fn NoCPS if noCPS then pure $ TailCall fn args else pure $ TailCall fn (args ++ [stdContinuation]) other -> return other exhFrameIdentifier :: String exhFrameIdentifier = "CatchFrame" isCatchFrame :: Name -> Bool isCatchFrame (Name [] ident _) = exhFrameIdentifier == ident isCatchFrame _ = False data StackSlot = SlotPrimitive | SlotPointer deriving (Eq) type StackLayout = Map Int StackSlot cpsExpression :: NodeSize -> StackLayout -> Function -> Variable -> [Variable] -> Expression -> Block -> Gen Block cpsExpression size slots origin frameVar binds simple rest = case simple of Catch exh exhArgs fn fnArgs -> do exFrameName <- tagName ("exception_frame") (fnName origin) let exceptionFrame = Variable { variableName = exFrameName , variableType = FramePtr } exSusp = Variable { variableName = Name [] "exSusp" 0 , variableType = Node } exhFrameName <- newName exhFrameIdentifier pushNode $ NodeDefinition exhFrameName [FramePtr, Node] mkContinuation $ \continuationFrame -> Bind [exSusp] (MkNode (FunctionName exh 2) exhArgs) $ Bind [exceptionFrame] (Store (ConstructorName exhFrameName 0) [ continuationFrame , exSusp ]) $ TailCall fn (fnArgs ++ [exceptionFrame]) Application fn fnArgs -> do noCPS <- hasAttribute fn NoCPS if noCPS then return $ Bind binds (Application fn fnArgs) rest else mkContinuation $ \continuationFrame -> TailCall fn (fnArgs ++ [continuationFrame]) Store (FunctionName fn blanks) args -> Bind binds (Store (FunctionName fn (blanks)) args) <$> cpsBlock size slots origin frameVar rest MkNode (FunctionName fn blanks) args -> Bind binds (MkNode (FunctionName fn (blanks)) args) <$> cpsBlock size slots origin frameVar rest Save var n -> Bind binds (Write frameVar n var) <$> let slot = if isPrimitive var then SlotPrimitive else SlotPointer in cpsBlock size (Map.insert n slot slots) origin frameVar rest Restore n -> Bind binds (Load frameVar n) <$> cpsBlock size slots origin frameVar rest other -> Bind binds other <$> cpsBlock size slots origin frameVar rest where mkContinuation use = do fnPtr <- newVariable "fnPtr" (Primitive $ ptr (LLVM.FunctionType LLVM.VoidType [ptr i8] False)) framePtr <- newVariable "bedrock.stackframe.cont" FramePtr contFnName <- tagName "continuation" (fnName origin) body <- cpsBlock size slots origin framePtr $ Bind [stdContinuation] (Load framePtr 1) $ rest let prims = Map.size (Map.filter (\key -> key == SlotPrimitive) slots) ptrs = Map.size (Map.filter (\key -> key == SlotPointer) slots) pushHelper $ Function { fnName = contFnName , fnAttributes = [ Prefix size prims ptrs Nothing ] , fnArguments = framePtr : binds , fnResults = [] , fnBody = body } return $ Bind [fnPtr] (FunctionPointer contFnName) $ Bind [] (Write frameVar 0 fnPtr) $ use frameVar cpsAlternative :: NodeSize -> StackLayout -> Function -> Variable -> Alternative -> Gen Alternative cpsAlternative size slots origin frameVar (Alternative pattern expr) = case pattern of -- NodePat (FunctionName fn n) args -> -- Alternative ( NodePat ( FunctionName fn n ) args ) < $ > size prims ptrs origin frameVar expr _ -> Alternative pattern <$> cpsBlock size slots origin frameVar expr stdContinuation :: Variable stdContinuation = Variable (Name [] "cont" 0) FramePtr frameSize :: Block -> Int frameSize block = case block of Bind _ Application{} rest -> max 2 (frameSize rest) Bind _ (Restore n) rest -> max (n+1) (frameSize rest) Bind _ _ rest -> frameSize rest Recursive _ rest -> frameSize rest Return{} -> 0 Case _scrut defaultBranch alts -> maximum ((case defaultBranch of Nothing -> 0 Just branch -> frameSize branch) : [ frameSize branch | Alternative _ branch <- alts ]) TailCall{} -> 0 Exit -> 0 _ -> error "Data.Bedrock.Exceptions.frameSize" isPrimitive :: Variable -> Bool isPrimitive var = case variableType var of NodePtr{} -> False Node{} -> False StaticNode{} -> False IWord{} -> True Primitive{} -> True FramePtr -> False
null
https://raw.githubusercontent.com/lemmih/lhc/53bfa57b9b7275b7737dcf9dd620533d0261be66/bedrock/src/Data/Bedrock/Exceptions.hs
haskell
stackFrameName :: Name stackFrameName = Name ["bedrock"] "StackFrame" 0 pushNode $ NodeDefinition stackFrameName [] Bind [frameVar] (Store (ConstructorName stackFrameName 0) []) $ We need to invoke with at least 1+'size' arguments. 'node' is repeated here. Could be Undefined as well. Doesn't matter. Raise exception -> do node <- newVariable "contNode" Node return $ Bind [node] (Fetch (stdContinuation size)) $ InvokeHandler node exception NodePat (FunctionName fn n) args -> Alternative
module Data.Bedrock.Exceptions ( runGen , cpsTransformation , stdContinuation , isCatchFrame ) where import Control.Applicative (pure, (<$>), (<*>)) import Control.Monad.State import Data.Map (Map) import qualified Data.Map as Map import Data . Bedrock . PrettyPrint ( pretty ) import Data.Bedrock import Data.Bedrock.Transform import qualified LLVM.AST as LLVM (Type (..)) import LLVM.AST.Type as LLVM cpsTransformation :: Gen () cpsTransformation = do fs <- gets (Map.elems . envFunctions) mapM_ cpsFunction fs cpsFunction :: Function -> Gen () cpsFunction fn | NoCPS `elem` fnAttributes fn = pushFunction fn cpsFunction fn = do let size = frameSize (fnBody fn) frameVar <- newVariable "bedrock.stackframe" FramePtr body <- cpsBlock size Map.empty fn frameVar (fnBody fn) let bodyWithFrame = Bind [] (Alloc size) $ Bind [frameVar] (ReadRegister "hp") $ Bind [] (BumpHeapPtr size) $ Bind [] (Write frameVar 1 stdContinuation) $ body let fn' = fn{fnArguments = fnArguments fn ++ [stdContinuation] ,fnResults = [] ,fnBody = if size > 0 then bodyWithFrame else body} pushFunction fn' cpsBlock :: NodeSize -> StackLayout -> Function -> Variable -> Block -> Gen Block cpsBlock size slots origin frameVar block = case block of Bind binds simple rest -> cpsExpression size slots origin frameVar binds simple rest Return args -> do node <- newVariable "returnAddr" IWord let fn_size = case fnResults origin of [StaticNode n] -> n _ -> length args return $ Bind [node] (Load stdContinuation 0) $ Invoke node (stdContinuation : take fn_size (args ++ repeat node)) Case scrut defaultBranch alternatives -> Case scrut <$> maybe (return Nothing) (fmap Just . cpsBlock size slots origin frameVar) defaultBranch <*> mapM (cpsAlternative size slots origin frameVar) alternatives TailCall fn args -> do noCPS <- hasAttribute fn NoCPS if noCPS then pure $ TailCall fn args else pure $ TailCall fn (args ++ [stdContinuation]) other -> return other exhFrameIdentifier :: String exhFrameIdentifier = "CatchFrame" isCatchFrame :: Name -> Bool isCatchFrame (Name [] ident _) = exhFrameIdentifier == ident isCatchFrame _ = False data StackSlot = SlotPrimitive | SlotPointer deriving (Eq) type StackLayout = Map Int StackSlot cpsExpression :: NodeSize -> StackLayout -> Function -> Variable -> [Variable] -> Expression -> Block -> Gen Block cpsExpression size slots origin frameVar binds simple rest = case simple of Catch exh exhArgs fn fnArgs -> do exFrameName <- tagName ("exception_frame") (fnName origin) let exceptionFrame = Variable { variableName = exFrameName , variableType = FramePtr } exSusp = Variable { variableName = Name [] "exSusp" 0 , variableType = Node } exhFrameName <- newName exhFrameIdentifier pushNode $ NodeDefinition exhFrameName [FramePtr, Node] mkContinuation $ \continuationFrame -> Bind [exSusp] (MkNode (FunctionName exh 2) exhArgs) $ Bind [exceptionFrame] (Store (ConstructorName exhFrameName 0) [ continuationFrame , exSusp ]) $ TailCall fn (fnArgs ++ [exceptionFrame]) Application fn fnArgs -> do noCPS <- hasAttribute fn NoCPS if noCPS then return $ Bind binds (Application fn fnArgs) rest else mkContinuation $ \continuationFrame -> TailCall fn (fnArgs ++ [continuationFrame]) Store (FunctionName fn blanks) args -> Bind binds (Store (FunctionName fn (blanks)) args) <$> cpsBlock size slots origin frameVar rest MkNode (FunctionName fn blanks) args -> Bind binds (MkNode (FunctionName fn (blanks)) args) <$> cpsBlock size slots origin frameVar rest Save var n -> Bind binds (Write frameVar n var) <$> let slot = if isPrimitive var then SlotPrimitive else SlotPointer in cpsBlock size (Map.insert n slot slots) origin frameVar rest Restore n -> Bind binds (Load frameVar n) <$> cpsBlock size slots origin frameVar rest other -> Bind binds other <$> cpsBlock size slots origin frameVar rest where mkContinuation use = do fnPtr <- newVariable "fnPtr" (Primitive $ ptr (LLVM.FunctionType LLVM.VoidType [ptr i8] False)) framePtr <- newVariable "bedrock.stackframe.cont" FramePtr contFnName <- tagName "continuation" (fnName origin) body <- cpsBlock size slots origin framePtr $ Bind [stdContinuation] (Load framePtr 1) $ rest let prims = Map.size (Map.filter (\key -> key == SlotPrimitive) slots) ptrs = Map.size (Map.filter (\key -> key == SlotPointer) slots) pushHelper $ Function { fnName = contFnName , fnAttributes = [ Prefix size prims ptrs Nothing ] , fnArguments = framePtr : binds , fnResults = [] , fnBody = body } return $ Bind [fnPtr] (FunctionPointer contFnName) $ Bind [] (Write frameVar 0 fnPtr) $ use frameVar cpsAlternative :: NodeSize -> StackLayout -> Function -> Variable -> Alternative -> Gen Alternative cpsAlternative size slots origin frameVar (Alternative pattern expr) = case pattern of ( NodePat ( FunctionName fn n ) args ) < $ > size prims ptrs origin frameVar expr _ -> Alternative pattern <$> cpsBlock size slots origin frameVar expr stdContinuation :: Variable stdContinuation = Variable (Name [] "cont" 0) FramePtr frameSize :: Block -> Int frameSize block = case block of Bind _ Application{} rest -> max 2 (frameSize rest) Bind _ (Restore n) rest -> max (n+1) (frameSize rest) Bind _ _ rest -> frameSize rest Recursive _ rest -> frameSize rest Return{} -> 0 Case _scrut defaultBranch alts -> maximum ((case defaultBranch of Nothing -> 0 Just branch -> frameSize branch) : [ frameSize branch | Alternative _ branch <- alts ]) TailCall{} -> 0 Exit -> 0 _ -> error "Data.Bedrock.Exceptions.frameSize" isPrimitive :: Variable -> Bool isPrimitive var = case variableType var of NodePtr{} -> False Node{} -> False StaticNode{} -> False IWord{} -> True Primitive{} -> True FramePtr -> False
abec49490fe39897e39d031297ba0ccbc40d788434692a50c4911455dff07592
c-cube/ocaml-containers
CCSexp_intf.ml
type 'a or_error = ('a, string) result type 'a iter = ('a -> unit) -> unit type 'a gen = unit -> 'a option * { 2 Abstract representation of S - expressions } @since 3.3 @since 3.3 *) module type BASIC_SEXP = sig type t val atom : string -> t val list : t list -> t val match_ : t -> atom:(string -> 'a) -> list:(t list -> 'a) -> 'a end * { 2 Abstract representation of S - expressions ( extended ) } @since 2.7 @since 2.7 *) module type SEXP = sig include BASIC_SEXP type loc val make_loc : (int * int -> int * int -> string -> loc) option (** If provided, builds a location from a pair of [(line,column)] positions, and a (possibly dummy) filename *) val atom_with_loc : loc:loc -> string -> t val list_with_loc : loc:loc -> t list -> t end * { 2 Operations over S - expressions } @since 2.7 @since 2.7 *) module type S0 = sig type t type sexp = t * { 2 Re - exports } val atom : string -> t * Make an atom out of this string . @since 2.8 @since 2.8 *) val list : t list -> t * Make a Sexpr of this list . @since 2.8 @since 2.8 *) (** {2 Constructors} *) val of_int : int -> t val of_bool : bool -> t val of_list : t list -> t val of_rev_list : t list -> t (** Reverse the list. *) val of_float : float -> t val of_unit : t val of_pair : t * t -> t val of_triple : t * t * t -> t val of_quad : t * t * t * t -> t val of_variant : string -> t list -> t (** [of_variant name args] is used to encode algebraic variants into a S-expr. For instance [of_variant "some" [of_int 1]] represents the value [Some 1]. *) val of_field : string -> t -> t * Used to represent one record field . val of_record : (string * t) list -> t (** Represent a record by its named fields. *) * { 2 Printing } val to_buf : Buffer.t -> t -> unit val to_string : t -> string val to_file : string -> t -> unit val to_file_iter : string -> t iter -> unit (** Print the given iter of expressions to a file. *) val to_chan : out_channel -> t -> unit val pp : Format.formatter -> t -> unit (** Pretty-printer nice on human eyes (including indentation). *) val pp_noindent : Format.formatter -> t -> unit (** Raw, direct printing as compact as possible. *) * { 2 Parsing } val parse_string : string -> t or_error * a string . val parse_string_list : string -> t list or_error * a string into a list of S - exprs . @since 2.8 @since 2.8 *) val parse_chan : in_channel -> t or_error * a S - expression from the given channel . Can read more data than necessary , so do n't use this if you need finer - grained control ( e.g. to read something else { b after } the S - exp ) . necessary, so don't use this if you need finer-grained control (e.g. to read something else {b after} the S-exp). *) val parse_chan_gen : in_channel -> t or_error gen * a channel into a generator of S - expressions . val parse_chan_list : in_channel -> t list or_error val parse_file : string -> t or_error (** Open the file and read a S-exp from it. *) val parse_file_list : string -> t list or_error (** Open the file and read a S-exp from it. *) end * { 2 Operations over S - expressions ( extended ) } @since 2.7 @since 2.7 *) module type S = sig include S0 type loc * Locations for the S - expressions . @since 3.3 @since 3.3 *) * { 2 Parsing } (** A parser of ['a] can return [Yield x] when it parsed a value, or [Fail e] when a parse error was encountered, or [End] if the input was empty. *) type 'a parse_result = Yield of 'a | Fail of string | End module Decoder : sig type t (** Decoder *) val of_lexbuf : Lexing.lexbuf -> t val next : t -> sexp parse_result * the next S - expression or return an error if the input is n't long enough or is n't a proper S - expression . long enough or isn't a proper S-expression. *) val to_list : t -> sexp list or_error * Read all the values from this decoder . @since 2.8 @since 2.8 *) val last_loc : t -> loc option * Last location for the decoder . In particular , after calling { ! next } , this gives the location of the last token used in the result , which is useful in case of error . @since 3.3 after calling {!next}, this gives the location of the last token used in the result, which is useful in case of error. @since 3.3 *) end end
null
https://raw.githubusercontent.com/c-cube/ocaml-containers/69f2805f1073c4ebd1063bbd58380d17e62f6324/src/core/CCSexp_intf.ml
ocaml
* If provided, builds a location from a pair of [(line,column)] positions, and a (possibly dummy) filename * {2 Constructors} * Reverse the list. * [of_variant name args] is used to encode algebraic variants into a S-expr. For instance [of_variant "some" [of_int 1]] represents the value [Some 1]. * Represent a record by its named fields. * Print the given iter of expressions to a file. * Pretty-printer nice on human eyes (including indentation). * Raw, direct printing as compact as possible. * Open the file and read a S-exp from it. * Open the file and read a S-exp from it. * A parser of ['a] can return [Yield x] when it parsed a value, or [Fail e] when a parse error was encountered, or [End] if the input was empty. * Decoder
type 'a or_error = ('a, string) result type 'a iter = ('a -> unit) -> unit type 'a gen = unit -> 'a option * { 2 Abstract representation of S - expressions } @since 3.3 @since 3.3 *) module type BASIC_SEXP = sig type t val atom : string -> t val list : t list -> t val match_ : t -> atom:(string -> 'a) -> list:(t list -> 'a) -> 'a end * { 2 Abstract representation of S - expressions ( extended ) } @since 2.7 @since 2.7 *) module type SEXP = sig include BASIC_SEXP type loc val make_loc : (int * int -> int * int -> string -> loc) option val atom_with_loc : loc:loc -> string -> t val list_with_loc : loc:loc -> t list -> t end * { 2 Operations over S - expressions } @since 2.7 @since 2.7 *) module type S0 = sig type t type sexp = t * { 2 Re - exports } val atom : string -> t * Make an atom out of this string . @since 2.8 @since 2.8 *) val list : t list -> t * Make a Sexpr of this list . @since 2.8 @since 2.8 *) val of_int : int -> t val of_bool : bool -> t val of_list : t list -> t val of_rev_list : t list -> t val of_float : float -> t val of_unit : t val of_pair : t * t -> t val of_triple : t * t * t -> t val of_quad : t * t * t * t -> t val of_variant : string -> t list -> t val of_field : string -> t -> t * Used to represent one record field . val of_record : (string * t) list -> t * { 2 Printing } val to_buf : Buffer.t -> t -> unit val to_string : t -> string val to_file : string -> t -> unit val to_file_iter : string -> t iter -> unit val to_chan : out_channel -> t -> unit val pp : Format.formatter -> t -> unit val pp_noindent : Format.formatter -> t -> unit * { 2 Parsing } val parse_string : string -> t or_error * a string . val parse_string_list : string -> t list or_error * a string into a list of S - exprs . @since 2.8 @since 2.8 *) val parse_chan : in_channel -> t or_error * a S - expression from the given channel . Can read more data than necessary , so do n't use this if you need finer - grained control ( e.g. to read something else { b after } the S - exp ) . necessary, so don't use this if you need finer-grained control (e.g. to read something else {b after} the S-exp). *) val parse_chan_gen : in_channel -> t or_error gen * a channel into a generator of S - expressions . val parse_chan_list : in_channel -> t list or_error val parse_file : string -> t or_error val parse_file_list : string -> t list or_error end * { 2 Operations over S - expressions ( extended ) } @since 2.7 @since 2.7 *) module type S = sig include S0 type loc * Locations for the S - expressions . @since 3.3 @since 3.3 *) * { 2 Parsing } type 'a parse_result = Yield of 'a | Fail of string | End module Decoder : sig type t val of_lexbuf : Lexing.lexbuf -> t val next : t -> sexp parse_result * the next S - expression or return an error if the input is n't long enough or is n't a proper S - expression . long enough or isn't a proper S-expression. *) val to_list : t -> sexp list or_error * Read all the values from this decoder . @since 2.8 @since 2.8 *) val last_loc : t -> loc option * Last location for the decoder . In particular , after calling { ! next } , this gives the location of the last token used in the result , which is useful in case of error . @since 3.3 after calling {!next}, this gives the location of the last token used in the result, which is useful in case of error. @since 3.3 *) end end
8dcb56d641fb834997d0229b6dcd286b52e7a993022b54411a18b3e52f87da2b
emqx/ecpool
ecpool_sup.erl
%%-------------------------------------------------------------------- Copyright ( c ) 2019 EMQ Technologies Co. , Ltd. All Rights Reserved . %% Licensed under the Apache License , Version 2.0 ( the " License " ) ; %% you may not use this file except in compliance with the License. %% You may obtain a copy of the License at %% %% -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(ecpool_sup). -behaviour(supervisor). -export([start_link/0]). %% API -export([ start_pool/3 , stop_pool/1 , get_pool/1 ]). -export([pools/0]). %% Supervisor callbacks -export([init/1]). -type pool_name() :: ecpool:pool_name(). %% @doc Start supervisor. -spec(start_link() -> {ok, pid()} | {error, term()}). start_link() -> supervisor:start_link({local, ?MODULE}, ?MODULE, []). %%-------------------------------------------------------------------- Start / Stop a pool %%-------------------------------------------------------------------- %% @doc Start a pool. -spec(start_pool(pool_name(), atom(), list(tuple())) -> {ok, pid()} | {error, term()}). start_pool(Pool, Mod, Opts) -> supervisor:start_child(?MODULE, pool_spec(Pool, Mod, Opts)). %% @doc Stop a pool. -spec(stop_pool(Pool :: pool_name()) -> ok | {error, term()}). stop_pool(Pool) -> ChildId = child_id(Pool), case supervisor:terminate_child(?MODULE, ChildId) of ok -> supervisor:delete_child(?MODULE, ChildId); {error, Reason} -> {error, Reason} end. %% @doc Get a pool. -spec(get_pool(pool_name()) -> undefined | pid()). get_pool(Pool) -> ChildId = child_id(Pool), case [Pid || {Id, Pid, supervisor, _} <- supervisor:which_children(?MODULE), Id =:= ChildId] of [] -> undefined; L -> hd(L) end. %% @doc Get All Pools supervisored by the ecpool_sup. -spec(pools() -> [{pool_name(), pid()}]). pools() -> [{Pool, Pid} || {{pool_sup, Pool}, Pid, supervisor, _} <- supervisor:which_children(?MODULE)]. %%-------------------------------------------------------------------- %% Supervisor callbacks %%-------------------------------------------------------------------- init([]) -> {ok, { {one_for_one, 10, 100}, []} }. pool_spec(Pool, Mod, Opts) -> #{id => child_id(Pool), start => {ecpool_pool_sup, start_link, [Pool, Mod, Opts]}, restart => transient, shutdown => infinity, type => supervisor, modules => [ecpool_pool_sup]}. child_id(Pool) -> {pool_sup, Pool}.
null
https://raw.githubusercontent.com/emqx/ecpool/d01b8cb99af90bc177eeeabe29075133db878fb3/src/ecpool_sup.erl
erlang
-------------------------------------------------------------------- you may not use this file except in compliance with the License. You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing, software 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. -------------------------------------------------------------------- API Supervisor callbacks @doc Start supervisor. -------------------------------------------------------------------- -------------------------------------------------------------------- @doc Start a pool. @doc Stop a pool. @doc Get a pool. @doc Get All Pools supervisored by the ecpool_sup. -------------------------------------------------------------------- Supervisor callbacks --------------------------------------------------------------------
Copyright ( c ) 2019 EMQ Technologies Co. , Ltd. All Rights Reserved . Licensed under the Apache License , Version 2.0 ( the " License " ) ; distributed under the License is distributed on an " AS IS " BASIS , -module(ecpool_sup). -behaviour(supervisor). -export([start_link/0]). -export([ start_pool/3 , stop_pool/1 , get_pool/1 ]). -export([pools/0]). -export([init/1]). -type pool_name() :: ecpool:pool_name(). -spec(start_link() -> {ok, pid()} | {error, term()}). start_link() -> supervisor:start_link({local, ?MODULE}, ?MODULE, []). Start / Stop a pool -spec(start_pool(pool_name(), atom(), list(tuple())) -> {ok, pid()} | {error, term()}). start_pool(Pool, Mod, Opts) -> supervisor:start_child(?MODULE, pool_spec(Pool, Mod, Opts)). -spec(stop_pool(Pool :: pool_name()) -> ok | {error, term()}). stop_pool(Pool) -> ChildId = child_id(Pool), case supervisor:terminate_child(?MODULE, ChildId) of ok -> supervisor:delete_child(?MODULE, ChildId); {error, Reason} -> {error, Reason} end. -spec(get_pool(pool_name()) -> undefined | pid()). get_pool(Pool) -> ChildId = child_id(Pool), case [Pid || {Id, Pid, supervisor, _} <- supervisor:which_children(?MODULE), Id =:= ChildId] of [] -> undefined; L -> hd(L) end. -spec(pools() -> [{pool_name(), pid()}]). pools() -> [{Pool, Pid} || {{pool_sup, Pool}, Pid, supervisor, _} <- supervisor:which_children(?MODULE)]. init([]) -> {ok, { {one_for_one, 10, 100}, []} }. pool_spec(Pool, Mod, Opts) -> #{id => child_id(Pool), start => {ecpool_pool_sup, start_link, [Pool, Mod, Opts]}, restart => transient, shutdown => infinity, type => supervisor, modules => [ecpool_pool_sup]}. child_id(Pool) -> {pool_sup, Pool}.
54ad62f1a63a5409a64131dac6119e45b5841d6cf533e59f14fb31a26986dc9b
5HT/ant
FontTFM.ml
open XNum; open Substitute; open GlyphMetric; open FontMetric; module LigKern = struct type lig_kern_cmd = [ LigCmd of int and int and int and int | KernCmd of int and int and num ]; (* access methods *) value is_lig lk = match lk with [ LigCmd _ _ _ _ -> True | KernCmd _ _ _ -> False ]; value is_kern lk = match lk with [ LigCmd _ _ _ _ -> False | KernCmd _ _ _ -> True ]; value skip lk = match lk with [ LigCmd s _ _ _ -> s | KernCmd s _ _ -> s ]; value next lk = match lk with [ LigCmd _ n _ _ -> n | KernCmd _ n _ -> n ]; value operand lk = match lk with [ LigCmd _ _ o _ -> o | KernCmd _ _ _ -> raise (Invalid_argument "LigKern.operand applied to kern!") ]; value remainder lk = match lk with [ LigCmd _ _ _ r -> r | KernCmd _ _ _ -> raise (Invalid_argument "LigKern.remainder applied to kern!") ]; value kern lk = match lk with [ LigCmd _ _ _ _ -> raise (Invalid_argument "LigKern.kern applied to ligature!") | KernCmd _ _ k -> k ]; (* |next_lig_kern| can be used to enumerate all lig-kern pairs. *) value next_lig_kern lk_array pos = do { let lk = lk_array.(pos); let s = skip lk; let n = next lk; let next_pos = if s < 128 then pos + s + 1 else -1; if s <= 128 then do { if is_lig lk then do { let op = operand lk; (next_pos, n, GlyphMetric.Ligature (remainder lk) (op lsr 2) ((op lsr 1) land 1 = 1) (op land 1 = 1)) } else (next_pos, n, GlyphMetric.Kern (kern lk)) } else (-1, -1, NoLigKern) }; Determines the ligature or kerning of two characterpos . lk_array is the array of commands , pos the position corresponding to the current character , and next_char the next character . Determines the ligature or kerning of two characterpos. lk_array is the array of LigKern commands, pos the position corresponding to the current character, and next_char the next character. *) value rec get_lig_kern lk_array pos next_char = do { let lk = lk_array.(pos); let s = skip lk; let n = next lk; if (n = next_char) && (s <= 128) then if is_lig lk then do { let op = operand lk; GlyphMetric.Ligature (remainder lk) (op lsr 2) ((op lsr 1) land 1 = 1) (op land 1 = 1) } else GlyphMetric.Kern (kern lk) else if s < 128 then get_lig_kern lk_array (pos + s + 1) next_char else NoLigKern }; value rec list_lig_kerns lk_array pos = do { let lk = lk_array.(pos); let s = skip lk; let n = next lk; if s > 128 then [] else if is_lig lk then do { let op = operand lk; let l = (n, GlyphMetric.Ligature (remainder lk) (op lsr 2) ((op lsr 1) land 1 = 1) (op land 1 = 1)); if s < 128 then [l :: list_lig_kerns lk_array (pos + s + 1)] else [l] } else do { let k = (n, GlyphMetric.Kern (kern lk)); if s < 128 then [k :: list_lig_kerns lk_array (pos + s + 1)] else [k] } }; end; value num_0x100 = num_of_int 0x100; value num_0x10000 = num_of_int 0x10000; value num_0x100000 = num_of_int 0x100000; value num_0x1000000 = num_of_int 0x1000000; value read_fix ic = IO.read_be_i32 ic // num_0x100000; value read_4 ic = do { let x1 = IO.read_be_u8 ic; let x2 = IO.read_be_u8 ic; let x3 = IO.read_be_u8 ic; let x4 = IO.read_be_u8 ic; (x1, x2, x3, x4) }; value read_array ic read_fun len = do { if len <= 0 then [| |] else do { let a = Array.make len (read_fun ic); for i = 1 to len - 1 do { a.(i) := read_fun ic }; a } }; value tfm_kerning lig_kern font c1 c2 = do { match (get_glyph_metric font (Simple c1)).gm_extra with [ GXI_LigKern lk -> LigKern.get_lig_kern lig_kern lk c2 | _ -> NoLigKern ]; }; value get_adjustment_tables lig_kern_table glyphs first_glyph last_glyph = do { iter first_glyph DynUCTrie.empty DynUCTrie.empty where rec iter g pos subst = do { if g > last_glyph then (if DynUCTrie.is_empty pos then [] else [Substitute.DirectLookup pos], if DynUCTrie.is_empty subst then [] else [Substitute.DirectLookup subst]) else match glyphs.(g - first_glyph).gm_extra with [ GXI_LigKern lk -> do { let lks = LigKern.list_lig_kerns lig_kern_table lk; add_lig_kern lks pos subst where rec add_lig_kern lks pos subst = match lks with [ [] -> iter (g+1) pos subst | [l::lks] -> match l with [ (g2, GlyphMetric.Ligature c s k1 k2) -> do { add_lig_kern lks pos (DynUCTrie.add_list [g; g2] (tex_ligature_cmd (Simple c) k1 k2, s) subst) } | (g2, GlyphMetric.Kern x) -> do { add_lig_kern lks (DynUCTrie.add_list [g; g2] (simple_pair_kerning_cmd x, 1) pos) subst } | (_, NoLigKern) -> assert False ] ] } | _ -> iter (g+1) pos subst ] } }; value get_glyph_bitmap bitmaps fm code = do { if !bitmaps = None then do { match FontPK.read_pk_font fm !default_bitmap_resolution with [ None -> () | Some (_, gs) -> !bitmaps := Some gs ] } else (); match !bitmaps with [ None -> GlyphBitmap.empty_glyph | Some bm -> bm.(code - fm.first_glyph) ] }; value make_lig_kern kern (x1,x2,x3,x4) = do { if x3 < 128 then LigKern.LigCmd x1 x2 x3 x4 else LigKern.KernCmd x1 x2 kern.(0x100 * (x3 - 128) + x4) }; value make_glyph_metric glyph_idx letter_spacing extra_kern size width height depth italic lig exten (w,x1,x2,r) = do { let h = x1 lsr 4; let d = x1 land 0xf; let i = x2 lsr 2; let t = x2 land 0x3; let user_kern_info = try let ki = List.assoc glyph_idx extra_kern; { ki_after_space = size */ ki.ki_after_space; ki_before_space = size */ ki.ki_before_space; ki_after_margin = size */ ki.ki_after_margin; ki_before_margin = size */ ki.ki_before_margin; ki_after_foreign = size */ ki.ki_after_foreign; ki_before_foreign = size */ ki.ki_before_foreign } with [ Not_found -> zero_kern_info ]; (* If italic.(i) = 0 then we do not need to allocate a new structure. *) let kern_info = if italic.(i) <>/ num_zero then { (user_kern_info) with ki_before_foreign = italic.(i) +/ user_kern_info.ki_before_foreign } else user_kern_info; let extra = match t with [ 0 -> GXI_Normal | 1 -> let lk = lig.(r) in GXI_LigKern (if LigKern.is_lig lk && LigKern.skip lk > 128 then 256 * LigKern.operand lk + LigKern.remainder lk else r) | 2 -> GXI_List r | _ -> let (t,m,b,r) = exten.(r) in GXI_Extendable t m b r ]; { gm_width = width.(w) +/ num_two */ size */ letter_spacing; gm_height = height.(h); gm_depth = depth.(d); gm_italic = italic.(i); gm_extra = extra; gm_extra_kern = kern_info } }; value tfm_composer pos subst fm _ _ = do { let (p_trie, p_state) = make_adjustment_trie pos; let (s_trie, s_state) = make_adjustment_trie subst; two_phase_composer fm (match_substitution_trie (get_border_glyph fm) s_trie s_state) (match_substitution_trie (get_border_glyph fm) p_trie p_state) }; value read_tfm file name params = do { let ic = IO.make_in_stream file; let _file_length = IO.read_be_u16 ic; let header_length = IO.read_be_u16 ic; let first_glyph = IO.read_be_u16 ic; let last_glyph = IO.read_be_u16 ic; let glyph_metric_table_len = last_glyph - first_glyph + 1; let width_table_len = IO.read_be_u16 ic; let height_table_len = IO.read_be_u16 ic; let depth_table_len = IO.read_be_u16 ic; let italic_table_len = IO.read_be_u16 ic; let lig_table_len = IO.read_be_u16 ic; let kern_table_len = IO.read_be_u16 ic; let ext_table_len = IO.read_be_u16 ic; let param_table_len = IO.read_be_u16 ic; let check_sum = IO.read_be_u32 ic; let design_size = read_fix ic; let size = if params.flp_size >=/ num_zero then params.flp_size else design_size; IO.skip ic (4 * header_length - 8); let glyph_metric = read_array ic read_4 glyph_metric_table_len; let width = Array.map (fun x -> x */ size) (read_array ic read_fix width_table_len); let height = Array.map (fun x -> x */ size) (read_array ic read_fix height_table_len); let depth = Array.map (fun x -> x */ size) (read_array ic read_fix depth_table_len); let italic = Array.map (fun x -> x */ size) (read_array ic read_fix italic_table_len); let lig = read_array ic read_4 lig_table_len; let kern = Array.map (fun x -> x */ size) (read_array ic read_fix kern_table_len); let ext = read_array ic read_4 ext_table_len; let param = read_array ic read_fix param_table_len; let lig_cmds = Array.map (fun x -> make_lig_kern kern x) lig; let (enc,dec) = match params.flp_encoding with [ [| |] -> (Encodings.raw_encoding, Encodings.raw_decoding) | m -> (Encodings.charmap_encoding (Encodings.fake_encoding m), Encodings.array_decoding m) ]; let lookup_char x = match enc x with [ Simple g -> g | _ -> (-1) ]; FIX let extra_kern = List.map (fun (g,k) -> (glyph_spec_to_index lookup_char lookup_name g, k)) params.flp_extra_kern; let gm_table = Array.mapi (fun i gm -> make_glyph_metric (i + first_glyph) params.flp_letter_spacing extra_kern size width height depth italic lig_cmds ext gm) glyph_metric; let (p,s) = get_adjustment_tables lig_cmds gm_table first_glyph last_glyph; let extra_pos = if GlyphSpecTrie.is_empty params.flp_extra_pos then p else [ adjustment_spec_to_table lookup_char lookup_name params.flp_extra_pos :: p]; let pos_table = add_border_kern (last_glyph + 1) (last_glyph + 2) (last_glyph + 3) size extra_kern extra_pos; let subst_table = if GlyphSpecTrie.is_empty params.flp_extra_subst then s else [ adjustment_spec_to_table lookup_char lookup_name params.flp_extra_subst :: s]; let hyphen_glyph = match params.flp_hyphen_glyph with [ Undef -> Simple 45 | h -> h ]; let composer x y = tfm_composer pos_table subst_table x y; { name = name; ps_name = name; file_name = file; font_type = Other; first_glyph = first_glyph; last_glyph = last_glyph; glyph_metric = gm_table; design_size = design_size; at_size = size; check_sum = check_sum; get_glyph = enc; get_unicode = dec; draw_simple_glyph = if params.flp_letter_spacing =/ num_zero then draw_simple_glyph else draw_displaced_simple_glyph (size */ params.flp_letter_spacing) num_zero; accent_base_point = accent_base_point_x_height; accent_attach_point = accent_attach_point_top; get_composer = composer; kerning = tfm_kerning lig_cmds; get_glyph_bitmap = (get_glyph_bitmap (ref None)); get_glyph_name = (fun g -> Printf.sprintf "c%d" g); parameter = { hyphen_glyph = hyphen_glyph; skew_glyph = params.flp_skew_glyph; margin_glyph = Simple (last_glyph + 1); space_glyph = Simple (last_glyph + 2); foreign_glyph = Simple (last_glyph + 3); slant = if param_table_len > 0 then param.( 0) else num_zero; space = if param_table_len > 1 then size */ param.( 1) else num_zero; space_stretch = if param_table_len > 2 then size */ param.( 2) else num_zero; space_shrink = if param_table_len > 3 then size */ param.( 3) else num_zero; x_height = if param_table_len > 4 then size */ param.( 4) else num_zero; quad = if param_table_len > 5 then size */ param.( 5) else design_size; extra_space = if param_table_len > 6 then size */ param.( 6) else num_zero; num_shift_1 = if param_table_len > 7 then size */ param.( 7) else num_zero; num_shift_2 = if param_table_len > 8 then size */ param.( 8) else num_zero; num_shift_3 = if param_table_len > 9 then size */ param.( 9) else num_zero; denom_shift_1 = if param_table_len > 10 then size */ param.(10) else num_zero; denom_shift_2 = if param_table_len > 11 then size */ param.(11) else num_zero; super_shift_1 = if param_table_len > 12 then size */ param.(12) else num_zero; super_shift_2 = if param_table_len > 13 then size */ param.(13) else num_zero; super_shift_3 = if param_table_len > 14 then size */ param.(14) else num_zero; sub_shift_1 = if param_table_len > 15 then size */ param.(15) else num_zero; sub_shift_2 = if param_table_len > 16 then size */ param.(16) else num_zero; super_drop = if param_table_len > 17 then size */ param.(17) else num_zero; sub_drop = if param_table_len > 18 then size */ param.(18) else num_zero; delim_1 = if param_table_len > 19 then size */ param.(19) else num_zero; delim_2 = if param_table_len > 20 then size */ param.(20) else num_zero; axis_height = if param_table_len > 21 then size */ param.(21) else num_zero; rule_thickness = if param_table_len > 7 then size */ param.( 7) else num_zero; big_op_spacing_1 = if param_table_len > 8 then size */ param.( 8) else num_zero; big_op_spacing_2 = if param_table_len > 9 then size */ param.( 9) else num_zero; big_op_spacing_3 = if param_table_len > 10 then size */ param.(10) else num_zero; big_op_spacing_4 = if param_table_len > 11 then size */ param.(11) else num_zero; big_op_spacing_5 = if param_table_len > 12 then size */ param.(12) else num_zero } } };
null
https://raw.githubusercontent.com/5HT/ant/6acf51f4c4ebcc06c52c595776e0293cfa2f1da4/Runtime/FontTFM.ml
ocaml
access methods |next_lig_kern| can be used to enumerate all lig-kern pairs. If italic.(i) = 0 then we do not need to allocate a new structure.
open XNum; open Substitute; open GlyphMetric; open FontMetric; module LigKern = struct type lig_kern_cmd = [ LigCmd of int and int and int and int | KernCmd of int and int and num ]; value is_lig lk = match lk with [ LigCmd _ _ _ _ -> True | KernCmd _ _ _ -> False ]; value is_kern lk = match lk with [ LigCmd _ _ _ _ -> False | KernCmd _ _ _ -> True ]; value skip lk = match lk with [ LigCmd s _ _ _ -> s | KernCmd s _ _ -> s ]; value next lk = match lk with [ LigCmd _ n _ _ -> n | KernCmd _ n _ -> n ]; value operand lk = match lk with [ LigCmd _ _ o _ -> o | KernCmd _ _ _ -> raise (Invalid_argument "LigKern.operand applied to kern!") ]; value remainder lk = match lk with [ LigCmd _ _ _ r -> r | KernCmd _ _ _ -> raise (Invalid_argument "LigKern.remainder applied to kern!") ]; value kern lk = match lk with [ LigCmd _ _ _ _ -> raise (Invalid_argument "LigKern.kern applied to ligature!") | KernCmd _ _ k -> k ]; value next_lig_kern lk_array pos = do { let lk = lk_array.(pos); let s = skip lk; let n = next lk; let next_pos = if s < 128 then pos + s + 1 else -1; if s <= 128 then do { if is_lig lk then do { let op = operand lk; (next_pos, n, GlyphMetric.Ligature (remainder lk) (op lsr 2) ((op lsr 1) land 1 = 1) (op land 1 = 1)) } else (next_pos, n, GlyphMetric.Kern (kern lk)) } else (-1, -1, NoLigKern) }; Determines the ligature or kerning of two characterpos . lk_array is the array of commands , pos the position corresponding to the current character , and next_char the next character . Determines the ligature or kerning of two characterpos. lk_array is the array of LigKern commands, pos the position corresponding to the current character, and next_char the next character. *) value rec get_lig_kern lk_array pos next_char = do { let lk = lk_array.(pos); let s = skip lk; let n = next lk; if (n = next_char) && (s <= 128) then if is_lig lk then do { let op = operand lk; GlyphMetric.Ligature (remainder lk) (op lsr 2) ((op lsr 1) land 1 = 1) (op land 1 = 1) } else GlyphMetric.Kern (kern lk) else if s < 128 then get_lig_kern lk_array (pos + s + 1) next_char else NoLigKern }; value rec list_lig_kerns lk_array pos = do { let lk = lk_array.(pos); let s = skip lk; let n = next lk; if s > 128 then [] else if is_lig lk then do { let op = operand lk; let l = (n, GlyphMetric.Ligature (remainder lk) (op lsr 2) ((op lsr 1) land 1 = 1) (op land 1 = 1)); if s < 128 then [l :: list_lig_kerns lk_array (pos + s + 1)] else [l] } else do { let k = (n, GlyphMetric.Kern (kern lk)); if s < 128 then [k :: list_lig_kerns lk_array (pos + s + 1)] else [k] } }; end; value num_0x100 = num_of_int 0x100; value num_0x10000 = num_of_int 0x10000; value num_0x100000 = num_of_int 0x100000; value num_0x1000000 = num_of_int 0x1000000; value read_fix ic = IO.read_be_i32 ic // num_0x100000; value read_4 ic = do { let x1 = IO.read_be_u8 ic; let x2 = IO.read_be_u8 ic; let x3 = IO.read_be_u8 ic; let x4 = IO.read_be_u8 ic; (x1, x2, x3, x4) }; value read_array ic read_fun len = do { if len <= 0 then [| |] else do { let a = Array.make len (read_fun ic); for i = 1 to len - 1 do { a.(i) := read_fun ic }; a } }; value tfm_kerning lig_kern font c1 c2 = do { match (get_glyph_metric font (Simple c1)).gm_extra with [ GXI_LigKern lk -> LigKern.get_lig_kern lig_kern lk c2 | _ -> NoLigKern ]; }; value get_adjustment_tables lig_kern_table glyphs first_glyph last_glyph = do { iter first_glyph DynUCTrie.empty DynUCTrie.empty where rec iter g pos subst = do { if g > last_glyph then (if DynUCTrie.is_empty pos then [] else [Substitute.DirectLookup pos], if DynUCTrie.is_empty subst then [] else [Substitute.DirectLookup subst]) else match glyphs.(g - first_glyph).gm_extra with [ GXI_LigKern lk -> do { let lks = LigKern.list_lig_kerns lig_kern_table lk; add_lig_kern lks pos subst where rec add_lig_kern lks pos subst = match lks with [ [] -> iter (g+1) pos subst | [l::lks] -> match l with [ (g2, GlyphMetric.Ligature c s k1 k2) -> do { add_lig_kern lks pos (DynUCTrie.add_list [g; g2] (tex_ligature_cmd (Simple c) k1 k2, s) subst) } | (g2, GlyphMetric.Kern x) -> do { add_lig_kern lks (DynUCTrie.add_list [g; g2] (simple_pair_kerning_cmd x, 1) pos) subst } | (_, NoLigKern) -> assert False ] ] } | _ -> iter (g+1) pos subst ] } }; value get_glyph_bitmap bitmaps fm code = do { if !bitmaps = None then do { match FontPK.read_pk_font fm !default_bitmap_resolution with [ None -> () | Some (_, gs) -> !bitmaps := Some gs ] } else (); match !bitmaps with [ None -> GlyphBitmap.empty_glyph | Some bm -> bm.(code - fm.first_glyph) ] }; value make_lig_kern kern (x1,x2,x3,x4) = do { if x3 < 128 then LigKern.LigCmd x1 x2 x3 x4 else LigKern.KernCmd x1 x2 kern.(0x100 * (x3 - 128) + x4) }; value make_glyph_metric glyph_idx letter_spacing extra_kern size width height depth italic lig exten (w,x1,x2,r) = do { let h = x1 lsr 4; let d = x1 land 0xf; let i = x2 lsr 2; let t = x2 land 0x3; let user_kern_info = try let ki = List.assoc glyph_idx extra_kern; { ki_after_space = size */ ki.ki_after_space; ki_before_space = size */ ki.ki_before_space; ki_after_margin = size */ ki.ki_after_margin; ki_before_margin = size */ ki.ki_before_margin; ki_after_foreign = size */ ki.ki_after_foreign; ki_before_foreign = size */ ki.ki_before_foreign } with [ Not_found -> zero_kern_info ]; let kern_info = if italic.(i) <>/ num_zero then { (user_kern_info) with ki_before_foreign = italic.(i) +/ user_kern_info.ki_before_foreign } else user_kern_info; let extra = match t with [ 0 -> GXI_Normal | 1 -> let lk = lig.(r) in GXI_LigKern (if LigKern.is_lig lk && LigKern.skip lk > 128 then 256 * LigKern.operand lk + LigKern.remainder lk else r) | 2 -> GXI_List r | _ -> let (t,m,b,r) = exten.(r) in GXI_Extendable t m b r ]; { gm_width = width.(w) +/ num_two */ size */ letter_spacing; gm_height = height.(h); gm_depth = depth.(d); gm_italic = italic.(i); gm_extra = extra; gm_extra_kern = kern_info } }; value tfm_composer pos subst fm _ _ = do { let (p_trie, p_state) = make_adjustment_trie pos; let (s_trie, s_state) = make_adjustment_trie subst; two_phase_composer fm (match_substitution_trie (get_border_glyph fm) s_trie s_state) (match_substitution_trie (get_border_glyph fm) p_trie p_state) }; value read_tfm file name params = do { let ic = IO.make_in_stream file; let _file_length = IO.read_be_u16 ic; let header_length = IO.read_be_u16 ic; let first_glyph = IO.read_be_u16 ic; let last_glyph = IO.read_be_u16 ic; let glyph_metric_table_len = last_glyph - first_glyph + 1; let width_table_len = IO.read_be_u16 ic; let height_table_len = IO.read_be_u16 ic; let depth_table_len = IO.read_be_u16 ic; let italic_table_len = IO.read_be_u16 ic; let lig_table_len = IO.read_be_u16 ic; let kern_table_len = IO.read_be_u16 ic; let ext_table_len = IO.read_be_u16 ic; let param_table_len = IO.read_be_u16 ic; let check_sum = IO.read_be_u32 ic; let design_size = read_fix ic; let size = if params.flp_size >=/ num_zero then params.flp_size else design_size; IO.skip ic (4 * header_length - 8); let glyph_metric = read_array ic read_4 glyph_metric_table_len; let width = Array.map (fun x -> x */ size) (read_array ic read_fix width_table_len); let height = Array.map (fun x -> x */ size) (read_array ic read_fix height_table_len); let depth = Array.map (fun x -> x */ size) (read_array ic read_fix depth_table_len); let italic = Array.map (fun x -> x */ size) (read_array ic read_fix italic_table_len); let lig = read_array ic read_4 lig_table_len; let kern = Array.map (fun x -> x */ size) (read_array ic read_fix kern_table_len); let ext = read_array ic read_4 ext_table_len; let param = read_array ic read_fix param_table_len; let lig_cmds = Array.map (fun x -> make_lig_kern kern x) lig; let (enc,dec) = match params.flp_encoding with [ [| |] -> (Encodings.raw_encoding, Encodings.raw_decoding) | m -> (Encodings.charmap_encoding (Encodings.fake_encoding m), Encodings.array_decoding m) ]; let lookup_char x = match enc x with [ Simple g -> g | _ -> (-1) ]; FIX let extra_kern = List.map (fun (g,k) -> (glyph_spec_to_index lookup_char lookup_name g, k)) params.flp_extra_kern; let gm_table = Array.mapi (fun i gm -> make_glyph_metric (i + first_glyph) params.flp_letter_spacing extra_kern size width height depth italic lig_cmds ext gm) glyph_metric; let (p,s) = get_adjustment_tables lig_cmds gm_table first_glyph last_glyph; let extra_pos = if GlyphSpecTrie.is_empty params.flp_extra_pos then p else [ adjustment_spec_to_table lookup_char lookup_name params.flp_extra_pos :: p]; let pos_table = add_border_kern (last_glyph + 1) (last_glyph + 2) (last_glyph + 3) size extra_kern extra_pos; let subst_table = if GlyphSpecTrie.is_empty params.flp_extra_subst then s else [ adjustment_spec_to_table lookup_char lookup_name params.flp_extra_subst :: s]; let hyphen_glyph = match params.flp_hyphen_glyph with [ Undef -> Simple 45 | h -> h ]; let composer x y = tfm_composer pos_table subst_table x y; { name = name; ps_name = name; file_name = file; font_type = Other; first_glyph = first_glyph; last_glyph = last_glyph; glyph_metric = gm_table; design_size = design_size; at_size = size; check_sum = check_sum; get_glyph = enc; get_unicode = dec; draw_simple_glyph = if params.flp_letter_spacing =/ num_zero then draw_simple_glyph else draw_displaced_simple_glyph (size */ params.flp_letter_spacing) num_zero; accent_base_point = accent_base_point_x_height; accent_attach_point = accent_attach_point_top; get_composer = composer; kerning = tfm_kerning lig_cmds; get_glyph_bitmap = (get_glyph_bitmap (ref None)); get_glyph_name = (fun g -> Printf.sprintf "c%d" g); parameter = { hyphen_glyph = hyphen_glyph; skew_glyph = params.flp_skew_glyph; margin_glyph = Simple (last_glyph + 1); space_glyph = Simple (last_glyph + 2); foreign_glyph = Simple (last_glyph + 3); slant = if param_table_len > 0 then param.( 0) else num_zero; space = if param_table_len > 1 then size */ param.( 1) else num_zero; space_stretch = if param_table_len > 2 then size */ param.( 2) else num_zero; space_shrink = if param_table_len > 3 then size */ param.( 3) else num_zero; x_height = if param_table_len > 4 then size */ param.( 4) else num_zero; quad = if param_table_len > 5 then size */ param.( 5) else design_size; extra_space = if param_table_len > 6 then size */ param.( 6) else num_zero; num_shift_1 = if param_table_len > 7 then size */ param.( 7) else num_zero; num_shift_2 = if param_table_len > 8 then size */ param.( 8) else num_zero; num_shift_3 = if param_table_len > 9 then size */ param.( 9) else num_zero; denom_shift_1 = if param_table_len > 10 then size */ param.(10) else num_zero; denom_shift_2 = if param_table_len > 11 then size */ param.(11) else num_zero; super_shift_1 = if param_table_len > 12 then size */ param.(12) else num_zero; super_shift_2 = if param_table_len > 13 then size */ param.(13) else num_zero; super_shift_3 = if param_table_len > 14 then size */ param.(14) else num_zero; sub_shift_1 = if param_table_len > 15 then size */ param.(15) else num_zero; sub_shift_2 = if param_table_len > 16 then size */ param.(16) else num_zero; super_drop = if param_table_len > 17 then size */ param.(17) else num_zero; sub_drop = if param_table_len > 18 then size */ param.(18) else num_zero; delim_1 = if param_table_len > 19 then size */ param.(19) else num_zero; delim_2 = if param_table_len > 20 then size */ param.(20) else num_zero; axis_height = if param_table_len > 21 then size */ param.(21) else num_zero; rule_thickness = if param_table_len > 7 then size */ param.( 7) else num_zero; big_op_spacing_1 = if param_table_len > 8 then size */ param.( 8) else num_zero; big_op_spacing_2 = if param_table_len > 9 then size */ param.( 9) else num_zero; big_op_spacing_3 = if param_table_len > 10 then size */ param.(10) else num_zero; big_op_spacing_4 = if param_table_len > 11 then size */ param.(11) else num_zero; big_op_spacing_5 = if param_table_len > 12 then size */ param.(12) else num_zero } } };
bbca7ae6162fb6531d715efcb1c9f7d0a5afd34059a2bdcd31027f18e95f7fbb
Helium4Haskell/Top
TypeGraphSubstitution.hs
# LANGUAGE MonoLocalBinds , UndecidableInstances , FlexibleInstances , MultiParamTypeClasses # # OPTIONS_GHC -fno - warn - orphans # ----------------------------------------------------------------------------- -- | License : GPL -- -- Maintainer : -- Stability : provisional -- Portability : non-portable (requires extensions) ----------------------------------------------------------------------------- module Top.Implementation.TypeGraphSubstitution where import Top.Implementation.TypeGraph.ClassMonadic import Top.Implementation.TypeGraph.Standard import Top.Implementation.TypeGraph.Heuristic import Top.Interface.Substitution import Top.Interface.Basic import Top.Interface.TypeInference import Top.Interface.Qualification import Top.Implementation.TypeGraph.DefaultHeuristics import Top.Implementation.TypeGraph.ApplyHeuristics import Top.Monad.Select import Top.Monad.StateFix import Top.Solver import Top.Implementation.General import Top.Util.Embedding ------------------------------------------------------------------------ ( I ) Algebraic data type data TypeGraphState info = TypeGraphState { typegraph :: StandardTypeGraph info , heuristics :: PathHeuristics info } ------------------------------------------------------------------------ -- (II) Instance of SolveState (Empty, Show) instance Show info => SolveState (TypeGraphState info) where stateName _ = "Typegraph substitution state" instance Show info => Show (TypeGraphState info) where show = show . typegraph instance Show info => Empty (TypeGraphState info) where empty = TypeGraphState empty defaultHeuristics ------------------------------------------------------------------------ ( III ) instance Embedded ClassSubst (TypeGraphState info) (TypeGraphState info) where embedding = idE instance Embedded ClassSubst (Simple (TypeGraphState info) x m) (TypeGraphState info) where embedding = fromFstSimpleE embedding ------------------------------------------------------------------------ -- (IV) Instance declaration instance ( Monad m , Embedded ClassSubst (s (StateFixT s m)) t , HasTG (Select t (StateFixT s m)) info ) => HasTG (StateFixT s m) info where withTypeGraph f = deSubst (withTypeGraph f) instance ( MonadState s m , Embedded ClassSubst s (TypeGraphState info) ) => HasTG (Select (TypeGraphState info) m) info where withTypeGraph f = do (a, new) <- gets (f . typegraph) modify (\tgs -> tgs { typegraph = new }) return a instance ( HasBasic m info , HasTI m info , HasQual m info , HasTG m info , MonadWriter LogEntries m , Show info , MonadState s m , Embedded ClassSubst s (TypeGraphState info) ) => HasSubst (Select (TypeGraphState info) m) info where makeSubstConsistent = do hs <- gets heuristics select (removeInconsistencies hs) unifyTerms a b c = select (theUnifyTerms a b c) findSubstForVar a = select (substituteVariable a) fixpointSubst = select makeFixpointSubst removeInconsistencies :: HasTypeGraph m info => PathHeuristics info -> m () removeInconsistencies hs = do errs <- applyHeuristics hs mapM_ deleteEdge (concatMap fst errs) mapM_ (addLabeledError unificationErrorLabel . snd) errs if null errs then -- everything is okay: no errors were found. unmarkPossibleErrors Bug patch 3 february 2004 safety first : check whether * everything * is really removed . removeInconsistencies hs
null
https://raw.githubusercontent.com/Helium4Haskell/Top/5e900184d6b2ab6d7ce69945287d782252e5ea68/src/Top/Implementation/TypeGraphSubstitution.hs
haskell
--------------------------------------------------------------------------- | License : GPL Maintainer : Stability : provisional Portability : non-portable (requires extensions) --------------------------------------------------------------------------- ---------------------------------------------------------------------- ---------------------------------------------------------------------- (II) Instance of SolveState (Empty, Show) ---------------------------------------------------------------------- ---------------------------------------------------------------------- (IV) Instance declaration everything is okay: no errors were found.
# LANGUAGE MonoLocalBinds , UndecidableInstances , FlexibleInstances , MultiParamTypeClasses # # OPTIONS_GHC -fno - warn - orphans # module Top.Implementation.TypeGraphSubstitution where import Top.Implementation.TypeGraph.ClassMonadic import Top.Implementation.TypeGraph.Standard import Top.Implementation.TypeGraph.Heuristic import Top.Interface.Substitution import Top.Interface.Basic import Top.Interface.TypeInference import Top.Interface.Qualification import Top.Implementation.TypeGraph.DefaultHeuristics import Top.Implementation.TypeGraph.ApplyHeuristics import Top.Monad.Select import Top.Monad.StateFix import Top.Solver import Top.Implementation.General import Top.Util.Embedding ( I ) Algebraic data type data TypeGraphState info = TypeGraphState { typegraph :: StandardTypeGraph info , heuristics :: PathHeuristics info } instance Show info => SolveState (TypeGraphState info) where stateName _ = "Typegraph substitution state" instance Show info => Show (TypeGraphState info) where show = show . typegraph instance Show info => Empty (TypeGraphState info) where empty = TypeGraphState empty defaultHeuristics ( III ) instance Embedded ClassSubst (TypeGraphState info) (TypeGraphState info) where embedding = idE instance Embedded ClassSubst (Simple (TypeGraphState info) x m) (TypeGraphState info) where embedding = fromFstSimpleE embedding instance ( Monad m , Embedded ClassSubst (s (StateFixT s m)) t , HasTG (Select t (StateFixT s m)) info ) => HasTG (StateFixT s m) info where withTypeGraph f = deSubst (withTypeGraph f) instance ( MonadState s m , Embedded ClassSubst s (TypeGraphState info) ) => HasTG (Select (TypeGraphState info) m) info where withTypeGraph f = do (a, new) <- gets (f . typegraph) modify (\tgs -> tgs { typegraph = new }) return a instance ( HasBasic m info , HasTI m info , HasQual m info , HasTG m info , MonadWriter LogEntries m , Show info , MonadState s m , Embedded ClassSubst s (TypeGraphState info) ) => HasSubst (Select (TypeGraphState info) m) info where makeSubstConsistent = do hs <- gets heuristics select (removeInconsistencies hs) unifyTerms a b c = select (theUnifyTerms a b c) findSubstForVar a = select (substituteVariable a) fixpointSubst = select makeFixpointSubst removeInconsistencies :: HasTypeGraph m info => PathHeuristics info -> m () removeInconsistencies hs = do errs <- applyHeuristics hs mapM_ deleteEdge (concatMap fst errs) mapM_ (addLabeledError unificationErrorLabel . snd) errs if null errs unmarkPossibleErrors Bug patch 3 february 2004 safety first : check whether * everything * is really removed . removeInconsistencies hs
2d938b9c81821305c6865a5f62c6cbc7e91535cbf5f6059377537e32920c1003
kolmodin/spdy
NVH.hs
module Network.SPDY.NVH ( encodeNVH , decodeNVH ) where -- haskell platform import Control.Monad (liftM) import Data.Binary.Get (runGetOrFail) import Data.Binary.Put (runPut) import qualified Data.ByteString as B import qualified Data.ByteString.Lazy as L import Data.IORef (IORef, readIORef, writeIORef) 3rd party import qualified Codec.Zlib as Z import Data.Binary.Bits.Get (runBitGet) import Data.Binary.Bits.Put (runBitPut) -- this library import Network.SPDY.Frame (NVH, NameValueHeaderBlock, getNVHBlock, nvhDictionary, putNVHBlock) encodeNVH :: NVH -> IORef (Maybe Z.Deflate) -> IO L.ByteString encodeNVH nvh deflateRef = do deflate <- getDeflate deflateRef deflateWithFlush deflate $ runPut (runBitPut (putNVHBlock nvh)) decodeNVH :: L.ByteString -> IORef (Maybe Z.Inflate) -> IO NameValueHeaderBlock decodeNVH bytes inflateRef = do inflate <- getInflate inflateRef bytes' <- inflateWithFlush inflate (L.toStrict bytes) case runGetOrFail (runBitGet getNVHBlock) bytes' of Right (_, _, nvh) -> return nvh -- Fail _ _ msg -> throwIO (SPDYNVHException Nothing msg) Partial _ - > throwIO ( SPDYNVHException Nothing " Could not parse NVH block , returned Partial . " ) getOrMkNew :: IO a -> IORef (Maybe a) -> IO a getOrMkNew new ref = do v <- readIORef ref case v of Just x -> return x Nothing -> do x <- new writeIORef ref (Just x) return x mkInflate :: IO Z.Inflate mkInflate = Z.initInflateWithDictionary Z.defaultWindowBits nvhDictionary mkDeflate :: IO Z.Deflate mkDeflate = Z.initDeflateWithDictionary 6 nvhDictionary Z.defaultWindowBits getDeflate :: IORef (Maybe Z.Deflate) -> IO Z.Deflate getDeflate = getOrMkNew mkDeflate getInflate :: IORef (Maybe Z.Inflate) -> IO Z.Inflate getInflate = getOrMkNew mkInflate inflateWithFlush :: Z.Inflate -> B.ByteString -> IO L.ByteString inflateWithFlush zInflate bytes = do a <- unfoldM =<< Z.feedInflate zInflate bytes b <- Z.flushInflate zInflate return $ L.fromChunks (a++[b]) unfoldM :: Monad m => m (Maybe a) -> m [a] unfoldM ma = ma >>= maybe (return []) (\x -> liftM ((:) x) (unfoldM ma)) deflateWithFlush :: Z.Deflate -> L.ByteString -> IO L.ByteString deflateWithFlush deflate lbs = do str <- unfoldM =<< Z.feedDeflate deflate (B.concat (L.toChunks lbs)) fl <- unfoldM (Z.flushDeflate deflate) return (L.fromChunks (str ++ fl))
null
https://raw.githubusercontent.com/kolmodin/spdy/e81cb708695e2f08426a2fe8f2dc30de89e7a6db/Network/SPDY/NVH.hs
haskell
haskell platform this library Fail _ _ msg -> throwIO (SPDYNVHException Nothing msg)
module Network.SPDY.NVH ( encodeNVH , decodeNVH ) where import Control.Monad (liftM) import Data.Binary.Get (runGetOrFail) import Data.Binary.Put (runPut) import qualified Data.ByteString as B import qualified Data.ByteString.Lazy as L import Data.IORef (IORef, readIORef, writeIORef) 3rd party import qualified Codec.Zlib as Z import Data.Binary.Bits.Get (runBitGet) import Data.Binary.Bits.Put (runBitPut) import Network.SPDY.Frame (NVH, NameValueHeaderBlock, getNVHBlock, nvhDictionary, putNVHBlock) encodeNVH :: NVH -> IORef (Maybe Z.Deflate) -> IO L.ByteString encodeNVH nvh deflateRef = do deflate <- getDeflate deflateRef deflateWithFlush deflate $ runPut (runBitPut (putNVHBlock nvh)) decodeNVH :: L.ByteString -> IORef (Maybe Z.Inflate) -> IO NameValueHeaderBlock decodeNVH bytes inflateRef = do inflate <- getInflate inflateRef bytes' <- inflateWithFlush inflate (L.toStrict bytes) case runGetOrFail (runBitGet getNVHBlock) bytes' of Right (_, _, nvh) -> return nvh Partial _ - > throwIO ( SPDYNVHException Nothing " Could not parse NVH block , returned Partial . " ) getOrMkNew :: IO a -> IORef (Maybe a) -> IO a getOrMkNew new ref = do v <- readIORef ref case v of Just x -> return x Nothing -> do x <- new writeIORef ref (Just x) return x mkInflate :: IO Z.Inflate mkInflate = Z.initInflateWithDictionary Z.defaultWindowBits nvhDictionary mkDeflate :: IO Z.Deflate mkDeflate = Z.initDeflateWithDictionary 6 nvhDictionary Z.defaultWindowBits getDeflate :: IORef (Maybe Z.Deflate) -> IO Z.Deflate getDeflate = getOrMkNew mkDeflate getInflate :: IORef (Maybe Z.Inflate) -> IO Z.Inflate getInflate = getOrMkNew mkInflate inflateWithFlush :: Z.Inflate -> B.ByteString -> IO L.ByteString inflateWithFlush zInflate bytes = do a <- unfoldM =<< Z.feedInflate zInflate bytes b <- Z.flushInflate zInflate return $ L.fromChunks (a++[b]) unfoldM :: Monad m => m (Maybe a) -> m [a] unfoldM ma = ma >>= maybe (return []) (\x -> liftM ((:) x) (unfoldM ma)) deflateWithFlush :: Z.Deflate -> L.ByteString -> IO L.ByteString deflateWithFlush deflate lbs = do str <- unfoldM =<< Z.feedDeflate deflate (B.concat (L.toChunks lbs)) fl <- unfoldM (Z.flushDeflate deflate) return (L.fromChunks (str ++ fl))
415fa816728e60fe88edb447e7e73056d3f2286e550868d68a03a98bdd24566c
mixphix/toolbox
Toolbox.hs
# LANGUAGE TupleSections # -- | -- Module : Data.Tuple.Toolbox Copyright : ( c ) 2021 -- License : BSD3 (see the file LICENSE) -- Maintainer : -- -- Utility functions on top of 'Data.Tuple'. -- -- This module re-exports the above library, so modules need only import 'Data.Tuple.Toolbox'. module Data.Tuple.Toolbox ( -- * Pairs dup, (&&&), (***), first, second, both, assoc, unassoc, firstF, secondF, toFirst, toSecond, -- * Triples fst3, snd3, thd3, first3, second3, third3, first3F, second3F, third3F, pairFst, unpairFst, pairSnd, unpairSnd, * 4 - tuples frst4, scnd4, thrd4, frth4, first4, second4, third4, fourth4, first4F, second4F, third4F, fourth4F, -- * Re-exports module Data.Tuple, ) where import Control.Applicative (liftA2) import Control.Monad (join) import qualified Data.Bifunctor (bimap, first, second) import Data.Tuple -- | Duplicate a value. dup :: a -> (a, a) dup a = (a, a) infix 1 &&&, *** | Apply two functions to the same value . -- > ( pred & & & succ ) 0 = = ( -1 , 1 ) (&&&) :: (a -> b) -> (a -> c) -> (a -> (b, c)) (&&&) = liftA2 (,) | Apply two functions pairwise . -- > ( pred * * * succ ) ( 0 , 0 ) = = ( -1 , 1 ) (***) :: (a -> c) -> (b -> d) -> ((a, b) -> (c, d)) (***) = Data.Bifunctor.bimap -- | Apply the same function to both components. both :: (a -> b) -> (a, a) -> (b, b) both = join (***) | Map a function over the first component of a pair . first :: (a -> b) -> (a, x) -> (b, x) first = Data.Bifunctor.first | Map a function over the second component of a pair . second :: (a -> b) -> (x, a) -> (x, b) second = Data.Bifunctor.second | Map a functorial function over the first component a pair , so that the whole pair is inside the functor . firstF :: (Functor f) => (a -> f b) -> (a, x) -> f (b, x) firstF f (a, x) = (,x) <$> f a | Map a functorial function over the second component a pair , so that the whole pair is inside the functor . secondF :: (Functor f) => (a -> f b) -> (x, a) -> f (x, b) secondF f (x, a) = (x,) <$> f a | Apply a functorial function and keep the argument in the second component . -- > toFirst (: [ ] ) 3 = = ( [ 3 ] , 3 ) -- > toFirst f x == firstF (const . f) (dup x) toFirst :: (Functor f) => (a -> f b) -> a -> f (b, a) toFirst f a = (,a) <$> f a | Apply a functorial function and keep the argument in the first component . -- > toSecond (: [ ] ) 3 = = ( [ 3 ] , 3 ) -- > toSecond f x == secondF (const . f) (dup x) toSecond :: (Functor f) => (a -> f b) -> a -> f (a, b) toSecond f a = (a,) <$> f a -- | Associate a pair-inside-a-pair. -- -- > assoc . unassoc == id assoc :: (a, (b, c)) -> ((a, b), c) assoc (a, (b, c)) = ((a, b), c) -- | Un-associate a pair-inside-a-pair. -- -- > unassoc . assoc == id unassoc :: ((a, b), c) -> (a, (b, c)) unassoc ((a, b), c) = (a, (b, c)) | Flatten a ' fst'-nested pair into a 3 - tuple . unpairFst :: ((a, b), c) -> (a, b, c) unpairFst ((a, b), c) = (a, b, c) | Flatten a ' snd'-nested pair into a 3 - tuple . unpairSnd :: (a, (b, c)) -> (a, b, c) unpairSnd (a, (b, c)) = (a, b, c) | Associate a 3 - tuple into a ' fst'-nested pair . pairFst :: (a, b, c) -> ((a, b), c) pairFst (a, b, c) = ((a, b), c) | Associate a 3 - tuple into a ' snd'-nested pair . pairSnd :: (a, b, c) -> (a, (b, c)) pairSnd (a, b, c) = (a, (b, c)) | Get the first component of a triple . fst3 :: (a, b, c) -> a fst3 (a, _, _) = a | Get the second component of a triple . snd3 :: (a, b, c) -> b snd3 (_, b, _) = b | Get the third component of a triple . thd3 :: (a, b, c) -> c thd3 (_, _, c) = c | Map a function over the first component of a triple . -- > first3 succ ( 0 , 0 , 0 ) = = ( 1 , 0 , 0 ) first3 :: (a -> x) -> (a, b, c) -> (x, b, c) first3 f (a, b, c) = (f a, b, c) | Map a function over the second component of a triple . -- > second3 succ ( 0 , 0 , 0 ) = = ( 0 , 1 , 0 ) second3 :: (b -> x) -> (a, b, c) -> (a, x, c) second3 f (a, b, c) = (a, f b, c) | Map a function over the third component of a triple . -- > third3 succ ( 0 , 0 , 0 ) = = ( 0 , 0 , 1 ) third3 :: (c -> x) -> (a, b, c) -> (a, b, x) third3 f (a, b, c) = (a, b, f c) | Map a functorial function over the first component of a triple , so that the whole triple is inside the functor . -- > first3F ( const Nothing ) ( 0 , 0 , 0 ) = = Nothing first3F :: (Functor f) => (a -> f x) -> (a, b, c) -> f (x, b, c) first3F f (a, b, c) = (,b,c) <$> f a | Map a functorial function over the second component of a triple , so that the whole triple is inside the functor . -- > second3F ( Just . pred ) ( 0 , 0 , 0 ) = = Just ( 0 , -1 , 0 ) second3F :: (Functor f) => (b -> f x) -> (a, b, c) -> f (a, x, c) second3F f (a, b, c) = (a,,c) <$> f b | Map a functorial function over the third component of a triple , so that the whole triple is inside the functor . -- > third3F ( Just . succ ) ( 0 , 0 , 0 ) = = Just ( 0 , 0 , 1 ) third3F :: (Functor f) => (c -> f x) -> (a, b, c) -> f (a, b, x) third3F f (a, b, c) = (a,b,) <$> f c | Get the first component of a 4 - tuple . frst4 :: (a, b, c, d) -> a frst4 (a, _, _, _) = a | Get the second component of a 4 - tuple . scnd4 :: (a, b, c, d) -> b scnd4 (_, b, _, _) = b | Get the third component of a 4 - tuple . thrd4 :: (a, b, c, d) -> c thrd4 (_, _, c, _) = c | Get the fourth component of a 4 - tuple . frth4 :: (a, b, c, d) -> d frth4 (_, _, _, d) = d | Map a function over the first component of a 4 - tuple . -- > succ ( 0 , 0 , 0 , 0 ) = = ( 1 , 0 , 0 , 0 ) first4 :: (a -> x) -> (a, b, c, d) -> (x, b, c, d) first4 f (a, b, c, d) = (f a, b, c, d) | Map a function over the second component of a 4 - tuple . -- > succ ( 0 , 0 , 0 , 0 ) = = ( 0 , 1 , 0 , 0 ) second4 :: (b -> x) -> (a, b, c, d) -> (a, x, c, d) second4 f (a, b, c, d) = (a, f b, c, d) | Map a function over the third component of a 4 - tuple . -- > third4 succ ( 0 , 0 , 0 , 0 ) = = ( 0 , 0 , 1 , 0 ) third4 :: (c -> x) -> (a, b, c, d) -> (a, b, x, d) third4 f (a, b, c, d) = (a, b, f c, d) | Map a function over the fourth component of a 4 - tuple . -- > fourth4 succ ( 0 , 0 , 0 , 0 ) = = ( 0 , 0 , 0 , 1 ) fourth4 :: (d -> x) -> (a, b, c, d) -> (a, b, c, x) fourth4 f (a, b, c, d) = (a, b, c, f d) | Map a function over the first component of a 4 - tuple , so that the entire tuple is inside the functor . first4F :: (Functor f) => (a -> f x) -> (a, b, c, d) -> f (x, b, c, d) first4F f (a, b, c, d) = (,b,c,d) <$> f a | Map a function over the second component of a 4 - tuple , so that the entire tuple is inside the functor . second4F :: (Functor f) => (b -> f x) -> (a, b, c, d) -> f (a, x, c, d) second4F f (a, b, c, d) = (a,,c,d) <$> f b | Map a function over the third component of a 4 - tuple , so that the entire tuple is inside the functor . -- > third4F succ ( 0 , 0 , 0 , 0 ) = = ( 0 , 0 , 1 , 0 ) third4F :: (Functor f) => (c -> f x) -> (a, b, c, d) -> f (a, b, x, d) third4F f (a, b, c, d) = (a,b,,d) <$> f c | Map a function over the fourth component of a 4 - tuple , so that the entire tuple is inside the functor . fourth4F :: (Functor f) => (d -> f x) -> (a, b, c, d) -> f (a, b, c, x) fourth4F f (a, b, c, d) = (a,b,c,) <$> f d
null
https://raw.githubusercontent.com/mixphix/toolbox/e36340533f1b543759bb4c1fff4e5a11d6274849/src/Data/Tuple/Toolbox.hs
haskell
| Module : Data.Tuple.Toolbox License : BSD3 (see the file LICENSE) Maintainer : Utility functions on top of 'Data.Tuple'. This module re-exports the above library, so modules need only import 'Data.Tuple.Toolbox'. * Pairs * Triples * Re-exports | Duplicate a value. | Apply the same function to both components. > toFirst f x == firstF (const . f) (dup x) > toSecond f x == secondF (const . f) (dup x) | Associate a pair-inside-a-pair. > assoc . unassoc == id | Un-associate a pair-inside-a-pair. > unassoc . assoc == id
# LANGUAGE TupleSections # Copyright : ( c ) 2021 module Data.Tuple.Toolbox ( dup, (&&&), (***), first, second, both, assoc, unassoc, firstF, secondF, toFirst, toSecond, fst3, snd3, thd3, first3, second3, third3, first3F, second3F, third3F, pairFst, unpairFst, pairSnd, unpairSnd, * 4 - tuples frst4, scnd4, thrd4, frth4, first4, second4, third4, fourth4, first4F, second4F, third4F, fourth4F, module Data.Tuple, ) where import Control.Applicative (liftA2) import Control.Monad (join) import qualified Data.Bifunctor (bimap, first, second) import Data.Tuple dup :: a -> (a, a) dup a = (a, a) infix 1 &&&, *** | Apply two functions to the same value . > ( pred & & & succ ) 0 = = ( -1 , 1 ) (&&&) :: (a -> b) -> (a -> c) -> (a -> (b, c)) (&&&) = liftA2 (,) | Apply two functions pairwise . > ( pred * * * succ ) ( 0 , 0 ) = = ( -1 , 1 ) (***) :: (a -> c) -> (b -> d) -> ((a, b) -> (c, d)) (***) = Data.Bifunctor.bimap both :: (a -> b) -> (a, a) -> (b, b) both = join (***) | Map a function over the first component of a pair . first :: (a -> b) -> (a, x) -> (b, x) first = Data.Bifunctor.first | Map a function over the second component of a pair . second :: (a -> b) -> (x, a) -> (x, b) second = Data.Bifunctor.second | Map a functorial function over the first component a pair , so that the whole pair is inside the functor . firstF :: (Functor f) => (a -> f b) -> (a, x) -> f (b, x) firstF f (a, x) = (,x) <$> f a | Map a functorial function over the second component a pair , so that the whole pair is inside the functor . secondF :: (Functor f) => (a -> f b) -> (x, a) -> f (x, b) secondF f (x, a) = (x,) <$> f a | Apply a functorial function and keep the argument in the second component . > toFirst (: [ ] ) 3 = = ( [ 3 ] , 3 ) toFirst :: (Functor f) => (a -> f b) -> a -> f (b, a) toFirst f a = (,a) <$> f a | Apply a functorial function and keep the argument in the first component . > toSecond (: [ ] ) 3 = = ( [ 3 ] , 3 ) toSecond :: (Functor f) => (a -> f b) -> a -> f (a, b) toSecond f a = (a,) <$> f a assoc :: (a, (b, c)) -> ((a, b), c) assoc (a, (b, c)) = ((a, b), c) unassoc :: ((a, b), c) -> (a, (b, c)) unassoc ((a, b), c) = (a, (b, c)) | Flatten a ' fst'-nested pair into a 3 - tuple . unpairFst :: ((a, b), c) -> (a, b, c) unpairFst ((a, b), c) = (a, b, c) | Flatten a ' snd'-nested pair into a 3 - tuple . unpairSnd :: (a, (b, c)) -> (a, b, c) unpairSnd (a, (b, c)) = (a, b, c) | Associate a 3 - tuple into a ' fst'-nested pair . pairFst :: (a, b, c) -> ((a, b), c) pairFst (a, b, c) = ((a, b), c) | Associate a 3 - tuple into a ' snd'-nested pair . pairSnd :: (a, b, c) -> (a, (b, c)) pairSnd (a, b, c) = (a, (b, c)) | Get the first component of a triple . fst3 :: (a, b, c) -> a fst3 (a, _, _) = a | Get the second component of a triple . snd3 :: (a, b, c) -> b snd3 (_, b, _) = b | Get the third component of a triple . thd3 :: (a, b, c) -> c thd3 (_, _, c) = c | Map a function over the first component of a triple . > first3 succ ( 0 , 0 , 0 ) = = ( 1 , 0 , 0 ) first3 :: (a -> x) -> (a, b, c) -> (x, b, c) first3 f (a, b, c) = (f a, b, c) | Map a function over the second component of a triple . > second3 succ ( 0 , 0 , 0 ) = = ( 0 , 1 , 0 ) second3 :: (b -> x) -> (a, b, c) -> (a, x, c) second3 f (a, b, c) = (a, f b, c) | Map a function over the third component of a triple . > third3 succ ( 0 , 0 , 0 ) = = ( 0 , 0 , 1 ) third3 :: (c -> x) -> (a, b, c) -> (a, b, x) third3 f (a, b, c) = (a, b, f c) | Map a functorial function over the first component of a triple , so that the whole triple is inside the functor . > first3F ( const Nothing ) ( 0 , 0 , 0 ) = = Nothing first3F :: (Functor f) => (a -> f x) -> (a, b, c) -> f (x, b, c) first3F f (a, b, c) = (,b,c) <$> f a | Map a functorial function over the second component of a triple , so that the whole triple is inside the functor . > second3F ( Just . pred ) ( 0 , 0 , 0 ) = = Just ( 0 , -1 , 0 ) second3F :: (Functor f) => (b -> f x) -> (a, b, c) -> f (a, x, c) second3F f (a, b, c) = (a,,c) <$> f b | Map a functorial function over the third component of a triple , so that the whole triple is inside the functor . > third3F ( Just . succ ) ( 0 , 0 , 0 ) = = Just ( 0 , 0 , 1 ) third3F :: (Functor f) => (c -> f x) -> (a, b, c) -> f (a, b, x) third3F f (a, b, c) = (a,b,) <$> f c | Get the first component of a 4 - tuple . frst4 :: (a, b, c, d) -> a frst4 (a, _, _, _) = a | Get the second component of a 4 - tuple . scnd4 :: (a, b, c, d) -> b scnd4 (_, b, _, _) = b | Get the third component of a 4 - tuple . thrd4 :: (a, b, c, d) -> c thrd4 (_, _, c, _) = c | Get the fourth component of a 4 - tuple . frth4 :: (a, b, c, d) -> d frth4 (_, _, _, d) = d | Map a function over the first component of a 4 - tuple . > succ ( 0 , 0 , 0 , 0 ) = = ( 1 , 0 , 0 , 0 ) first4 :: (a -> x) -> (a, b, c, d) -> (x, b, c, d) first4 f (a, b, c, d) = (f a, b, c, d) | Map a function over the second component of a 4 - tuple . > succ ( 0 , 0 , 0 , 0 ) = = ( 0 , 1 , 0 , 0 ) second4 :: (b -> x) -> (a, b, c, d) -> (a, x, c, d) second4 f (a, b, c, d) = (a, f b, c, d) | Map a function over the third component of a 4 - tuple . > third4 succ ( 0 , 0 , 0 , 0 ) = = ( 0 , 0 , 1 , 0 ) third4 :: (c -> x) -> (a, b, c, d) -> (a, b, x, d) third4 f (a, b, c, d) = (a, b, f c, d) | Map a function over the fourth component of a 4 - tuple . > fourth4 succ ( 0 , 0 , 0 , 0 ) = = ( 0 , 0 , 0 , 1 ) fourth4 :: (d -> x) -> (a, b, c, d) -> (a, b, c, x) fourth4 f (a, b, c, d) = (a, b, c, f d) | Map a function over the first component of a 4 - tuple , so that the entire tuple is inside the functor . first4F :: (Functor f) => (a -> f x) -> (a, b, c, d) -> f (x, b, c, d) first4F f (a, b, c, d) = (,b,c,d) <$> f a | Map a function over the second component of a 4 - tuple , so that the entire tuple is inside the functor . second4F :: (Functor f) => (b -> f x) -> (a, b, c, d) -> f (a, x, c, d) second4F f (a, b, c, d) = (a,,c,d) <$> f b | Map a function over the third component of a 4 - tuple , so that the entire tuple is inside the functor . > third4F succ ( 0 , 0 , 0 , 0 ) = = ( 0 , 0 , 1 , 0 ) third4F :: (Functor f) => (c -> f x) -> (a, b, c, d) -> f (a, b, x, d) third4F f (a, b, c, d) = (a,b,,d) <$> f c | Map a function over the fourth component of a 4 - tuple , so that the entire tuple is inside the functor . fourth4F :: (Functor f) => (d -> f x) -> (a, b, c, d) -> f (a, b, c, x) fourth4F f (a, b, c, d) = (a,b,c,) <$> f d
47cd5c447683f57a70ea565be73ef179dfb640a75092ffc3cf1e90cb7583f46c
kelamg/HtDP2e-workthrough
ex225.rkt
The first three lines of this file were inserted by . They record metadata ;; about the language level of this file in a form that our tools can easily process. #reader(lib "htdp-beginner-abbr-reader.ss" "lang")((modname ex225) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #f #t none #f () #f))) (require 2htdp/image) (require 2htdp/universe) ;; CONSTANTS ;; Scene (define WIDTH 800) (define HEIGHT 400) (define CENTER (/ WIDTH 2)) (define MTS (empty-scene WIDTH HEIGHT "black")) ;; airplane (define AIRPLANE-SPEED 10) (define AIRPLANE-WIDTH 120) (define AIRPLANE-HEIGHT 30) (define AIRPLANE-Y (+ AIRPLANE-HEIGHT 20)) (define AIRPLANE-RUDDER-SIZE AIRPLANE-HEIGHT) (define AIRPLANE-RUDDER (rotate 25 (triangle AIRPLANE-RUDDER-SIZE "solid" "red"))) (define AIRPLANE (underlay/xy AIRPLANE-RUDDER (- (/ AIRPLANE-RUDDER-SIZE 2)) (/ AIRPLANE-RUDDER-SIZE 2) (ellipse AIRPLANE-WIDTH AIRPLANE-HEIGHT "solid" "gray"))) (define AIRPLANE-FLIP-LEFT (flip-horizontal AIRPLANE)) ;; fire (define FIRE (overlay (ellipse 10 30 "solid" "red") (ellipse 20 40 "solid" "orange"))) (define FIRE-Y (- HEIGHT (/ (image-height FIRE) 2))) .005 probability of spawning per tick (define MAX-FIRE-PROXIMITY (image-width FIRE)) (define MAX-FIRES 5) (define HIT-RANGE 10) ;; water (define BABY-BLUE (make-color 137 207 240)) (define WATER (overlay (ellipse 15 35 "solid" "blue") (ellipse 25 45 "solid" BABY-BLUE))) (define WATER-SPEED 5) (define TIME-LIMIT 60) ; in secs ;; DEFINITIONS (define-struct plane (x dir)) ;; An Airplane is a structure: ( make - plane Number Direction N ) ;; interp. at any time, a plane is at x-coordinate x, ;; and has a direction dir A Direction is one of : ;; - 1 ;; - -1 interp . 1 means going right , -1 means going left ;; A Water is a Posn ;; interp. the position of a waterload on the canvas ;; List-of-water is one of: ;; - '() ;; - (cons Water List-of-water) ;; A Fire is a Posn ;; interp. the position of a fire on the canvas ;; List-of-fire is one of: ;; - '() - ( cons Fire List - of - fire ) (define-struct game (plane fires waters)) ;; A Game is a structure: ( make - game Plane List - of - fire List - of - water ) ;; interp. the entire state of the world (define P1 (make-plane 0 -1)) (define P2 (make-plane WIDTH 1)) (define P3 (make-plane CENTER 1)) (define F0 '()) (define F1 (list (make-posn 75 FIRE-Y))) (define F2 (list (make-posn 650 FIRE-Y))) (define F3 (list (make-posn 110 135) (make-posn CENTER FIRE-Y))) (define W0 '()) (define W1 (list (make-posn 75 (- FIRE-Y HIT-RANGE)))) (define W2 (list (make-posn 590 100))) (define W3 (list (make-posn 214 253) (make-posn CENTER 183))) (define W4 (cons (make-posn 200 (+ HEIGHT (image-height WATER) 1)) W3)) (define GS0 (make-game P1 '() '())) (define GS1 (make-game P1 F1 W1)) (define GS2 (make-game P2 F2 W2)) (define GS3 (make-game P3 F3 W3)) (define GS4 (make-game P3 F3 W4)) (define GS-INIT (make-game (make-plane CENTER 1) '() '())) ;; FUNCTIONS GameState - > GameState run with ( main GS - INIT ) (define (main gs) (big-bang gs [to-draw render-game] [on-tick next-game 1/28 (* TIME-LIMIT 28)] [on-key plane-control] [check-with is-gamestate?])) GameState - > Image ;; renders an image of the entire state of the game (check-expect (render-game GS0) (render-plane P1 MTS)) (check-expect (render-game GS1) (render-plane P1 (render-posn-objs F1 FIRE (render-posn-objs W1 WATER MTS)))) (check-expect (render-game GS3) (render-plane P3 (render-posn-objs F3 FIRE (render-posn-objs W3 WATER MTS)))) (define (render-game gs) (render-plane (game-plane gs) (render-posn-objs (game-fires gs) FIRE (render-posn-objs (game-waters gs) WATER MTS)))) ;; List-of-posn Image Image -> Image ;; renders posn objects of akin image into img at their specified positions (check-expect (render-posn-objs F0 FIRE MTS) MTS) (check-expect (render-posn-objs F3 FIRE MTS) (place-image FIRE (posn-x (first F3)) (posn-y (first F3)) (place-image FIRE (posn-x (second F3)) (posn-y (second F3)) MTS))) (check-expect (render-posn-objs W0 WATER MTS) MTS) (check-expect (render-posn-objs W3 WATER MTS) (place-image WATER (posn-x (first W3)) (posn-y (first W3)) (place-image WATER (posn-x (second W3)) (posn-y (second W3)) MTS))) (define (render-posn-objs lop p-img img) (cond [(empty? lop) img] [else (place-image p-img (posn-x (first lop)) (posn-y (first lop)) (render-posn-objs (rest lop) p-img img))])) Plane Image - > Image ;; renders a plane into image img ;; flips the plane if at edges of the scene (check-expect (render-plane P1 MTS) (place-image AIRPLANE-FLIP-LEFT (plane-x P1) AIRPLANE-Y MTS)) (check-expect (render-plane P2 MTS) (place-image AIRPLANE (plane-x P2) AIRPLANE-Y MTS)) (check-expect (render-plane P3 MTS) (place-image AIRPLANE (plane-x P3) AIRPLANE-Y MTS)) (define (render-plane p img) (if (= (plane-dir p) 1) (place-image AIRPLANE (plane-x p) AIRPLANE-Y img) (place-image AIRPLANE-FLIP-LEFT (plane-x p) AIRPLANE-Y img))) GameState - > GameState ;; produces the next state of the game (define (next-game gs) (make-game (game-plane gs) (process-fires (game-fires gs) (game-waters gs)) (process-waterloads (game-waters gs) (game-fires gs)))) ;; List-of-fire List-of-water -> List-of-fire ;; randomly spawns fires based on how many fires are currently burning (define (process-fires lof low) (if (should-create? lof) (fire-create (cancel-out lof low)) (cancel-out lof low))) ;; List-of-fire -> Boolean produces true if length of lof is below MAX - FIRES ;; and the probability test passes (define (should-create? lof) (and (<= (length lof) MAX-FIRES) (< (/ (random 1000) 1000) FIRE-SPAWN-PROBABILITY))) ;; List-of-fire -> List-of-fire ;; generates a new fire based on currently burning fires (check-satisfied (fire-create F0) proper?) (check-satisfied (fire-create F1) proper?) (define (fire-create lof) (fire-check-create (make-posn (random WIDTH) FIRE-Y) lof)) ;; Fire List-of-fire -> List-of-fire ;; generative recursion new Fire is generated at random until the currently generated one is not at the same position as the last one (define (fire-check-create f candidate) (if (close-proximity? f candidate) (fire-create candidate) (cons f candidate))) ;; Fire List-of-fire -> Boolean ;; produces true if fire f is too close to any other fire (check-expect (close-proximity? (make-posn 40 FIRE-Y) (list (make-posn 450 FIRE-Y) (make-posn 80 FIRE-Y))) #f) (check-expect (close-proximity? (make-posn 40 FIRE-Y) (list (make-posn (+ 40 MAX-FIRE-PROXIMITY) FIRE-Y) (make-posn 80 FIRE-Y))) #t) (define (close-proximity? f lof) (cond [(empty? lof) #f] [else (or (<= (abs (- (posn-x f) (posn-x (first lof)))) MAX-FIRE-PROXIMITY) (close-proximity? f (rest lof)))])) ; Fire -> Boolean ; use for testing only (define (proper? lof) (not (member? (first lof) (rest lof)))) ;; List-of-water List-of-fire -> List-of-water ;; advances each waterload (if any) down the canvas waterloads that hit a fire get used ( removed from list ) , ;; as well as those that fall out beneath the scene (check-expect (process-waterloads W0 F0) '()) (check-expect (process-waterloads W1 F1) '()) (check-expect (process-waterloads W1 F2) (list (make-posn (posn-x (first W1)) (+ (posn-y (first W1)) WATER-SPEED)))) (check-expect (process-waterloads W2 F2) (list (make-posn (posn-x (first W2)) (+ (posn-y (first W2)) WATER-SPEED)))) (check-expect (process-waterloads W3 F3) (list (make-posn (posn-x (first W3)) (+ (posn-y (first W3)) WATER-SPEED)) (make-posn (posn-x (second W3)) (+ (posn-y (second W3)) WATER-SPEED)))) (define (process-waterloads low lof) (drop-waterloads (cancel-out (filter-missed-waterloads low) lof))) ;; List-of-water -> List-of-water ;; drops each waterload towards to the bottom of the scene (check-expect (drop-waterloads W2) (list (make-posn (posn-x (first W2)) (+ (posn-y (first W2)) WATER-SPEED)))) (check-expect (drop-waterloads W3) (list (make-posn (posn-x (first W3)) (+ (posn-y (first W3)) WATER-SPEED)) (make-posn (posn-x (second W3)) (+ (posn-y (second W3)) WATER-SPEED)))) (define (drop-waterloads low) (cond [(empty? low) '()] [else (cons (make-posn (posn-x (first low)) (+ (posn-y (first low)) WATER-SPEED)) (drop-waterloads (rest low)))])) ;; List-of-water -> List-of-water only keeps the waterloads that are still visible in the scene ;; removes those that have fallen off the bottom of the scene (check-expect (filter-missed-waterloads W3) W3) (check-expect (filter-missed-waterloads W4) W3) (define (filter-missed-waterloads low) (cond [(empty? low) '()] [else (if (>= (posn-y (first low)) (+ HEIGHT (image-height WATER))) (filter-missed-waterloads (rest low)) (cons (first low) (filter-missed-waterloads (rest low))))])) ;; List-of-posn List-of-posn -> List-of-posn removes all posns in that are " too close " to any posns in lopb (check-expect (cancel-out (list (make-posn 23 50) (make-posn 63 79)) (list (make-posn 20 51) (make-posn 80 100))) (list (make-posn 63 79))) (check-expect (cancel-out (list (make-posn 23 50) (make-posn 63 79)) (list (make-posn 200 51) (make-posn 80 100))) (list (make-posn 23 50) (make-posn 63 79))) (define (cancel-out lopa lopb) (cond [(empty? lopa) '()] [else (if (hit? (first lopa) lopb) (cancel-out (rest lopa) lopb) (cons (first lopa) (cancel-out (rest lopa) lopb)))])) ;; Posn List-of-Posn -> Boolean produces true if p is close enough to any posn in lop (check-expect (hit? (make-posn 23 50) (list (make-posn 20 51) (make-posn 80 100))) #t) (check-expect (hit? (make-posn 23 50) (list (make-posn 200 51) (make-posn 80 100))) #f) (define (hit? w lof) (cond [(empty? lof) #f] [else (or (close? w (first lof)) (hit? w (rest lof)))])) ;; Posn Posn -> Boolean ;; produces true if p1 and p2 are close enough to each others (check-expect (close? (make-posn 42 42) (make-posn 30 70)) #f) (check-expect (close? (make-posn 50 120) (make-posn 50 119)) #t) (check-expect (close? (make-posn 30 70) (make-posn 30 70)) #t) (define (close? p1 p2) (<= (distance p1 p2) HIT-RANGE)) ;; Posn -> Number calculates the Eucledian distance between two posns (check-expect (round (distance (make-posn 0 4) (make-posn 3 0))) 5) (check-expect (round (distance (make-posn 12 48) (make-posn 34 28))) 30) (define (distance a b) (inexact->exact (sqrt (+ (sqr (- (posn-y a) (posn-y b))) (sqr (- (posn-x a) (posn-x b))))))) Plane Direction - > Plane ;; translates the plane right or left (check-expect (plane-translate P1 1) (make-plane (+ (plane-x P1) AIRPLANE-SPEED) 1)) (check-expect (plane-translate P1 -1) (make-plane (+ (plane-x P1) (* AIRPLANE-SPEED (plane-dir P1))) -1)) (check-expect (plane-translate P2 1) (make-plane (+ (plane-x P2) (* AIRPLANE-SPEED (plane-dir P2))) 1)) (check-expect (plane-translate P2 -1) (make-plane (- (plane-x P2) AIRPLANE-SPEED) -1)) (define (plane-translate p dir) (cond [(= dir (plane-dir p)) (make-plane (+ (plane-x p) (* AIRPLANE-SPEED (plane-dir p))) (plane-dir p))] [(and (= dir 1) (= (plane-dir p) -1)) (make-plane (+ (plane-x p) AIRPLANE-SPEED) 1)] [(and (= dir -1) (= (plane-dir p) 1)) (make-plane (- (plane-x p) AIRPLANE-SPEED) -1)])) GameState KeyEvent - > GameState ;; controls the movement of the plane ;; "left" moves the plane left, "right" moves the plane "right" " " drops waterloads (check-expect (plane-control GS0 "left") GS0) (check-expect (plane-control GS0 "right") (make-game (plane-translate P1 1) (game-fires GS0) (game-waters GS0))) (check-expect (plane-control GS2 "right") GS2) (check-expect (plane-control GS2 "left") (make-game (plane-translate P2 -1) (game-fires GS2) (game-waters GS2))) (check-expect (plane-control GS3 "down") GS3) (check-expect (plane-control GS3 "a") GS3) (check-expect (plane-control GS3 "right") (make-game (plane-translate P3 1) (game-fires GS3) (game-waters GS3))) (check-expect (plane-control GS3 "left") (make-game (plane-translate P3 -1) (game-fires GS3) (game-waters GS3))) (check-expect (plane-control GS3 " ") (make-game (game-plane GS3) (game-fires GS3) (cons (make-posn (plane-x (game-plane GS3)) (+ AIRPLANE-Y AIRPLANE-HEIGHT)) (game-waters GS3)))) (define (plane-control gs ke) (cond [(and (key=? ke "left") (not (<= (plane-x (game-plane gs)) 0))) (make-game (plane-translate (game-plane gs) -1) (game-fires gs) (game-waters gs))] [(and (key=? ke "right") (not (>= (plane-x (game-plane gs)) WIDTH))) (make-game (plane-translate (game-plane gs) 1) (game-fires gs) (game-waters gs))] [(key=? ke " ") (make-game (game-plane gs) (game-fires gs) (cons (make-posn (plane-x (game-plane gs)) (+ AIRPLANE-Y AIRPLANE-HEIGHT)) (game-waters gs)))] [else gs])) GameState - > Boolean (define (is-gamestate? gs) (game? gs))
null
https://raw.githubusercontent.com/kelamg/HtDP2e-workthrough/ec05818d8b667a3c119bea8d1d22e31e72e0a958/HtDP/Arbitrarily-Large-Data/ex225.rkt
racket
about the language level of this file in a form that our tools can easily process. CONSTANTS Scene airplane fire water in secs DEFINITIONS An Airplane is a structure: interp. at any time, a plane is at x-coordinate x, and has a direction dir - 1 - -1 A Water is a Posn interp. the position of a waterload on the canvas List-of-water is one of: - '() - (cons Water List-of-water) A Fire is a Posn interp. the position of a fire on the canvas List-of-fire is one of: - '() A Game is a structure: interp. the entire state of the world FUNCTIONS renders an image of the entire state of the game List-of-posn Image Image -> Image renders posn objects of akin image into img at their specified positions renders a plane into image img flips the plane if at edges of the scene produces the next state of the game List-of-fire List-of-water -> List-of-fire randomly spawns fires based on how many fires are currently burning List-of-fire -> Boolean and the probability test passes List-of-fire -> List-of-fire generates a new fire based on currently burning fires Fire List-of-fire -> List-of-fire generative recursion Fire List-of-fire -> Boolean produces true if fire f is too close to any other fire Fire -> Boolean use for testing only List-of-water List-of-fire -> List-of-water advances each waterload (if any) down the canvas as well as those that fall out beneath the scene List-of-water -> List-of-water drops each waterload towards to the bottom of the scene List-of-water -> List-of-water removes those that have fallen off the bottom of the scene List-of-posn List-of-posn -> List-of-posn Posn List-of-Posn -> Boolean Posn Posn -> Boolean produces true if p1 and p2 are close enough to each others Posn -> Number translates the plane right or left controls the movement of the plane "left" moves the plane left, "right" moves the plane "right"
The first three lines of this file were inserted by . They record metadata #reader(lib "htdp-beginner-abbr-reader.ss" "lang")((modname ex225) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #f #t none #f () #f))) (require 2htdp/image) (require 2htdp/universe) (define WIDTH 800) (define HEIGHT 400) (define CENTER (/ WIDTH 2)) (define MTS (empty-scene WIDTH HEIGHT "black")) (define AIRPLANE-SPEED 10) (define AIRPLANE-WIDTH 120) (define AIRPLANE-HEIGHT 30) (define AIRPLANE-Y (+ AIRPLANE-HEIGHT 20)) (define AIRPLANE-RUDDER-SIZE AIRPLANE-HEIGHT) (define AIRPLANE-RUDDER (rotate 25 (triangle AIRPLANE-RUDDER-SIZE "solid" "red"))) (define AIRPLANE (underlay/xy AIRPLANE-RUDDER (- (/ AIRPLANE-RUDDER-SIZE 2)) (/ AIRPLANE-RUDDER-SIZE 2) (ellipse AIRPLANE-WIDTH AIRPLANE-HEIGHT "solid" "gray"))) (define AIRPLANE-FLIP-LEFT (flip-horizontal AIRPLANE)) (define FIRE (overlay (ellipse 10 30 "solid" "red") (ellipse 20 40 "solid" "orange"))) (define FIRE-Y (- HEIGHT (/ (image-height FIRE) 2))) .005 probability of spawning per tick (define MAX-FIRE-PROXIMITY (image-width FIRE)) (define MAX-FIRES 5) (define HIT-RANGE 10) (define BABY-BLUE (make-color 137 207 240)) (define WATER (overlay (ellipse 15 35 "solid" "blue") (ellipse 25 45 "solid" BABY-BLUE))) (define WATER-SPEED 5) (define-struct plane (x dir)) ( make - plane Number Direction N ) A Direction is one of : interp . 1 means going right , -1 means going left - ( cons Fire List - of - fire ) (define-struct game (plane fires waters)) ( make - game Plane List - of - fire List - of - water ) (define P1 (make-plane 0 -1)) (define P2 (make-plane WIDTH 1)) (define P3 (make-plane CENTER 1)) (define F0 '()) (define F1 (list (make-posn 75 FIRE-Y))) (define F2 (list (make-posn 650 FIRE-Y))) (define F3 (list (make-posn 110 135) (make-posn CENTER FIRE-Y))) (define W0 '()) (define W1 (list (make-posn 75 (- FIRE-Y HIT-RANGE)))) (define W2 (list (make-posn 590 100))) (define W3 (list (make-posn 214 253) (make-posn CENTER 183))) (define W4 (cons (make-posn 200 (+ HEIGHT (image-height WATER) 1)) W3)) (define GS0 (make-game P1 '() '())) (define GS1 (make-game P1 F1 W1)) (define GS2 (make-game P2 F2 W2)) (define GS3 (make-game P3 F3 W3)) (define GS4 (make-game P3 F3 W4)) (define GS-INIT (make-game (make-plane CENTER 1) '() '())) GameState - > GameState run with ( main GS - INIT ) (define (main gs) (big-bang gs [to-draw render-game] [on-tick next-game 1/28 (* TIME-LIMIT 28)] [on-key plane-control] [check-with is-gamestate?])) GameState - > Image (check-expect (render-game GS0) (render-plane P1 MTS)) (check-expect (render-game GS1) (render-plane P1 (render-posn-objs F1 FIRE (render-posn-objs W1 WATER MTS)))) (check-expect (render-game GS3) (render-plane P3 (render-posn-objs F3 FIRE (render-posn-objs W3 WATER MTS)))) (define (render-game gs) (render-plane (game-plane gs) (render-posn-objs (game-fires gs) FIRE (render-posn-objs (game-waters gs) WATER MTS)))) (check-expect (render-posn-objs F0 FIRE MTS) MTS) (check-expect (render-posn-objs F3 FIRE MTS) (place-image FIRE (posn-x (first F3)) (posn-y (first F3)) (place-image FIRE (posn-x (second F3)) (posn-y (second F3)) MTS))) (check-expect (render-posn-objs W0 WATER MTS) MTS) (check-expect (render-posn-objs W3 WATER MTS) (place-image WATER (posn-x (first W3)) (posn-y (first W3)) (place-image WATER (posn-x (second W3)) (posn-y (second W3)) MTS))) (define (render-posn-objs lop p-img img) (cond [(empty? lop) img] [else (place-image p-img (posn-x (first lop)) (posn-y (first lop)) (render-posn-objs (rest lop) p-img img))])) Plane Image - > Image (check-expect (render-plane P1 MTS) (place-image AIRPLANE-FLIP-LEFT (plane-x P1) AIRPLANE-Y MTS)) (check-expect (render-plane P2 MTS) (place-image AIRPLANE (plane-x P2) AIRPLANE-Y MTS)) (check-expect (render-plane P3 MTS) (place-image AIRPLANE (plane-x P3) AIRPLANE-Y MTS)) (define (render-plane p img) (if (= (plane-dir p) 1) (place-image AIRPLANE (plane-x p) AIRPLANE-Y img) (place-image AIRPLANE-FLIP-LEFT (plane-x p) AIRPLANE-Y img))) GameState - > GameState (define (next-game gs) (make-game (game-plane gs) (process-fires (game-fires gs) (game-waters gs)) (process-waterloads (game-waters gs) (game-fires gs)))) (define (process-fires lof low) (if (should-create? lof) (fire-create (cancel-out lof low)) (cancel-out lof low))) produces true if length of lof is below MAX - FIRES (define (should-create? lof) (and (<= (length lof) MAX-FIRES) (< (/ (random 1000) 1000) FIRE-SPAWN-PROBABILITY))) (check-satisfied (fire-create F0) proper?) (check-satisfied (fire-create F1) proper?) (define (fire-create lof) (fire-check-create (make-posn (random WIDTH) FIRE-Y) lof)) new Fire is generated at random until the currently generated one is not at the same position as the last one (define (fire-check-create f candidate) (if (close-proximity? f candidate) (fire-create candidate) (cons f candidate))) (check-expect (close-proximity? (make-posn 40 FIRE-Y) (list (make-posn 450 FIRE-Y) (make-posn 80 FIRE-Y))) #f) (check-expect (close-proximity? (make-posn 40 FIRE-Y) (list (make-posn (+ 40 MAX-FIRE-PROXIMITY) FIRE-Y) (make-posn 80 FIRE-Y))) #t) (define (close-proximity? f lof) (cond [(empty? lof) #f] [else (or (<= (abs (- (posn-x f) (posn-x (first lof)))) MAX-FIRE-PROXIMITY) (close-proximity? f (rest lof)))])) (define (proper? lof) (not (member? (first lof) (rest lof)))) waterloads that hit a fire get used ( removed from list ) , (check-expect (process-waterloads W0 F0) '()) (check-expect (process-waterloads W1 F1) '()) (check-expect (process-waterloads W1 F2) (list (make-posn (posn-x (first W1)) (+ (posn-y (first W1)) WATER-SPEED)))) (check-expect (process-waterloads W2 F2) (list (make-posn (posn-x (first W2)) (+ (posn-y (first W2)) WATER-SPEED)))) (check-expect (process-waterloads W3 F3) (list (make-posn (posn-x (first W3)) (+ (posn-y (first W3)) WATER-SPEED)) (make-posn (posn-x (second W3)) (+ (posn-y (second W3)) WATER-SPEED)))) (define (process-waterloads low lof) (drop-waterloads (cancel-out (filter-missed-waterloads low) lof))) (check-expect (drop-waterloads W2) (list (make-posn (posn-x (first W2)) (+ (posn-y (first W2)) WATER-SPEED)))) (check-expect (drop-waterloads W3) (list (make-posn (posn-x (first W3)) (+ (posn-y (first W3)) WATER-SPEED)) (make-posn (posn-x (second W3)) (+ (posn-y (second W3)) WATER-SPEED)))) (define (drop-waterloads low) (cond [(empty? low) '()] [else (cons (make-posn (posn-x (first low)) (+ (posn-y (first low)) WATER-SPEED)) (drop-waterloads (rest low)))])) only keeps the waterloads that are still visible in the scene (check-expect (filter-missed-waterloads W3) W3) (check-expect (filter-missed-waterloads W4) W3) (define (filter-missed-waterloads low) (cond [(empty? low) '()] [else (if (>= (posn-y (first low)) (+ HEIGHT (image-height WATER))) (filter-missed-waterloads (rest low)) (cons (first low) (filter-missed-waterloads (rest low))))])) removes all posns in that are " too close " to any posns in lopb (check-expect (cancel-out (list (make-posn 23 50) (make-posn 63 79)) (list (make-posn 20 51) (make-posn 80 100))) (list (make-posn 63 79))) (check-expect (cancel-out (list (make-posn 23 50) (make-posn 63 79)) (list (make-posn 200 51) (make-posn 80 100))) (list (make-posn 23 50) (make-posn 63 79))) (define (cancel-out lopa lopb) (cond [(empty? lopa) '()] [else (if (hit? (first lopa) lopb) (cancel-out (rest lopa) lopb) (cons (first lopa) (cancel-out (rest lopa) lopb)))])) produces true if p is close enough to any posn in lop (check-expect (hit? (make-posn 23 50) (list (make-posn 20 51) (make-posn 80 100))) #t) (check-expect (hit? (make-posn 23 50) (list (make-posn 200 51) (make-posn 80 100))) #f) (define (hit? w lof) (cond [(empty? lof) #f] [else (or (close? w (first lof)) (hit? w (rest lof)))])) (check-expect (close? (make-posn 42 42) (make-posn 30 70)) #f) (check-expect (close? (make-posn 50 120) (make-posn 50 119)) #t) (check-expect (close? (make-posn 30 70) (make-posn 30 70)) #t) (define (close? p1 p2) (<= (distance p1 p2) HIT-RANGE)) calculates the Eucledian distance between two posns (check-expect (round (distance (make-posn 0 4) (make-posn 3 0))) 5) (check-expect (round (distance (make-posn 12 48) (make-posn 34 28))) 30) (define (distance a b) (inexact->exact (sqrt (+ (sqr (- (posn-y a) (posn-y b))) (sqr (- (posn-x a) (posn-x b))))))) Plane Direction - > Plane (check-expect (plane-translate P1 1) (make-plane (+ (plane-x P1) AIRPLANE-SPEED) 1)) (check-expect (plane-translate P1 -1) (make-plane (+ (plane-x P1) (* AIRPLANE-SPEED (plane-dir P1))) -1)) (check-expect (plane-translate P2 1) (make-plane (+ (plane-x P2) (* AIRPLANE-SPEED (plane-dir P2))) 1)) (check-expect (plane-translate P2 -1) (make-plane (- (plane-x P2) AIRPLANE-SPEED) -1)) (define (plane-translate p dir) (cond [(= dir (plane-dir p)) (make-plane (+ (plane-x p) (* AIRPLANE-SPEED (plane-dir p))) (plane-dir p))] [(and (= dir 1) (= (plane-dir p) -1)) (make-plane (+ (plane-x p) AIRPLANE-SPEED) 1)] [(and (= dir -1) (= (plane-dir p) 1)) (make-plane (- (plane-x p) AIRPLANE-SPEED) -1)])) GameState KeyEvent - > GameState " " drops waterloads (check-expect (plane-control GS0 "left") GS0) (check-expect (plane-control GS0 "right") (make-game (plane-translate P1 1) (game-fires GS0) (game-waters GS0))) (check-expect (plane-control GS2 "right") GS2) (check-expect (plane-control GS2 "left") (make-game (plane-translate P2 -1) (game-fires GS2) (game-waters GS2))) (check-expect (plane-control GS3 "down") GS3) (check-expect (plane-control GS3 "a") GS3) (check-expect (plane-control GS3 "right") (make-game (plane-translate P3 1) (game-fires GS3) (game-waters GS3))) (check-expect (plane-control GS3 "left") (make-game (plane-translate P3 -1) (game-fires GS3) (game-waters GS3))) (check-expect (plane-control GS3 " ") (make-game (game-plane GS3) (game-fires GS3) (cons (make-posn (plane-x (game-plane GS3)) (+ AIRPLANE-Y AIRPLANE-HEIGHT)) (game-waters GS3)))) (define (plane-control gs ke) (cond [(and (key=? ke "left") (not (<= (plane-x (game-plane gs)) 0))) (make-game (plane-translate (game-plane gs) -1) (game-fires gs) (game-waters gs))] [(and (key=? ke "right") (not (>= (plane-x (game-plane gs)) WIDTH))) (make-game (plane-translate (game-plane gs) 1) (game-fires gs) (game-waters gs))] [(key=? ke " ") (make-game (game-plane gs) (game-fires gs) (cons (make-posn (plane-x (game-plane gs)) (+ AIRPLANE-Y AIRPLANE-HEIGHT)) (game-waters gs)))] [else gs])) GameState - > Boolean (define (is-gamestate? gs) (game? gs))
df3996ce2b93c1ece40214156c8c40bc14652cd431cce738d2b450edbe23f8d9
mmark-md/mmark-ext
KbdSpec.hs
{-# LANGUAGE OverloadedStrings #-} module Text.MMark.Extension.KbdSpec (spec) where import Test.Hspec import Text.MMark.Extension.Kbd import Text.MMark.Extension.TestUtils spec :: Spec spec = describe "kbd" $ do let to = withExt kbd it "works" $ "Press [Ctrl+A](kbd:)" `to` "<p>Press <kbd>Ctrl+A</kbd></p>\n"
null
https://raw.githubusercontent.com/mmark-md/mmark-ext/cc7d035224d32a6133789d65cd0e130bcdbf8d2c/tests/Text/MMark/Extension/KbdSpec.hs
haskell
# LANGUAGE OverloadedStrings #
module Text.MMark.Extension.KbdSpec (spec) where import Test.Hspec import Text.MMark.Extension.Kbd import Text.MMark.Extension.TestUtils spec :: Spec spec = describe "kbd" $ do let to = withExt kbd it "works" $ "Press [Ctrl+A](kbd:)" `to` "<p>Press <kbd>Ctrl+A</kbd></p>\n"
25579d1078255f425e6a9c4c00d1e517b98d63917932a935de7ebd3684f3db5a
tweag/asterius
drvrun011.hs
-- Tests some simple deriving stuff, and built-in instances module Main( main ) where data Command = Commit (Maybe String) | Foo | Baz Bool | Boz Int deriving (Read,Show) type T = ([Command], [Command], [Command]) val :: T val = ([Commit Nothing, Commit (Just "foo")], [Foo, Baz True], [Boz 3, Boz (-2)]) main = do { print val ; print ((read (show val)) :: T) }
null
https://raw.githubusercontent.com/tweag/asterius/e7b823c87499656860f87b9b468eb0567add1de8/asterius/test/ghc-testsuite/deriving/drvrun011.hs
haskell
Tests some simple deriving stuff, and built-in instances
module Main( main ) where data Command = Commit (Maybe String) | Foo | Baz Bool | Boz Int deriving (Read,Show) type T = ([Command], [Command], [Command]) val :: T val = ([Commit Nothing, Commit (Just "foo")], [Foo, Baz True], [Boz 3, Boz (-2)]) main = do { print val ; print ((read (show val)) :: T) }
8b7fbeed2dc71fbeb0fb76c1e216c7be3f0ed7451dd0f3b4a2e589ed648655b1
xh4/web-toolkit
crc24.lisp
;;;; -*- mode: lisp; indent-tabs-mode: nil -*- ;;;; crc24.lisp (in-package :crypto) (in-ironclad-readtable) (declaim (type (simple-array (unsigned-byte 32) (256)) +crc24-table+)) (defconst +crc24-table+ #32@(#x00000000 #x00864CFB #x008AD50D #x000C99F6 #x0093E6E1 #x0015AA1A #x001933EC #x009F7F17 #x00A18139 #x0027CDC2 #x002B5434 #x00AD18CF #x003267D8 #x00B42B23 #x00B8B2D5 #x003EFE2E #x00C54E89 #x00430272 #x004F9B84 #x00C9D77F #x0056A868 #x00D0E493 #x00DC7D65 #x005A319E #x0064CFB0 #x00E2834B #x00EE1ABD #x00685646 #x00F72951 #x007165AA #x007DFC5C #x00FBB0A7 #x000CD1E9 #x008A9D12 #x008604E4 #x0000481F #x009F3708 #x00197BF3 #x0015E205 #x0093AEFE #x00AD50D0 #x002B1C2B #x002785DD #x00A1C926 #x003EB631 #x00B8FACA #x00B4633C #x00322FC7 #x00C99F60 #x004FD39B #x00434A6D #x00C50696 #x005A7981 #x00DC357A #x00D0AC8C #x0056E077 #x00681E59 #x00EE52A2 #x00E2CB54 #x006487AF #x00FBF8B8 #x007DB443 #x00712DB5 #x00F7614E #x0019A3D2 #x009FEF29 #x009376DF #x00153A24 #x008A4533 #x000C09C8 #x0000903E #x0086DCC5 #x00B822EB #x003E6E10 #x0032F7E6 #x00B4BB1D #x002BC40A #x00AD88F1 #x00A11107 #x00275DFC #x00DCED5B #x005AA1A0 #x00563856 #x00D074AD #x004F0BBA #x00C94741 #x00C5DEB7 #x0043924C #x007D6C62 #x00FB2099 #x00F7B96F #x0071F594 #x00EE8A83 #x0068C678 #x00645F8E #x00E21375 #x0015723B #x00933EC0 #x009FA736 #x0019EBCD #x008694DA #x0000D821 #x000C41D7 #x008A0D2C #x00B4F302 #x0032BFF9 #x003E260F #x00B86AF4 #x002715E3 #x00A15918 #x00ADC0EE #x002B8C15 #x00D03CB2 #x00567049 #x005AE9BF #x00DCA544 #x0043DA53 #x00C596A8 #x00C90F5E #x004F43A5 #x0071BD8B #x00F7F170 #x00FB6886 #x007D247D #x00E25B6A #x00641791 #x00688E67 #x00EEC29C #x003347A4 #x00B50B5F #x00B992A9 #x003FDE52 #x00A0A145 #x0026EDBE #x002A7448 #x00AC38B3 #x0092C69D #x00148A66 #x00181390 #x009E5F6B #x0001207C #x00876C87 #x008BF571 #x000DB98A #x00F6092D #x007045D6 #x007CDC20 #x00FA90DB #x0065EFCC #x00E3A337 #x00EF3AC1 #x0069763A #x00578814 #x00D1C4EF #x00DD5D19 #x005B11E2 #x00C46EF5 #x0042220E #x004EBBF8 #x00C8F703 #x003F964D #x00B9DAB6 #x00B54340 #x00330FBB #x00AC70AC #x002A3C57 #x0026A5A1 #x00A0E95A #x009E1774 #x00185B8F #x0014C279 #x00928E82 #x000DF195 #x008BBD6E #x00872498 #x00016863 #x00FAD8C4 #x007C943F #x00700DC9 #x00F64132 #x00693E25 #x00EF72DE #x00E3EB28 #x0065A7D3 #x005B59FD #x00DD1506 #x00D18CF0 #x0057C00B #x00C8BF1C #x004EF3E7 #x00426A11 #x00C426EA #x002AE476 #x00ACA88D #x00A0317B #x00267D80 #x00B90297 #x003F4E6C #x0033D79A #x00B59B61 #x008B654F #x000D29B4 #x0001B042 #x0087FCB9 #x001883AE #x009ECF55 #x009256A3 #x00141A58 #x00EFAAFF #x0069E604 #x00657FF2 #x00E33309 #x007C4C1E #x00FA00E5 #x00F69913 #x0070D5E8 #x004E2BC6 #x00C8673D #x00C4FECB #x0042B230 #x00DDCD27 #x005B81DC #x0057182A #x00D154D1 #x0026359F #x00A07964 #x00ACE092 #x002AAC69 #x00B5D37E #x00339F85 #x003F0673 #x00B94A88 #x0087B4A6 #x0001F85D #x000D61AB #x008B2D50 #x00145247 #x00921EBC #x009E874A #x0018CBB1 #x00E37B16 #x006537ED #x0069AE1B #x00EFE2E0 #x00709DF7 #x00F6D10C #x00FA48FA #x007C0401 #x0042FA2F #x00C4B6D4 #x00C82F22 #x004E63D9 #x00D11CCE #x00575035 #x005BC9C3 #x00DD8538)) (defstruct (crc24 (:constructor %make-crc24-digest nil) (:constructor %make-crc24-state (crc)) (:copier nil)) (crc #xb704ce :type (unsigned-byte 32))) (defmethod reinitialize-instance ((state crc24) &rest initargs) (declare (ignore initargs)) (setf (crc24-crc state) #xb704ce) state) (defmethod copy-digest ((state crc24) &optional copy) (declare (type (or null crc24) copy)) (cond (copy (setf (crc24-crc copy) (crc24-crc state)) copy) (t (%make-crc24-state (crc24-crc state))))) (define-digest-updater crc24 (let ((crc (crc24-crc state))) (declare (type (unsigned-byte 32) crc)) (do ((i start (1+ i)) (table +crc24-table+)) ((>= i end) (setf (crc24-crc state) (ldb (byte 24 0) crc)) state) (setf crc (logxor (aref table (logand (logxor (mod32ash crc -16) (aref sequence i)) #xff)) (mod32ash crc 8)))))) (define-digest-finalizer (crc24 3) (flet ((stuff-state (crc digest start) (declare (type (simple-array (unsigned-byte 8) (*)) digest)) (declare (type (integer 0 #.(- array-dimension-limit 3)) start)) (setf (aref digest (+ start 0)) (ldb (byte 8 16) crc) (aref digest (+ start 1)) (ldb (byte 8 8) crc) (aref digest (+ start 2)) (ldb (byte 8 0) crc)) digest)) (declare (inline stuff-state)) (stuff-state (crc24-crc state) digest digest-start))) (defdigest crc24 :digest-length 3 :block-length 1)
null
https://raw.githubusercontent.com/xh4/web-toolkit/e510d44a25b36ca8acd66734ed1ee9f5fe6ecd09/vendor/ironclad-v0.47/src/digests/crc24.lisp
lisp
-*- mode: lisp; indent-tabs-mode: nil -*- crc24.lisp
(in-package :crypto) (in-ironclad-readtable) (declaim (type (simple-array (unsigned-byte 32) (256)) +crc24-table+)) (defconst +crc24-table+ #32@(#x00000000 #x00864CFB #x008AD50D #x000C99F6 #x0093E6E1 #x0015AA1A #x001933EC #x009F7F17 #x00A18139 #x0027CDC2 #x002B5434 #x00AD18CF #x003267D8 #x00B42B23 #x00B8B2D5 #x003EFE2E #x00C54E89 #x00430272 #x004F9B84 #x00C9D77F #x0056A868 #x00D0E493 #x00DC7D65 #x005A319E #x0064CFB0 #x00E2834B #x00EE1ABD #x00685646 #x00F72951 #x007165AA #x007DFC5C #x00FBB0A7 #x000CD1E9 #x008A9D12 #x008604E4 #x0000481F #x009F3708 #x00197BF3 #x0015E205 #x0093AEFE #x00AD50D0 #x002B1C2B #x002785DD #x00A1C926 #x003EB631 #x00B8FACA #x00B4633C #x00322FC7 #x00C99F60 #x004FD39B #x00434A6D #x00C50696 #x005A7981 #x00DC357A #x00D0AC8C #x0056E077 #x00681E59 #x00EE52A2 #x00E2CB54 #x006487AF #x00FBF8B8 #x007DB443 #x00712DB5 #x00F7614E #x0019A3D2 #x009FEF29 #x009376DF #x00153A24 #x008A4533 #x000C09C8 #x0000903E #x0086DCC5 #x00B822EB #x003E6E10 #x0032F7E6 #x00B4BB1D #x002BC40A #x00AD88F1 #x00A11107 #x00275DFC #x00DCED5B #x005AA1A0 #x00563856 #x00D074AD #x004F0BBA #x00C94741 #x00C5DEB7 #x0043924C #x007D6C62 #x00FB2099 #x00F7B96F #x0071F594 #x00EE8A83 #x0068C678 #x00645F8E #x00E21375 #x0015723B #x00933EC0 #x009FA736 #x0019EBCD #x008694DA #x0000D821 #x000C41D7 #x008A0D2C #x00B4F302 #x0032BFF9 #x003E260F #x00B86AF4 #x002715E3 #x00A15918 #x00ADC0EE #x002B8C15 #x00D03CB2 #x00567049 #x005AE9BF #x00DCA544 #x0043DA53 #x00C596A8 #x00C90F5E #x004F43A5 #x0071BD8B #x00F7F170 #x00FB6886 #x007D247D #x00E25B6A #x00641791 #x00688E67 #x00EEC29C #x003347A4 #x00B50B5F #x00B992A9 #x003FDE52 #x00A0A145 #x0026EDBE #x002A7448 #x00AC38B3 #x0092C69D #x00148A66 #x00181390 #x009E5F6B #x0001207C #x00876C87 #x008BF571 #x000DB98A #x00F6092D #x007045D6 #x007CDC20 #x00FA90DB #x0065EFCC #x00E3A337 #x00EF3AC1 #x0069763A #x00578814 #x00D1C4EF #x00DD5D19 #x005B11E2 #x00C46EF5 #x0042220E #x004EBBF8 #x00C8F703 #x003F964D #x00B9DAB6 #x00B54340 #x00330FBB #x00AC70AC #x002A3C57 #x0026A5A1 #x00A0E95A #x009E1774 #x00185B8F #x0014C279 #x00928E82 #x000DF195 #x008BBD6E #x00872498 #x00016863 #x00FAD8C4 #x007C943F #x00700DC9 #x00F64132 #x00693E25 #x00EF72DE #x00E3EB28 #x0065A7D3 #x005B59FD #x00DD1506 #x00D18CF0 #x0057C00B #x00C8BF1C #x004EF3E7 #x00426A11 #x00C426EA #x002AE476 #x00ACA88D #x00A0317B #x00267D80 #x00B90297 #x003F4E6C #x0033D79A #x00B59B61 #x008B654F #x000D29B4 #x0001B042 #x0087FCB9 #x001883AE #x009ECF55 #x009256A3 #x00141A58 #x00EFAAFF #x0069E604 #x00657FF2 #x00E33309 #x007C4C1E #x00FA00E5 #x00F69913 #x0070D5E8 #x004E2BC6 #x00C8673D #x00C4FECB #x0042B230 #x00DDCD27 #x005B81DC #x0057182A #x00D154D1 #x0026359F #x00A07964 #x00ACE092 #x002AAC69 #x00B5D37E #x00339F85 #x003F0673 #x00B94A88 #x0087B4A6 #x0001F85D #x000D61AB #x008B2D50 #x00145247 #x00921EBC #x009E874A #x0018CBB1 #x00E37B16 #x006537ED #x0069AE1B #x00EFE2E0 #x00709DF7 #x00F6D10C #x00FA48FA #x007C0401 #x0042FA2F #x00C4B6D4 #x00C82F22 #x004E63D9 #x00D11CCE #x00575035 #x005BC9C3 #x00DD8538)) (defstruct (crc24 (:constructor %make-crc24-digest nil) (:constructor %make-crc24-state (crc)) (:copier nil)) (crc #xb704ce :type (unsigned-byte 32))) (defmethod reinitialize-instance ((state crc24) &rest initargs) (declare (ignore initargs)) (setf (crc24-crc state) #xb704ce) state) (defmethod copy-digest ((state crc24) &optional copy) (declare (type (or null crc24) copy)) (cond (copy (setf (crc24-crc copy) (crc24-crc state)) copy) (t (%make-crc24-state (crc24-crc state))))) (define-digest-updater crc24 (let ((crc (crc24-crc state))) (declare (type (unsigned-byte 32) crc)) (do ((i start (1+ i)) (table +crc24-table+)) ((>= i end) (setf (crc24-crc state) (ldb (byte 24 0) crc)) state) (setf crc (logxor (aref table (logand (logxor (mod32ash crc -16) (aref sequence i)) #xff)) (mod32ash crc 8)))))) (define-digest-finalizer (crc24 3) (flet ((stuff-state (crc digest start) (declare (type (simple-array (unsigned-byte 8) (*)) digest)) (declare (type (integer 0 #.(- array-dimension-limit 3)) start)) (setf (aref digest (+ start 0)) (ldb (byte 8 16) crc) (aref digest (+ start 1)) (ldb (byte 8 8) crc) (aref digest (+ start 2)) (ldb (byte 8 0) crc)) digest)) (declare (inline stuff-state)) (stuff-state (crc24-crc state) digest digest-start))) (defdigest crc24 :digest-length 3 :block-length 1)
04a2d9b2ede9f58dfa62e1a2898b88dda083bbfc32b4e05f14979a92f36fedb6
FieryCod/holy-lambda
publish.clj
(require '[selmer.parser :as selm]) (require '[babashka.process :as p]) (require '[clojure.string :as s]) (def ARM64 "arm64") (def AMD64 "amd64") (def ARCHS #{ARM64 AMD64}) (def FILES #{"README.md.template" "Dockerfile.bb.template" "template.yml.template"}) (def BABASHKA_VERSION "0.9.162") (def SEMANTIC_VERSION "0.7.0") (defn arch->subcord [arch] (get {"arm64" "aarch64" "amd64" "amd64"} arch)) (defn template->filename [template arch] (let [[file ext] (s/split (subs template 0 (- (count template) 9)) #"\.")] (str file "-" arch "." ext))) (defn render [template arch] (spit (template->filename template arch) (selm/render (slurp template) {:arch arch :semantic-version SEMANTIC_VERSION :babashka-version BABASHKA_VERSION :aarch (arch->subcord arch) :arch_is (if (= arch "arm64") "arm64" "x86_64")}))) (defn- shell [cmd] @(p/process (p/tokenize cmd) {:inherit true})) (def task (first *command-line-args*)) (when (or (= task "render") (= task "all")) (doseq [arch ARCHS] (doseq [file FILES] (render file arch)))) (when (or (= task "build") (= task "all")) (doseq [arch ARCHS] (shell (str "docker build . --target BUILDER -t holy-lambda-babashka-layer-" arch " -f Dockerfile-" arch ".bb")) (shell "bash -c \"docker rm build || true\"") (shell (str "docker create --name build holy-lambda-babashka-layer-" arch)) (shell (str "docker cp build:/opt/holy-lambda-babashka-runtime-" arch ".zip holy-lambda-babashka-runtime-" arch ".zip")) (shell "bash -c \"docker rm build || true\"") (shell (str "docker image rm -f holy-lambda-babashka-layer-" arch)))) (when (or (= task "publish") (= task "all")) (doseq [arch ARCHS] (let [arch arch version SEMANTIC_VERSION s3 "holy-lambda-babashka-layer" s3-prefix "holy-lambda" region "eu-central-1" babashka-version BABASHKA_VERSION semantic-version SEMANTIC_VERSION] (shell (selm/<< "sam package --template-file template-{{arch}}.yml --output-template-file packaged-{{arch}}.yml --s3-bucket {{s3}} --s3-prefix {{s3-prefix}}")) (shell (selm/<< "sam publish --template-file packaged-{{arch}}.yml --semantic-version {{version}}")))))
null
https://raw.githubusercontent.com/FieryCod/holy-lambda/e695797d21163d7e5f2b3818bf5abfc905f41376/modules/holy-lambda-babashka-layer/publish.clj
clojure
(require '[selmer.parser :as selm]) (require '[babashka.process :as p]) (require '[clojure.string :as s]) (def ARM64 "arm64") (def AMD64 "amd64") (def ARCHS #{ARM64 AMD64}) (def FILES #{"README.md.template" "Dockerfile.bb.template" "template.yml.template"}) (def BABASHKA_VERSION "0.9.162") (def SEMANTIC_VERSION "0.7.0") (defn arch->subcord [arch] (get {"arm64" "aarch64" "amd64" "amd64"} arch)) (defn template->filename [template arch] (let [[file ext] (s/split (subs template 0 (- (count template) 9)) #"\.")] (str file "-" arch "." ext))) (defn render [template arch] (spit (template->filename template arch) (selm/render (slurp template) {:arch arch :semantic-version SEMANTIC_VERSION :babashka-version BABASHKA_VERSION :aarch (arch->subcord arch) :arch_is (if (= arch "arm64") "arm64" "x86_64")}))) (defn- shell [cmd] @(p/process (p/tokenize cmd) {:inherit true})) (def task (first *command-line-args*)) (when (or (= task "render") (= task "all")) (doseq [arch ARCHS] (doseq [file FILES] (render file arch)))) (when (or (= task "build") (= task "all")) (doseq [arch ARCHS] (shell (str "docker build . --target BUILDER -t holy-lambda-babashka-layer-" arch " -f Dockerfile-" arch ".bb")) (shell "bash -c \"docker rm build || true\"") (shell (str "docker create --name build holy-lambda-babashka-layer-" arch)) (shell (str "docker cp build:/opt/holy-lambda-babashka-runtime-" arch ".zip holy-lambda-babashka-runtime-" arch ".zip")) (shell "bash -c \"docker rm build || true\"") (shell (str "docker image rm -f holy-lambda-babashka-layer-" arch)))) (when (or (= task "publish") (= task "all")) (doseq [arch ARCHS] (let [arch arch version SEMANTIC_VERSION s3 "holy-lambda-babashka-layer" s3-prefix "holy-lambda" region "eu-central-1" babashka-version BABASHKA_VERSION semantic-version SEMANTIC_VERSION] (shell (selm/<< "sam package --template-file template-{{arch}}.yml --output-template-file packaged-{{arch}}.yml --s3-bucket {{s3}} --s3-prefix {{s3-prefix}}")) (shell (selm/<< "sam publish --template-file packaged-{{arch}}.yml --semantic-version {{version}}")))))
1237aaabff9bb9de5e45a4e2cc357a3f63867deaf79bfe19ce5bbd537dbb57be
orionsbelt-battlegrounds/obb-rules
translator.cljc
(ns obb-rules.translator (:require [obb-rules.board :as board] [obb-rules.simplifier :as simplify] [obb-rules.laws :as laws] [obb-rules.element :as element])) (def max-coordinate (+ 1 laws/default-board-w)) (defn- default-focus? "Checks if the current given focus is the default one" [focus] (simplify/name= :p1 focus)) (defn coordinate "Translates a coordinate for a given player focus" [focus [x y]] (if (default-focus? focus) [x y] [(- max-coordinate x) (- max-coordinate y)])) (defn direction "Translates a direction for a given player focus" [focus dir] (if (default-focus? focus) dir (cond (= (keyword dir) :south) :north (= (keyword dir) :north) :south (= (keyword dir) :west) :east (= (keyword dir) :east) :west))) (defn element "Translates an element for a given player focus" [focus element] (if (default-focus? focus) element (let [dir (element/element-direction element) coord (element/element-coordinate element)] (-> (element/element-coordinate element (coordinate focus coord)) (element/element-direction (direction focus dir)))))) (defmulti convert-action (fn [x] (keyword (first x)))) (defmethod convert-action :rotate [action] [:rotate (coordinate :p2 (get action 1)) (direction :p2 (get action 2))]) (defmethod convert-action :move [action] [:move (coordinate :p2 (get action 1)) (coordinate :p2 (get action 2)) (get action 3)]) (defmethod convert-action :go-to [action] [:go-to (coordinate :p2 (get action 1)) (coordinate :p2 (get action 2))]) (defmethod convert-action :attack [action] [:attack (coordinate :p2 (get action 1)) (coordinate :p2 (get action 2))]) (defmethod convert-action :deploy [action] [:deploy (get action 1) (get action 2) (coordinate :p2 (get action 3))]) (defn action "Translates an action for a given player focus" [focus action] (if (default-focus? focus) action (convert-action action))) (defn actions "Translates all actions for a given player focus" [focus actions] (map (partial action focus) actions)) (defn- convert-board "Converts a board to :p2 focus" [board] (let [elements (board/elements board) translated (into {} (for [[k v] elements] [(coordinate :p2 k) (element :p2 v)]))] (board/elements board translated))) (defn board "Translates a full board to a given player focus" [focus board] (if (default-focus? focus) board (convert-board board)))
null
https://raw.githubusercontent.com/orionsbelt-battlegrounds/obb-rules/97fad6506eb81142f74f4722aca58b80d618bf45/src/obb_rules/translator.cljc
clojure
(ns obb-rules.translator (:require [obb-rules.board :as board] [obb-rules.simplifier :as simplify] [obb-rules.laws :as laws] [obb-rules.element :as element])) (def max-coordinate (+ 1 laws/default-board-w)) (defn- default-focus? "Checks if the current given focus is the default one" [focus] (simplify/name= :p1 focus)) (defn coordinate "Translates a coordinate for a given player focus" [focus [x y]] (if (default-focus? focus) [x y] [(- max-coordinate x) (- max-coordinate y)])) (defn direction "Translates a direction for a given player focus" [focus dir] (if (default-focus? focus) dir (cond (= (keyword dir) :south) :north (= (keyword dir) :north) :south (= (keyword dir) :west) :east (= (keyword dir) :east) :west))) (defn element "Translates an element for a given player focus" [focus element] (if (default-focus? focus) element (let [dir (element/element-direction element) coord (element/element-coordinate element)] (-> (element/element-coordinate element (coordinate focus coord)) (element/element-direction (direction focus dir)))))) (defmulti convert-action (fn [x] (keyword (first x)))) (defmethod convert-action :rotate [action] [:rotate (coordinate :p2 (get action 1)) (direction :p2 (get action 2))]) (defmethod convert-action :move [action] [:move (coordinate :p2 (get action 1)) (coordinate :p2 (get action 2)) (get action 3)]) (defmethod convert-action :go-to [action] [:go-to (coordinate :p2 (get action 1)) (coordinate :p2 (get action 2))]) (defmethod convert-action :attack [action] [:attack (coordinate :p2 (get action 1)) (coordinate :p2 (get action 2))]) (defmethod convert-action :deploy [action] [:deploy (get action 1) (get action 2) (coordinate :p2 (get action 3))]) (defn action "Translates an action for a given player focus" [focus action] (if (default-focus? focus) action (convert-action action))) (defn actions "Translates all actions for a given player focus" [focus actions] (map (partial action focus) actions)) (defn- convert-board "Converts a board to :p2 focus" [board] (let [elements (board/elements board) translated (into {} (for [[k v] elements] [(coordinate :p2 k) (element :p2 v)]))] (board/elements board translated))) (defn board "Translates a full board to a given player focus" [focus board] (if (default-focus? focus) board (convert-board board)))
fea38a9225021df8c181015f35581ade646c8d32e2a9ba1de748b5e941cc1c36
SoftwareFoundationGroupAtKyotoU/VeriCUDA
vc.ml
open Why3.Term module Varinfo = struct type t = Cil.varinfo let compare v1 v2 = compare v1.Cil.vid v2.Cil.vid end module VarinfoMap : (Map.S with type key = Cil.varinfo) = Map.Make(Varinfo) module OrderedString = struct type t = string let compare : string -> string -> int = compare end module StrMap : (Map.S with type key = string) = Map.Make(OrderedString) type assignment_info = { a_newvar : lsymbol; a_oldvar : lsymbol; a_mask : term -> term; a_index : term -> term; a_rhs : term -> term; a_mkind : Formula.var_kind; } type declaration = (* automatically generated variable *) | VarDecl of lsymbol (* automatically generated assumption *) | AxiomDecl of term * string option (* assignment *) | AsgnDecl of assignment_info let axiom_decl ?(name) t = AxiomDecl (t, name) type vc = { (* vc_asgn : assignment_info list; *) vc_decls : declaration list; vc_goal : term; vc_name : string option; }
null
https://raw.githubusercontent.com/SoftwareFoundationGroupAtKyotoU/VeriCUDA/8c62058af5362cb1bd6c86121d9b8742e31706f2/vc.ml
ocaml
automatically generated variable automatically generated assumption assignment vc_asgn : assignment_info list;
open Why3.Term module Varinfo = struct type t = Cil.varinfo let compare v1 v2 = compare v1.Cil.vid v2.Cil.vid end module VarinfoMap : (Map.S with type key = Cil.varinfo) = Map.Make(Varinfo) module OrderedString = struct type t = string let compare : string -> string -> int = compare end module StrMap : (Map.S with type key = string) = Map.Make(OrderedString) type assignment_info = { a_newvar : lsymbol; a_oldvar : lsymbol; a_mask : term -> term; a_index : term -> term; a_rhs : term -> term; a_mkind : Formula.var_kind; } type declaration = | VarDecl of lsymbol | AxiomDecl of term * string option | AsgnDecl of assignment_info let axiom_decl ?(name) t = AxiomDecl (t, name) type vc = { vc_decls : declaration list; vc_goal : term; vc_name : string option; }
1ac240f81f6052c7499f307e6dc65fe4759b6e3b32a81b570d5c353e45640358
rabbitmq/rabbitmq-stomp
command_SUITE.erl
This Source Code Form is subject to the terms of the Mozilla Public License , v. 2.0 . If a copy of the MPL was not distributed with this file , You can obtain one at /. %% Copyright ( c ) 2007 - 2020 VMware , Inc. or its affiliates . All rights reserved . %% -module(command_SUITE). -compile([export_all]). -include_lib("common_test/include/ct.hrl"). -include_lib("eunit/include/eunit.hrl"). -include_lib("amqp_client/include/amqp_client.hrl"). -include("rabbit_stomp.hrl"). -define(COMMAND, 'Elixir.RabbitMQ.CLI.Ctl.Commands.ListStompConnectionsCommand'). all() -> [ {group, non_parallel_tests} ]. groups() -> [ {non_parallel_tests, [], [ merge_defaults, run ]} ]. init_per_suite(Config) -> Config1 = rabbit_ct_helpers:set_config(Config, [{rmq_nodename_suffix, ?MODULE}]), rabbit_ct_helpers:log_environment(), rabbit_ct_helpers:run_setup_steps(Config1, rabbit_ct_broker_helpers:setup_steps()). end_per_suite(Config) -> rabbit_ct_helpers:run_teardown_steps(Config, rabbit_ct_broker_helpers:teardown_steps()). init_per_group(_, Config) -> Config. end_per_group(_, Config) -> Config. init_per_testcase(Testcase, Config) -> rabbit_ct_helpers:testcase_started(Config, Testcase). end_per_testcase(Testcase, Config) -> rabbit_ct_helpers:testcase_finished(Config, Testcase). merge_defaults(_Config) -> {[<<"session_id">>, <<"conn_name">>], #{verbose := false}} = ?COMMAND:merge_defaults([], #{}), {[<<"other_key">>], #{verbose := true}} = ?COMMAND:merge_defaults([<<"other_key">>], #{verbose => true}), {[<<"other_key">>], #{verbose := false}} = ?COMMAND:merge_defaults([<<"other_key">>], #{verbose => false}). run(Config) -> Node = rabbit_ct_broker_helpers:get_node_config(Config, 0, nodename), Opts = #{node => Node, timeout => 10000, verbose => false}, %% No connections [] = 'Elixir.Enum':to_list(?COMMAND:run([], Opts)), StompPort = rabbit_ct_broker_helpers:get_node_config(Config, 0, tcp_port_stomp), {ok, _Client} = rabbit_stomp_client:connect(StompPort), ct:sleep(100), [[{session_id, _}]] = 'Elixir.Enum':to_list(?COMMAND:run([<<"session_id">>], Opts)), {ok, _Client2} = rabbit_stomp_client:connect(StompPort), ct:sleep(100), [[{session_id, _}], [{session_id, _}]] = 'Elixir.Enum':to_list(?COMMAND:run([<<"session_id">>], Opts)), Port = rabbit_ct_broker_helpers:get_node_config(Config, 0, tcp_port_amqp), start_amqp_connection(network, Node, Port), There are still just two connections [[{session_id, _}], [{session_id, _}]] = 'Elixir.Enum':to_list(?COMMAND:run([<<"session_id">>], Opts)), start_amqp_connection(direct, Node, Port), Still two MQTT connections , one direct AMQP 0 - 9 - 1 connection [[{session_id, _}], [{session_id, _}]] = 'Elixir.Enum':to_list(?COMMAND:run([<<"session_id">>], Opts)), Verbose returns all keys Infos = lists:map(fun(El) -> atom_to_binary(El, utf8) end, ?INFO_ITEMS), AllKeys = 'Elixir.Enum':to_list(?COMMAND:run(Infos, Opts)), AllKeys = 'Elixir.Enum':to_list(?COMMAND:run([], Opts#{verbose => true})), There are two connections [First, _Second] = AllKeys, Keys are INFO_ITEMS KeysCount = length(?INFO_ITEMS), KeysCount = length(First), {Keys, _} = lists:unzip(First), [] = Keys -- ?INFO_ITEMS, [] = ?INFO_ITEMS -- Keys. start_amqp_connection(Type, Node, Port) -> Params = amqp_params(Type, Node, Port), {ok, _Connection} = amqp_connection:start(Params). amqp_params(network, _, Port) -> #amqp_params_network{port = Port}; amqp_params(direct, Node, _) -> #amqp_params_direct{node = Node}.
null
https://raw.githubusercontent.com/rabbitmq/rabbitmq-stomp/925d78e2c7152723a68452b38fbc2713d2797b8b/test/command_SUITE.erl
erlang
No connections
This Source Code Form is subject to the terms of the Mozilla Public License , v. 2.0 . If a copy of the MPL was not distributed with this file , You can obtain one at /. Copyright ( c ) 2007 - 2020 VMware , Inc. or its affiliates . All rights reserved . -module(command_SUITE). -compile([export_all]). -include_lib("common_test/include/ct.hrl"). -include_lib("eunit/include/eunit.hrl"). -include_lib("amqp_client/include/amqp_client.hrl"). -include("rabbit_stomp.hrl"). -define(COMMAND, 'Elixir.RabbitMQ.CLI.Ctl.Commands.ListStompConnectionsCommand'). all() -> [ {group, non_parallel_tests} ]. groups() -> [ {non_parallel_tests, [], [ merge_defaults, run ]} ]. init_per_suite(Config) -> Config1 = rabbit_ct_helpers:set_config(Config, [{rmq_nodename_suffix, ?MODULE}]), rabbit_ct_helpers:log_environment(), rabbit_ct_helpers:run_setup_steps(Config1, rabbit_ct_broker_helpers:setup_steps()). end_per_suite(Config) -> rabbit_ct_helpers:run_teardown_steps(Config, rabbit_ct_broker_helpers:teardown_steps()). init_per_group(_, Config) -> Config. end_per_group(_, Config) -> Config. init_per_testcase(Testcase, Config) -> rabbit_ct_helpers:testcase_started(Config, Testcase). end_per_testcase(Testcase, Config) -> rabbit_ct_helpers:testcase_finished(Config, Testcase). merge_defaults(_Config) -> {[<<"session_id">>, <<"conn_name">>], #{verbose := false}} = ?COMMAND:merge_defaults([], #{}), {[<<"other_key">>], #{verbose := true}} = ?COMMAND:merge_defaults([<<"other_key">>], #{verbose => true}), {[<<"other_key">>], #{verbose := false}} = ?COMMAND:merge_defaults([<<"other_key">>], #{verbose => false}). run(Config) -> Node = rabbit_ct_broker_helpers:get_node_config(Config, 0, nodename), Opts = #{node => Node, timeout => 10000, verbose => false}, [] = 'Elixir.Enum':to_list(?COMMAND:run([], Opts)), StompPort = rabbit_ct_broker_helpers:get_node_config(Config, 0, tcp_port_stomp), {ok, _Client} = rabbit_stomp_client:connect(StompPort), ct:sleep(100), [[{session_id, _}]] = 'Elixir.Enum':to_list(?COMMAND:run([<<"session_id">>], Opts)), {ok, _Client2} = rabbit_stomp_client:connect(StompPort), ct:sleep(100), [[{session_id, _}], [{session_id, _}]] = 'Elixir.Enum':to_list(?COMMAND:run([<<"session_id">>], Opts)), Port = rabbit_ct_broker_helpers:get_node_config(Config, 0, tcp_port_amqp), start_amqp_connection(network, Node, Port), There are still just two connections [[{session_id, _}], [{session_id, _}]] = 'Elixir.Enum':to_list(?COMMAND:run([<<"session_id">>], Opts)), start_amqp_connection(direct, Node, Port), Still two MQTT connections , one direct AMQP 0 - 9 - 1 connection [[{session_id, _}], [{session_id, _}]] = 'Elixir.Enum':to_list(?COMMAND:run([<<"session_id">>], Opts)), Verbose returns all keys Infos = lists:map(fun(El) -> atom_to_binary(El, utf8) end, ?INFO_ITEMS), AllKeys = 'Elixir.Enum':to_list(?COMMAND:run(Infos, Opts)), AllKeys = 'Elixir.Enum':to_list(?COMMAND:run([], Opts#{verbose => true})), There are two connections [First, _Second] = AllKeys, Keys are INFO_ITEMS KeysCount = length(?INFO_ITEMS), KeysCount = length(First), {Keys, _} = lists:unzip(First), [] = Keys -- ?INFO_ITEMS, [] = ?INFO_ITEMS -- Keys. start_amqp_connection(Type, Node, Port) -> Params = amqp_params(Type, Node, Port), {ok, _Connection} = amqp_connection:start(Params). amqp_params(network, _, Port) -> #amqp_params_network{port = Port}; amqp_params(direct, Node, _) -> #amqp_params_direct{node = Node}.
7e75ad47aa778370eff030089fe293be348c3054cb3fb578961ec863f887fdca
tonyg/racket-operational-transformation
client.rkt
#lang racket/gui (require racket/cmdline) (require racket/match) (require racket/serialize) (require racket/tcp) (require operational-transformation) (require operational-transformation/text) (require operational-transformation/text/simple-document) (define ot-text% (class text% (init-field [insert-callback (lambda (loc str) (void))] [delete-callback (lambda (loc len) (void))]) (super-new) (inherit get-text select-all clear insert delete) (define remote-edit? #f) (define/augment (after-delete loc len) (when (not remote-edit?) (delete-callback loc len))) (define/augment (after-insert loc len) (when (not remote-edit?) (insert-callback loc (get-text loc (+ loc len))))) (define/public (replace-contents new-contents) (set! remote-edit? #t) (select-all) (clear) (insert new-contents 0) (set! remote-edit? #f)) (define/public (document-perform op #:remote? remote?) ;; (printf "document-perform: ~v ~v\n" op remote?) (flush-output) (set! remote-edit? remote?) (when remote? (match op [(insertion loc str) (insert str loc)] [(deletion loc len) (delete loc (+ loc len))])) (set! remote-edit? #f) this))) (define ot-editor-canvas% (class editor-canvas% (super-new) (inherit get-editor) (define/override (on-char e) (cond [(send e get-control-down) (case (send e get-key-code) [(#\q #\Q) (send (send this get-top-level-window) show #f)] [(#\a #\A) (send (get-editor) select-all)] [(#\x #\X) (send (get-editor) cut)] [(#\c #\C) (send (get-editor) copy)] [(#\v #\V) (send (get-editor) paste)] [else (void)])] [else (super on-char e)])))) (define (write-msg v o) (write (serialize v) o) (newline o) (flush-output o)) (define (read-msg i) (deserialize (read i))) (define (run-client #:port port #:host server-host) (define-values (i o) (tcp-connect server-host port)) (define (disconnect!) (send f show #f)) (define handle-server-event! (match-lambda [(? string? filename) (send f set-label filename)] [(server-snapshot rev (simple-document content)) (send t replace-contents content) (set! c (make-client (server-snapshot rev t))) (send e enable #t) (send e focus)] [(? pending-operation? p) (maybe-send! (incorporate-operation-from-server c p)) (write-msg (client-state-server-revision c) o)])) (define (on-insertion loc str) (send-to-server! (insertion loc str))) (define (on-deletion loc len) (send-to-server! (deletion loc len))) (define (maybe-send! updated-c) (define-values (p new-c) (flush-buffered-operation updated-c)) (set! c new-c) (when p (write-msg p o))) (define (send-to-server! op) (maybe-send! (incorporate-local-operation c op))) (define f (new frame% [label "Racket OT Client"] [width 640] [height 480])) (define t (new ot-text% [insert-callback on-insertion] [delete-callback on-deletion])) (define e (new ot-editor-canvas% [parent f] [editor t])) (define c #f) (send (send (send t get-style-list) find-named-style "Standard") set-delta (make-object style-delta% 'change-family 'modern)) (thread (lambda () (with-handlers [(values (lambda (e) (queue-callback disconnect!)))] (let loop () (define v (read-msg i)) (if (eof-object? v) (queue-callback disconnect!) (begin (queue-callback (lambda () (handle-server-event! v))) (loop))))))) (send e enable #f) (send f show #t)) (module+ main (define port 5888) (command-line #:once-each [("-p" "--port") server-port ((format "Server port (default ~v)" port)) (set! port (string->number server-port))] #:args (server-hostname) (run-client #:port port #:host server-hostname)))
null
https://raw.githubusercontent.com/tonyg/racket-operational-transformation/1960b7f70138a9de6e3ceb2943b8ca46c83d94ae/operational-transformation-demo/client.rkt
racket
(printf "document-perform: ~v ~v\n" op remote?) (flush-output)
#lang racket/gui (require racket/cmdline) (require racket/match) (require racket/serialize) (require racket/tcp) (require operational-transformation) (require operational-transformation/text) (require operational-transformation/text/simple-document) (define ot-text% (class text% (init-field [insert-callback (lambda (loc str) (void))] [delete-callback (lambda (loc len) (void))]) (super-new) (inherit get-text select-all clear insert delete) (define remote-edit? #f) (define/augment (after-delete loc len) (when (not remote-edit?) (delete-callback loc len))) (define/augment (after-insert loc len) (when (not remote-edit?) (insert-callback loc (get-text loc (+ loc len))))) (define/public (replace-contents new-contents) (set! remote-edit? #t) (select-all) (clear) (insert new-contents 0) (set! remote-edit? #f)) (define/public (document-perform op #:remote? remote?) (set! remote-edit? remote?) (when remote? (match op [(insertion loc str) (insert str loc)] [(deletion loc len) (delete loc (+ loc len))])) (set! remote-edit? #f) this))) (define ot-editor-canvas% (class editor-canvas% (super-new) (inherit get-editor) (define/override (on-char e) (cond [(send e get-control-down) (case (send e get-key-code) [(#\q #\Q) (send (send this get-top-level-window) show #f)] [(#\a #\A) (send (get-editor) select-all)] [(#\x #\X) (send (get-editor) cut)] [(#\c #\C) (send (get-editor) copy)] [(#\v #\V) (send (get-editor) paste)] [else (void)])] [else (super on-char e)])))) (define (write-msg v o) (write (serialize v) o) (newline o) (flush-output o)) (define (read-msg i) (deserialize (read i))) (define (run-client #:port port #:host server-host) (define-values (i o) (tcp-connect server-host port)) (define (disconnect!) (send f show #f)) (define handle-server-event! (match-lambda [(? string? filename) (send f set-label filename)] [(server-snapshot rev (simple-document content)) (send t replace-contents content) (set! c (make-client (server-snapshot rev t))) (send e enable #t) (send e focus)] [(? pending-operation? p) (maybe-send! (incorporate-operation-from-server c p)) (write-msg (client-state-server-revision c) o)])) (define (on-insertion loc str) (send-to-server! (insertion loc str))) (define (on-deletion loc len) (send-to-server! (deletion loc len))) (define (maybe-send! updated-c) (define-values (p new-c) (flush-buffered-operation updated-c)) (set! c new-c) (when p (write-msg p o))) (define (send-to-server! op) (maybe-send! (incorporate-local-operation c op))) (define f (new frame% [label "Racket OT Client"] [width 640] [height 480])) (define t (new ot-text% [insert-callback on-insertion] [delete-callback on-deletion])) (define e (new ot-editor-canvas% [parent f] [editor t])) (define c #f) (send (send (send t get-style-list) find-named-style "Standard") set-delta (make-object style-delta% 'change-family 'modern)) (thread (lambda () (with-handlers [(values (lambda (e) (queue-callback disconnect!)))] (let loop () (define v (read-msg i)) (if (eof-object? v) (queue-callback disconnect!) (begin (queue-callback (lambda () (handle-server-event! v))) (loop))))))) (send e enable #f) (send f show #t)) (module+ main (define port 5888) (command-line #:once-each [("-p" "--port") server-port ((format "Server port (default ~v)" port)) (set! port (string->number server-port))] #:args (server-hostname) (run-client #:port port #:host server-hostname)))
dad21461f4028dae7ced79522f93272efde3f9f5e5b9836d59a90a00755cdc82
Clozure/ccl
l1-error-system.lisp
-*-Mode : LISP ; Package : CCL -*- ;;; Copyright 1994 - 2009 Clozure Associates ;;; 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 ;;; ;;; -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. ;;; This file contains the error/condition system. Functions that ;;; signal/handle errors are defined later. (in-package "CCL") ;;;*********************************** ;;; Error System ;;;*********************************** (defclass condition () ()) (defclass warning (condition) ()) (defclass serious-condition (condition) ()) (defclass error (serious-condition) ()) (defun check-condition-superclasses (cond supers) (let* ((bad nil)) (dolist (s supers) (let* ((class (find-class s nil))) (unless (and class (subtypep class 'condition)) (push s bad)))) (when bad (error "Parent types of condition named ~s being defined aren't known subtypes of CONDITION: ~s." cond bad)))) (define-condition simple-condition (condition) ((format-control :initarg :format-control :reader simple-condition-format-control) (format-arguments :initarg :format-arguments :initform nil :reader simple-condition-format-arguments)) (:report (lambda (c stream) ;; If this were a method, slot value might be faster someday. Accessors always faster ? ;; And of course it's terribly important that this be as fast as humanly possible... ;Use accessors because they're documented and users can specialize them. (apply #'format stream (simple-condition-format-control c) (simple-condition-format-arguments c))))) (define-condition storage-condition (serious-condition) ()) (define-condition thread-condition (condition) ()) (define-condition process-reset (thread-condition) ((kill :initarg :kill :initform nil :reader process-reset-kill))) (define-condition encoding-problem (condition) ((character :initarg :character :reader encoding-problem-character) (destination :initarg :destination :reader encoding-problem-destination) (encoding-name :initarg :encoding-name :reader encoding-problem-encoding-name)) (:report (lambda (c s) (with-slots (character destination encoding-name) c (format s "Character ~c can't be written to ~a in encoding ~a." character destination encoding-name))))) (define-condition decoding-problem (condition) ((source :initarg :source :reader decoding-problem-source) (position :initarg :position :reader decoding-problem-position) (encoding-name :initarg :encoding-name :reader decoding-problem-encoding-name)) (:report (lambda (c stream) (with-slots (source position encoding-name) c (format stream "Contents of ~a" source) (when position (format stream ", near ~a ~d," (if (typep source 'stream) "position" "index") position)) (format stream " don't represent a valid character in ~s." encoding-name))))) (define-condition print-not-readable (error) ((object :initarg :object :reader print-not-readable-object) (stream :initarg :stream :reader print-not-readable-stream)) (:report (lambda (c stream) (let* ((*print-readably* nil)) (format stream "Attempt to print object ~S on stream ~S ." (print-not-readable-object c) (print-not-readable-stream c)))))) (define-condition simple-warning (simple-condition warning) ()) (define-condition compiler-warning (warning) ((function-name :initarg :function-name :initform nil :accessor compiler-warning-function-name) (source-note :initarg :source-note :initform nil :accessor compiler-warning-source-note) (warning-type :initarg :warning-type :reader compiler-warning-warning-type) (args :initarg :args :reader compiler-warning-args) (nrefs :initform () :accessor compiler-warning-nrefs)) (:report report-compiler-warning)) ;; Backward compatibility (defmethod compiler-warning-file-name ((w compiler-warning)) (source-note-filename (compiler-warning-source-note w))) (define-condition style-warning (compiler-warning) ((warning-type :initform :unsure) (args :initform nil))) (define-condition undefined-reference (style-warning) ()) (define-condition undefined-type-reference (undefined-reference) ()) (define-condition undefined-function-reference (undefined-reference) ()) (define-condition macro-used-before-definition (compiler-warning) ()) (define-condition invalid-type-warning (style-warning) ()) (define-condition invalid-arguments (style-warning) ()) (define-condition invalid-arguments-global (style-warning) ()) (define-condition undefined-keyword-reference (undefined-reference invalid-arguments) ()) (define-condition shadowed-typecase-clause (style-warning) ((construct :initarg :construct :initform 'typecase) (clause :initarg :clause) (by :initarg :by)) (:report (lambda (c s) (with-slots (construct clause by) c (format s "Clause ~S ignored in ~S form - shadowed by ~S ." clause construct by))))) (define-condition simple-error (simple-condition error) ()) (define-condition simple-storage-condition (simple-condition storage-condition) ()) (define-condition stack-overflow-condition (simple-storage-condition) ()) (define-condition invalid-memory-access (storage-condition) ((address :initarg :address) (write-p :initform nil :initarg :write-p)) (:report (lambda (c s) (with-slots (address write-p) c (format s "Fault during ~a memory address #x~x" (if write-p "write to" "read of") address))))) (define-condition invalid-memory-operation (storage-condition) () (:report (lambda (c s) (declare (ignore c)) (format s "Invalid memory operation.")))) (define-condition write-to-watched-object (storage-condition) ((object :initform nil :initarg :object :reader write-to-watched-object-object) (offset :initarg :offset :reader write-to-watched-object-offset) (instruction :initarg :instruction :reader write-to-watched-object-instruction)) (:report report-write-to-watched-object)) (defun report-write-to-watched-object (c s) (with-slots (object offset instruction) c (cond ((uvectorp object) (let* ((count (uvsize object)) (nbytes (if (ivectorp object) (subtag-bytes (typecode object) count) (* count target::node-size))) (bytes-per-element (/ nbytes count)) (offset (- offset target::misc-data-offset)) (index (/ offset bytes-per-element))) (format s "Write to watched uvector ~s at " object) (if (fixnump index) (format s "index ~s" index) (format s "an apparently unaligned byte offset ~s" offset)))) ((consp object) (format s "Write to ~a watched cons cell ~s" (cond ((= offset target::cons.cdr) "the CDR of") ((= offset target::cons.car) "the CAR of") (t (format nil "an apparently unaligned byte offset (~s) into" offset))) object)) (t (format s "Write to a strange object ~s at byte offset ~s" object offset))) (when instruction (format s "~&Faulting instruction: ~s" instruction)))) (define-condition allocation-disabled (storage-condition) () (:report (lambda (c s) (declare (ignore c)) (format s "Attempt to heap-allocate a lisp object when heap allocation is disabled.")))) (define-condition vector-size-limitation (storage-condition) ((subtag :initarg :subtag) (element-count :initarg :element-count)) (:report (lambda (c s) (let* ((subtag (slot-value c 'subtag)) (element-count (slot-value c 'element-count)) (typename (if (eql subtag target::subtag-bignum) 'bignum (if (eql subtag target::subtag-simple-vector) 'simple-vector (if (eql subtag target::subtag-simple-base-string) 'string (if (> subtag target::subtag-simple-vector) `(simple-array ,(element-subtype-type subtag) (*)) `(ccl::uvector ,subtag)))))) (qualifier (if (eql subtag target::subtag-bignum) "32-bit " ""))) (format s "Cannot allocate a ~s with ~d elements.~&Objects of type ~s can can have at most ~&~d ~aelements in this implementation." typename element-count (copy-tree typename) (1- target::array-total-size-limit) qualifier))))) (define-condition type-error (error) ((datum :initarg :datum) (expected-type :initarg :expected-type :reader type-error-expected-type) (format-control :initarg :format-control :initform (%rsc-string $xwrongtype) :reader type-error-format-control)) (:report (lambda (c s) (format s (type-error-format-control c) (type-error-datum c) (type-error-expected-type c))))) (define-condition bad-slot-type (type-error) ((slot-definition :initform nil :initarg :slot-definition) (instance :initform nil :initarg :instance)) (:report (lambda (c s) (format s "The value ~s can not be used to set the value of the slot ~s in ~s, because it is not of type ~s. " (type-error-datum c) (slot-definition-name (slot-value c 'slot-definition)) (slot-value c 'instance) (type-error-expected-type c))))) (define-condition bad-slot-type-from-initform (bad-slot-type) () (:report (lambda (c s) (let* ((slotd (slot-value c 'slot-definition))) (format s "The value ~s, derived from the initform ~s, can not be used to set the value of the slot ~s in ~s, because it is not of type ~s. " (type-error-datum c) (slot-definition-initform slotd) (slot-definition-name slotd) (slot-value c 'instance) (type-error-expected-type c)))))) (define-condition bad-slot-type-from-initarg (bad-slot-type) ((initarg-name :initarg :initarg-name)) (:report (lambda (c s) (let* ((slotd (slot-value c 'slot-definition))) (format s "The value ~s, derived from the initarg ~s, can not be used to set the value of the slot ~s in ~s, because it is not of type ~s. " (type-error-datum c) (slot-value c 'initarg-name) (slot-definition-name slotd) (slot-value c 'instance) (type-error-expected-type c)))))) (define-condition improper-list (type-error) ((expected-type :initform '(satisfies proper-list-p) :reader type-error-expected-type))) (define-condition cant-construct-arglist (improper-list) ()) (let* ((magic-token '("Unbound"))) (defmethod type-error-datum ((c type-error)) (let* ((datum-slot (slot-value c 'datum))) (if (eq magic-token datum-slot) (%unbound-marker-8) datum-slot))) ; do we need this (defun signal-type-error (datum expected &optional (format-string (%rsc-string $xwrongtype))) (let ((error #'error)) (funcall error (make-condition 'type-error :format-control format-string :datum (if (eq datum (%unbound-marker-8)) magic-token datum) :expected-type (%type-error-type expected))))) ) (define-condition sequence-index-type-error (type-error) ((sequence :initarg :sequence)) (:report (lambda (c s) (format s "~s is not a valid sequence index for ~s" (type-error-datum c) (slot-value c 'sequence))))) This is admittedly sleazy ; ANSI CL requires TYPE - ERRORs to be ;;; signalled in cases where a type-specifier is not of an appropriate ;;; subtype. The sleazy part is whether it's right to overload TYPE-ERROR ;;; like this. (define-condition invalid-subtype-error (type-error) () (:report (lambda (c s) (format s "The type specifier ~S is not determinably a subtype of the type ~S" (type-error-datum c) (type-error-expected-type c))))) (define-condition simple-type-error (simple-condition type-error) ()) (define-condition array-element-type-error (simple-type-error) ((array :initarg :array :reader array-element-type-error-array)) (:report (lambda (c s) (format s (simple-condition-format-control c) (type-error-datum c) (array-element-type-error-array c))))) (define-condition program-error (error) ()) (define-condition simple-program-error (simple-condition program-error) ((context :initarg :context :reader simple-program-error-context :initform nil))) (define-condition invalid-type-specifier (program-error) ((typespec :initarg :typespec :reader invalid-type-specifier-typespec)) (:report (lambda (c s) (with-slots (typespec) c (format s "Invalid type specifier: ~s ." typespec))))) (defun signal-program-error (string &rest args) (let* ((e #'error)) (funcall e (make-condition 'simple-program-error :format-control (if (fixnump string) (%rsc-string string) string) :format-arguments args)))) (define-condition simple-destructuring-error (simple-program-error) ()) (define-condition wrong-number-of-arguments (program-error) ((nargs :initform nil :initarg :nargs :reader wrong-number-of-arguments-nargs) (fn :initform nil :initarg :fn :reader wrong-number-of-arguments-fn)) (:report report-argument-mismatch)) (define-condition too-many-arguments (wrong-number-of-arguments) ()) (define-condition too-few-arguments (wrong-number-of-arguments) ()) (defun report-argument-mismatch (c s) (let* ((nargs-provided (wrong-number-of-arguments-nargs c)) (fn (wrong-number-of-arguments-fn c)) (too-many (typep c 'too-many-arguments))) (multiple-value-bind (min max scaled-nargs) (min-max-actual-args fn nargs-provided) (if (not min) (progn (format s "Function ~s called with too ~a arguments. " fn (if too-many "many" "few"))) (if too-many (format s "Too many arguments in call to ~s:~&~d argument~:p provided, at most ~d accepted. " fn scaled-nargs max) (format s "Too few arguments in call to ~s:~&~d argument~:p provided, at least ~d required. " fn scaled-nargs min)))))) (define-condition compile-time-program-error (simple-program-error) nil ;((context :initarg :context :reader compile-time-program-error-context)) (:report (lambda (c s) (format s "While compiling ~a :~%~a" (simple-program-error-context c) (apply #'format nil (simple-condition-format-control c) (simple-condition-format-arguments c)))))) ;;; Miscellaneous error during compilation (caused by macroexpansion, transforms, compile-time evaluation, etc.) ;;; NOT program-errors. (define-condition compile-time-error (simple-error) ((context :initarg :context :reader compile-time-error-context)) (:report (lambda (c s) (format s "While compiling ~a :~%~a" (compile-time-error-context c) (format nil "~a" c))))) (define-condition control-error (error) ()) (define-condition cant-throw-error (control-error) ((tag :initarg :tag)) (:report (lambda (c s) (format s "Can't throw to tag ~s" (slot-value c 'tag))))) (define-condition inactive-restart (control-error) ((restart-name :initarg :restart-name)) (:report (lambda (c s) (format s "Restart ~s is not active" (slot-value c 'restart-name))))) (define-condition lock-protocol-error (control-error) ((lock :initarg :lock))) (define-condition not-lock-owner (lock-protocol-error) () (:report (lambda (c s) (format s "Current process ~s does not own lock ~s" *current-process* (slot-value c 'lock))))) (define-condition not-locked (lock-protocol-error) () (:report (lambda (c s) (format s "Lock ~s isn't locked." (slot-value c 'lock))))) (define-condition deadlock (lock-protocol-error) () (:report (lambda (c s) (format s "Requested operation on ~s would cause deadlock." (slot-value c 'lock))))) (define-condition package-error (error) ((package :initarg :package :reader package-error-package))) (define-condition no-such-package (package-error) () (:report (lambda (c s) (format s (%rsc-string $xnopkg) (package-error-package c))))) (define-condition unintern-conflict-error (package-error) ((sym-to-unintern :initarg :sym) (conflicting-syms :initarg :conflicts)) (:report (lambda (c s) (format s (%rsc-string $xunintc) (slot-value c 'sym-to-unintern) (package-error-package c) (slot-value c 'conflicting-syms))))) (define-condition simple-package-error (package-error simple-condition) ()) (defun signal-package-error (package format-control &rest format-args) (error 'simple-package-error :package package :format-control format-control :format-arguments format-args)) (defun signal-package-cerror (package continue-string format-control &rest format-args) (cerror continue-string 'simple-package-error :package package :format-control format-control :format-arguments format-args)) (define-condition import-conflict-error (package-error) ((imported-sym :initarg :imported-sym) (conflicting-sym :initarg :conflicting-sym) (conflict-external-p :initarg :conflict-external)) (:report (lambda (c s) (format s (%rsc-string (if (slot-value c 'conflict-external-p) $ximprtcx $ximprtc)) (slot-value c 'imported-sym) (package-error-package c) (slot-value c 'conflicting-sym))))) (define-condition use-package-conflict-error (package-error) ((package-to-use :initarg :package-to-use) (conflicts :initarg :conflicts) (external-p :initarg :external-p)) (:report (lambda (c s) (format s (%rsc-string (if (slot-value c 'external-p) $xusecX $xusec)) (slot-value c 'package-to-use) (package-error-package c) (slot-value c 'conflicts))))) (define-condition export-conflict-error (package-error) ((conflicts :initarg :conflicts)) (:report (lambda (c s) (format s "Name conflict~p detected by ~A :" (length (slot-value c 'conflicts)) 'export) (let* ((package (package-error-package c))) (dolist (conflict (slot-value c 'conflicts)) (destructuring-bind (inherited-p sym-to-export using-package conflicting-sym) conflict (format s "~&~A'ing ~S from ~S would cause a name conflict with ~&~ the ~a symbol ~S in the package ~s, which uses ~S." 'export sym-to-export package (if inherited-p "inherited" "present") conflicting-sym using-package package))))))) (define-condition export-requires-import (package-error) ((to-be-imported :initarg :to-be-imported)) (:report (lambda (c s) (let* ((p (package-error-package c))) (format s "The following symbols need to be imported to ~S before they can be exported ~& from that package:~%~s:" p (slot-value c 'to-be-imported)))))) (define-condition package-name-conflict-error (package-error simple-error) ()) (define-condition package-is-used-by (package-error) ((using-packages :initarg :using-packages)) (:report (lambda (c s) (format s "~S is used by ~S" (package-error-package c) (slot-value c 'using-packages))))) (define-condition symbol-name-not-accessible (package-error) ((symbol-name :initarg :symbol-name)) (:report (lambda (c s) (format s "No aymbol named ~S is accessible in package ~s" (slot-value c 'symbol-name) (package-error-package c))))) (define-condition stream-error (error) ((stream :initarg :stream :reader stream-error-stream))) (defun stream-error-context (condition) (let* ((stream (stream-error-stream condition))) (with-output-to-string (s) (format s "on ~s" stream) (let* ((pos (ignore-errors (stream-position stream)))) (when pos (format s ", near position ~d" pos))) (let* ((surrounding (stream-surrounding-characters stream))) (when surrounding (format s ", within ~s" surrounding)))))) (define-condition parse-error (error) ()) (define-condition parse-integer-not-integer-string (parse-error) ((string :initarg :string)) (:report (lambda (c s) (format s "Not an integer string: ~s" (slot-value c 'string))))) (define-condition reader-error (parse-error stream-error) ()) (define-condition end-of-file (stream-error) () (:report (lambda (c s) (format s "Unexpected end of file ~a" (stream-error-context c))))) (define-condition stream-is-closed-error (stream-error) () (:report (lambda (condition stream) (format stream "~s is closed" (stream-error-stream condition))))) (define-condition io-timeout (stream-error) ()) (define-condition input-timeout (io-timeout) () (:report (lambda (c s) (format s "Input timeout on ~s" (stream-error-stream c))))) (define-condition output-timeout (io-timeout) () (:report (lambda (c s) (format s "Output timeout on ~s" (stream-error-stream c))))) (define-condition communication-deadline-expired (io-timeout) () (:report (lambda (c s) (format s "Communication deadline timeout on ~s" (stream-error-stream c))))) (define-condition impossible-number (reader-error) ((token :initarg :token :reader impossible-number-token) (condition :initarg :condition :reader impossible-number-condition)) (:report (lambda (c s) (format s "Condition of type ~s raised ~&while trying to parse numeric token ~s ~&~s" (type-of (impossible-number-condition c)) (impossible-number-token c) (stream-error-context c))))) (define-condition simple-stream-error (stream-error simple-condition) () (:report (lambda (c s) (format s "~a : ~&~a" (stream-error-context c) (apply #'format nil (simple-condition-format-control c) (simple-condition-format-arguments c)))))) (define-condition file-error (error) ((pathname :initarg :pathname :initform "<unspecified>" :reader file-error-pathname) (error-type :initarg :error-type :initform "File error on file ~S")) (:report (lambda (c s) (format s (slot-value c 'error-type) (file-error-pathname c))))) (define-condition simple-file-error (simple-condition file-error) () (:report (lambda (c s) (apply #'format s (slot-value c 'error-type) (file-error-pathname c) (simple-condition-format-arguments c))))) (define-condition namestring-parse-error (error) ((complaint :reader namestring-parse-error-complaint :initarg :complaint) (arguments :reader namestring-parse-error-arguments :initarg :arguments :initform nil) (namestring :reader namestring-parse-error-namestring :initarg :namestring) (offset :reader namestring-parse-error-offset :initarg :offset)) (:report (lambda (condition stream) (format stream "Parse error in namestring: ~?~% ~A~% ~V@T^" (namestring-parse-error-complaint condition) (namestring-parse-error-arguments condition) (namestring-parse-error-namestring condition) (namestring-parse-error-offset condition))))) (define-condition cell-error (error) ((name :initarg :name :reader cell-error-name) (error-type :initarg :error-type :initform "Cell error" :reader cell-error-type)) (:report (lambda (c s) (format s "~A: ~S" (cell-error-type c) (cell-error-name c))))) (define-condition unbound-variable (cell-error) ((error-type :initform "Unbound variable"))) (define-condition undefined-function (cell-error) ((error-type :initform "Undefined function"))) (define-condition undefined-function-call (control-error undefined-function) ((function-arguments :initarg :function-arguments :reader undefined-function-call-arguments)) (:report (lambda (c s) (format s "Undefined function ~S called with arguments ~:S ." (cell-error-name c) (undefined-function-call-arguments c))))) (define-condition call-special-operator-or-macro (undefined-function-call) () (:report (lambda (c s) (format s "Special operator or global macro-function ~s can't be FUNCALLed or APPLYed" (cell-error-name c))))) (define-condition unbound-slot (cell-error) ((instance :initarg :instance :accessor unbound-slot-instance)) (:report (lambda (c s) (format s "Slot ~s is unbound in ~s" (cell-error-name c) (unbound-slot-instance c))))) (define-condition arithmetic-error (error) ((operation :initform nil :initarg :operation :reader arithmetic-error-operation) (operands :initform nil :initarg :operands :reader arithmetic-error-operands) (status :initform nil :initarg :status :reader arithmetic-error-status)) (:report (lambda (c s) (format s "~S detected" (type-of c)) (let* ((operands (arithmetic-error-operands c))) (when operands (format s "~&performing ~A on ~:S" (arithmetic-error-operation c) operands)))))) (define-condition division-by-zero (arithmetic-error) ()) (define-condition floating-point-underflow (arithmetic-error) ()) (define-condition floating-point-overflow (arithmetic-error) ()) (define-condition floating-point-inexact (arithmetic-error) ()) (define-condition floating-point-invalid-operation (arithmetic-error) ()) (define-condition compiler-bug (simple-error) () (:report (lambda (c stream) (format stream "Compiler bug or inconsistency:~%") (apply #'format stream (simple-condition-format-control c) (simple-condition-format-arguments c))))) (define-condition external-process-creation-failure (serious-condition) ((proc :initarg :proc)) (:report (lambda (c stream) (with-slots (proc) c (let* ((code (external-process-%exit-code proc))) (format stream "Fork failed in ~s: ~a. " proc (if (eql code -1) "random lisp error" (%strerror code)))))))) (define-condition simple-reader-error (reader-error simple-error) () (:report (lambda (c output-stream) (format output-stream "Reader error ~a:~%~?" (stream-error-context c) (simple-condition-format-control c) (simple-condition-format-arguments c))))) ;;; This condition is signalled whenever we make a UNKNOWN-TYPE so that ;;; compiler warnings can be emitted as appropriate. ;;; (define-condition parse-unknown-type (condition) ((specifier :reader parse-unknown-type-specifier :initarg :specifier)) (:report (lambda (c s) (print-unreadable-object (c s :type t) (format s "unknown type ~A" (parse-unknown-type-specifier c)))))) (define-condition no-applicable-method-exists (error) ((gf :initarg :gf) (args :initarg :args)) (:report (lambda (c s) (with-slots (gf args) c (format s "There is no applicable method for the generic function:~% ~s~%when called with arguments:~% ~s" gf args))))) (defun restartp (thing) (istruct-typep thing 'restart)) (setf (type-predicate 'restart) 'restartp) (defmethod print-object ((restart restart) stream) (let ((report (%restart-report restart))) (cond ((or *print-escape* (null report)) (print-unreadable-object (restart stream :identity t) (format stream "~S ~S" 'restart (%restart-name restart)))) ((stringp report) (write-string report stream)) (t (funcall report stream))))) (defun %make-restart (name action report interactive test) (%cons-restart name action report interactive test)) (defun make-restart (vector name action-function &key report-function interactive-function test-function) (unless vector (setq vector (%cons-restart nil nil nil nil nil))) (setf (%restart-name vector) name (%restart-action vector) (require-type action-function 'function) (%restart-report vector) (if report-function (require-type report-function 'function)) (%restart-interactive vector) (if interactive-function (require-type interactive-function 'function)) (%restart-test vector) (if test-function (require-type test-function 'function))) vector) (defun restart-name (restart) "Return the name of the given restart object." (%restart-name (require-type restart 'restart))) (defun applicable-restart-p (restart condition) (let* ((pair (if condition (assq restart *condition-restarts*))) (test (%restart-test restart))) (and (or (null pair) (eq (%cdr pair) condition)) (or (null test) (funcall test condition))))) (defun compute-restarts (&optional condition &aux restarts) "Return a list of all the currently active restarts ordered from most recently established to less recently established. If CONDITION is specified, then only restarts associated with CONDITION (or with no condition) will be returned." (dolist (cluster %restarts% (nreverse restarts)) (dolist (restart cluster) (when (applicable-restart-p restart condition) (push restart restarts))))) (defun find-restart (name &optional condition) "Return the first active restart named NAME. If NAME names a restart, the restart is returned if it is currently active. If no such restart is found, NIL is returned. It is an error to supply NIL as a name. If CONDITION is specified and not NIL, then only restarts associated with that condition (or with no condition) will be returned." (if (typep name 'restart) (dolist (cluster %restarts%) (dolist (restart cluster) (if (eq restart name) (return-from find-restart restart)))) (dolist (cluster %restarts%) (dolist (restart cluster) (when (and (eq (restart-name restart) name) (applicable-restart-p restart condition)) (return-from find-restart restart)))))) (defun %active-restart (name) (dolist (cluster %restarts%) (dolist (restart cluster) (when (or (eq restart name) (let* ((rname (%restart-name restart))) (and (eq rname name) (applicable-restart-p restart nil)))) (return-from %active-restart (values restart cluster))))) (error 'inactive-restart :restart-name name)) (defun invoke-restart (restart &rest values) "Calls the function associated with the given restart, passing any given arguments. If the argument restart is not a restart or a currently active non-nil restart name, then a CONTROL-ERROR is signalled." (multiple-value-bind (restart tag) (%active-restart restart) (let ((fn (%restart-action restart))) (cond ((null fn) ; simple restart (unless (null values) (%err-disp $xtminps)) (throw tag nil)) ((fixnump fn) ; restart case (throw tag (cons fn values))) ((functionp fn) ; restart bind (apply fn values)) (t ; with-simple-restart (throw tag (values nil t))))))) (define-condition restart-failure (control-error) ((restart :initarg :restart :reader restart-failure-restart)) (:report (lambda (c s) (format s "The ~a restart failed to transfer control dynamically as expected." (restart-name (restart-failure-restart c)))))) (defun invoke-restart-no-return (restart &rest values) (declare (dynamic-extent values)) (apply #'invoke-restart restart values) (error 'restart-failure :restart restart)) (defun invoke-restart-interactively (restart) "Calls the function associated with the given restart, prompting for any necessary arguments. If the argument restart is not a restart or a currently active non-NIL restart name, then a CONTROL-ERROR is signalled." (let* ((restart (%active-restart restart))) (format *error-output* "~&Invoking restart: ~a~&" restart) (let* ((argfn (%restart-interactive restart)) (values (when argfn (funcall argfn)))) (apply #'invoke-restart restart values)))) (defun maybe-invoke-restart (restart value condition) (let ((restart (find-restart restart condition))) (when restart (invoke-restart restart value)))) (defun use-value (value &optional condition) "Transfer control and VALUE to a restart named USE-VALUE, or return NIL if none exists." (maybe-invoke-restart 'use-value value condition)) (defun store-value (value &optional condition) "Transfer control and VALUE to a restart named STORE-VALUE, or return NIL if none exists." (maybe-invoke-restart 'store-value value condition)) (defun condition-arg (thing args type) (cond ((condition-p thing) (if args (%err-disp $xtminps) thing)) ((symbolp thing) (apply #'make-condition thing args)) (t (make-condition type :format-control thing :format-arguments args)))) (defun make-condition (name &rest init-list) "Make an instance of a condition object using the specified initargs." (declare (dynamic-extent init-list)) (if (subtypep name 'condition) (apply #'make-instance name init-list) (let ((class (if (classp name) name (find-class name)))) ;; elicit an error if no such class (unless (class-finalized-p class) (finalize-inheritance class)) ;; elicit an error if forward refs. (error "~S is not a condition class" class)))) (defmethod print-object ((c condition) stream) (if *print-escape* (call-next-method) (report-condition c stream))) (defmethod report-condition ((c condition) stream) (princ (cond ((typep c 'error) "Error ") ((typep c 'warning) "Warning ") (t "Condition ")) stream) ;Here should dump all slots or something. For now... (let ((*print-escape* t)) (print-object c stream))) (defun signal-simple-condition (class-name format-string &rest args) (let ((e #'error)) ; Never-tail-call. (funcall e (make-condition class-name :format-control format-string :format-arguments args)))) (defun signal-simple-program-error (format-string &rest args) (apply #'signal-simple-condition 'simple-program-error format-string args)) ;;getting the function name for error functions. (defun %last-fn-on-stack (&optional (number 0) (s (%get-frame-ptr))) (let* ((fn nil)) (let ((p s)) (dotimes (i number) (declare (fixnum i)) (unless (setq p (parent-frame p nil)) (return))) (do* ((i number (1+ i))) ((null p)) (if (setq fn (cfp-lfun p)) (return (values fn i)) (setq p (parent-frame p nil))))))) (defun %err-fn-name (lfun) "given an lfun returns the name or the string \"Unknown\"" (if (lfunp lfun) (or (lfun-name lfun) lfun) (or lfun "Unknown"))) (defun %real-err-fn-name (error-pointer) (multiple-value-bind (fn p) (%last-fn-on-stack 0 error-pointer) (let ((name (%err-fn-name fn))) (if (and (memq name '( call-check-regs)) p) (%err-fn-name (%last-fn-on-stack (1+ p) error-pointer)) name)))) ;; Some simple restarts for simple error conditions. Callable from the kernel. (defun find-unique-homonyms (name &optional (test (constantly t))) (delete-duplicates (loop with symbol = (if (consp name) (second name) name) with pname = (symbol-name symbol) for package in (list-all-packages) for other-package-symbol = (find-symbol pname package) for canditate = (and other-package-symbol (neq other-package-symbol symbol) (if (consp name) (list (first name) other-package-symbol) other-package-symbol)) when (and canditate (funcall test canditate)) collect canditate) :test #'equal)) (def-kernel-restart $xvunbnd %default-unbound-variable-restarts (frame-ptr cell-name) (unless *level-1-loaded* (dbg cell-name)) ; user should never see this. (let ((condition (make-condition 'unbound-variable :name cell-name)) (other-variables (find-unique-homonyms cell-name (lambda (name) (and (not (keywordp name)) (boundp name)))))) (flet ((new-value () (catch-cancel (return-from new-value (list (read-from-string (get-string-from-user (format nil "New value for ~s : " cell-name)))))) (continue condition))) ; force error again if cancelled, var still not set. (restart-case (%error condition nil frame-ptr) (continue () :report (lambda (s) (format s "Retry getting the value of ~S." cell-name)) (symbol-value cell-name)) (use-homonym (homonym) :test (lambda (c) (and (or (null c) (eq c condition)) other-variables)) :report (lambda (s) (if (= 1 (length other-variables)) (format s "Use the value of ~s this time." (first other-variables)) (format s "Use one of the homonyms ~{~S or ~} this time." other-variables))) :interactive (lambda () (if (= 1 (length other-variables)) other-variables (select-item-from-list other-variables :window-title "Select homonym to use"))) (symbol-value homonym)) (use-value (value) :interactive new-value :report (lambda (s) (format s "Specify a value of ~S to use this time." cell-name)) value) (store-value (value) :interactive new-value :report (lambda (s) (format s "Specify a value of ~S to store and use." cell-name)) (setf (symbol-value cell-name) value)))))) (def-kernel-restart $xnopkg %default-no-package-restart (frame-ptr package-name) (or (and *autoload-lisp-package* (or (string-equal package-name "LISP") (string-equal package-name "USER")) (progn (require "LISP-PACKAGE") (find-package package-name))) (let* ((alias (or (%cdr (assoc package-name '(("LISP" . "COMMON-LISP") ("USER" . "CL-USER")) :test #'string-equal)) (if (packagep *package*) (package-name *package*)))) (condition (make-condition 'no-such-package :package package-name))) (flet ((try-again (p) (or (find-package p) (%kernel-restart $xnopkg p)))) (restart-case (restart-case (%error condition nil frame-ptr) (continue () :report (lambda (s) (format s "Retry finding package with name ~S." package-name)) (try-again package-name)) (use-value (value) :interactive (lambda () (block nil (catch-cancel (return (list (get-string-from-user "Find package named : ")))) (continue condition))) :report (lambda (s) (format s "Find specified package instead of ~S ." package-name)) (try-again value)) (make-nickname () :report (lambda (s) (format s "Make ~S be a nickname for package ~S." package-name alias)) (let ((p (try-again alias))) (push package-name (cdr (pkg.names p))) p))) (require-lisp-package () :test (lambda (c) (and (eq c condition) (or (string-equal package-name "LISP") (string-equal package-name "USER")))) :report (lambda (s) (format s "(require :lisp-package) and retry finding package ~s" package-name)) (require "LISP-PACKAGE") (try-again package-name))))))) (def-kernel-restart $xunintc unintern-conflict-restarts (frame-ptr sym package conflicts) (let ((condition (make-condition 'unintern-conflict-error :package package :sym sym :conflicts conflicts))) (restart-case (%error condition nil frame-ptr) (continue () :report (lambda (s) (format s "Try again to unintern ~s from ~s" sym package)) (unintern sym package)) (do-shadowing-import (ssym) :report (lambda (s) (format s "SHADOWING-IMPORT one of ~S in ~S." conflicts package)) :interactive (lambda () (block nil (catch-cancel (return (select-item-from-list conflicts :window-title (format nil "Shadowing-import one of the following in ~s" package) :table-print-function #'prin1))) (continue condition))) (shadowing-import (list ssym) package))))) (def-kernel-restart $xusec blub (frame-ptr package-to-use using-package conflicts) (resolve-use-package-conflict-error frame-ptr package-to-use using-package conflicts nil)) (def-kernel-restart $xusecX blub (frame-ptr package-to-use using-package conflicts) (resolve-use-package-conflict-error frame-ptr package-to-use using-package conflicts t)) (defun resolve-use-package-conflict-error (frame-ptr package-to-use using-package conflicts external-p) (let ((condition (make-condition 'use-package-conflict-error :package using-package :package-to-use package-to-use :conflicts conflicts :external-p external-p))) (flet ((external-test (&rest ignore) (declare (ignore ignore)) external-p) (present-test (&rest ignore) (declare (ignore ignore)) (not external-p))) (declare (dynamic-extent #'present-test #'external-test)) (restart-case (%error condition nil frame-ptr) (continue () :report (lambda (s) (format s "Try again to use ~s in ~s" package-to-use using-package))) (resolve-by-shadowing-import (&rest shadowing-imports) :test external-test :interactive (lambda () (mapcar #'(lambda (pair) (block nil (catch-cancel (return (car (select-item-from-list pair :window-title (format nil "Shadowing-import one of the following in ~s" using-package) :table-print-function #'prin1)))) (continue condition))) conflicts)) :report (lambda (s) (format s "SHADOWING-IMPORT one of each pair of conflicting symbols.")) (shadowing-import shadowing-imports using-package)) (unintern-all () :test present-test :report (lambda (s) (format s "UNINTERN all conflicting symbols from ~S" using-package)) (dolist (c conflicts) (unintern (car c) using-package))) (shadow-all () :test present-test :report (lambda (s) (format s "SHADOW all conflicting symbols in ~S" using-package)) (dolist (c conflicts) (shadow-1 using-package (car c)))) (resolve-by-unintern-or-shadow (&rest dispositions) :test present-test :interactive (lambda () (mapcar #'(lambda (pair) (let* ((present-sym (car pair))) (block nil (catch-cancel (return (car (select-item-from-list (list 'shadow 'unintern) :window-title (format nil "SHADOW ~S in, or UNINTERN ~S from ~S" present-sym present-sym using-package) :table-print-function #'prin1))) (continue condition))))) conflicts)) :report (lambda (s) (format s "SHADOW or UNINTERN the conflicting symbols in ~S." using-package)) (dolist (d dispositions) (let* ((sym (car (pop conflicts)))) (if (eq d 'shadow) (shadow-1 using-package sym) (unintern sym using-package))))))))) (defun resolve-export-conflicts (conflicts package) (let* ((first-inherited (caar conflicts)) (all-same (dolist (conflict (cdr conflicts) t) (unless (eq (car conflict) first-inherited) (return nil)))) (all-inherited (and all-same first-inherited)) (all-present (and all-same (not first-inherited))) (condition (make-condition 'export-conflict-error :conflicts conflicts :package package))) (flet ((check-again () (let* ((remaining-conflicts (check-export-conflicts (mapcar #'cadr conflicts) package))) (if remaining-conflicts (resolve-export-conflicts remaining-conflicts package))))) (restart-case (%error condition nil (%get-frame-ptr)) (resolve-all-by-shadowing-import-inherited () :test (lambda (&rest ignore) (declare (ignore ignore)) all-inherited) :report (lambda (s) (format s "SHADOWING-IMPORT all conflicting inherited symbol(s) in using package(s).")) (dolist (conflict conflicts (check-again)) (destructuring-bind (using-package inherited-sym) (cddr conflict) (shadowing-import-1 using-package inherited-sym)))) (resolve-all-by-shadowing-import-exported () :test (lambda (&rest ignore) (declare (ignore ignore)) all-inherited) :report (lambda (s) (format s "SHADOWING-IMPORT all conflicting symbol(s) to be exported in using package(s).")) (dolist (conflict conflicts (check-again)) (destructuring-bind (exported-sym using-package ignore) (cdr conflict) (declare (ignore ignore)) (shadowing-import-1 using-package exported-sym)))) (resolve-all-by-uninterning-present () :test (lambda (&rest ignore) (declare (ignore ignore)) all-present) :report (lambda (s) (format s "UNINTERN all present conflicting symbol(s) in using package(s).")) (dolist (conflict conflicts (check-again)) (destructuring-bind (using-package inherited-sym) (cddr conflict) (unintern inherited-sym using-package)))) (resolve-all-by-shadowing-present () :test (lambda (&rest ignore) (declare (ignore ignore)) all-present) :report (lambda (s) (format s "SHADOW all present conflicting symbol(s) in using package(s).")) (dolist (conflict conflicts (check-again)) (destructuring-bind (using-package inherited-sym) (cddr conflict) (shadow-1 using-package inherited-sym)))) (review-and-resolve (dispositions) :report (lambda (s) (format s "Review each name conflict and resolve individually.")) :interactive (lambda () (let* ((disp nil)) (block b (catch-cancel (dolist (conflict conflicts (return-from b (list disp))) (destructuring-bind (inherited-p exported-sym using-package conflicting-sym) conflict (let* ((syms (list exported-sym conflicting-sym))) (if inherited-p (push (list 'shadowing-import (select-item-from-list syms :window-title (format nil "Shadowing-import one of the following in ~s" using-package) :table-print-function #'prin1) using-package) disp) (let* ((selection (car (select-item-from-list syms :window-title (format nil "Shadow ~S or unintern ~s in ~s" exported-sym conflicting-sym using-package) :table-print-function #'prin1)))) (push (if (eq selection 'exported-sym) (list 'shadow (list exported-sym) using-package) (list 'unintern conflicting-sym using-package)) disp))))))) nil))) (dolist (disp dispositions (check-again)) (apply (car disp) (cdr disp)))))))) (def-kernel-restart $xwrongtype default-require-type-restarts (frame-ptr value typespec) (setq typespec (%type-error-type typespec)) (let ((condition (make-condition 'type-error :datum value :expected-type typespec))) (restart-case (%error condition nil frame-ptr) (use-value (newval) :report (lambda (s) (format s "Use a new value of type ~s instead of ~s." typespec value)) :interactive (lambda () (format *query-io* "~&New value of type ~S :" typespec) (list (read *query-io*))) (require-type newval typespec))))) (def-kernel-restart $xudfcall default-undefined-function-call-restarts (frame-ptr function-name args) (unless *level-1-loaded* (dbg function-name)) ; user should never see this (let ((condition (make-condition 'undefined-function-call :name function-name :function-arguments args)) (other-functions (find-unique-homonyms function-name #'fboundp))) (restart-case (%error condition nil frame-ptr) (continue () :report (lambda (s) (format s "Retry applying ~S to ~S." function-name args)) (apply function-name args)) (use-homonym (function-name) :test (lambda (c) (and (or (null c) (eq c condition)) other-functions)) :report (lambda (s) (if (= 1 (length other-functions)) (format s "Apply ~s to ~S this time." (first other-functions) args) (format s "Apply one of ~{~S or ~} to ~S this time." other-functions args))) :interactive (lambda () (if (= 1 (length other-functions)) other-functions (select-item-from-list other-functions :window-title "Select homonym to use"))) (apply (fdefinition function-name) args)) (use-value (function) :interactive (lambda () (format *query-io* "Function to apply instead of ~s :" function-name) (let ((f (read *query-io*))) (unless (symbolp f) (setq f (eval f))) ; almost-the-right-thing (tm) (list (coerce f 'function)))) :report (lambda (s) (format s "Apply specified function to ~S this time." args)) (apply function args)) (store-value (function) :interactive (lambda () (format *query-io* "Function to apply as new definition of ~s :" function-name) (let ((f (read *query-io*))) (unless (symbolp f) (setq f (eval f))) ; almost-the-right-thing (tm) (list (coerce f 'function)))) :report (lambda (s) (format s "Specify a function to use as the definition of ~S." function-name)) (apply (setf (symbol-function function-name) function) args))))) (defun %check-type (value typespec placename typename) (let ((condition (make-condition 'type-error :datum value :expected-type typespec))) (if typename (setf (slot-value condition 'format-control) (format nil "value ~~S is not ~A (~~S)." typename))) (restart-case (%error condition nil (%get-frame-ptr)) (store-value (newval) :report (lambda (s) (format s "Assign a new value of type ~a to ~s" typespec placename)) :interactive (lambda () (format *query-io* "~&New value for ~S :" placename) (list (eval (read)))) newval)))) ; This has to be defined fairly early (assuming, of course, that it "has" to be defined at all ... (defun ensure-value-of-type (value typespec placename &optional typename) (tagbody again (unless (typep value typespec) (let ((condition (make-condition 'type-error :datum value :expected-type typespec))) (if typename (setf (slot-value condition 'format-control) (format nil "value ~~S is not ~A (~~S)." typename))) (restart-case (%error condition nil (%get-frame-ptr)) (store-value (newval) :report (lambda (s) (format s "Assign a new value of type ~a to ~s" typespec placename)) :interactive (lambda () (format *query-io* "~&New value for ~S :" placename) (list (eval (read)))) (setq value newval) (go again)))))) value) ;;;The Error Function (defparameter *kernel-simple-error-classes* (list (cons $xcalltoofew 'simple-destructuring-error) (cons $xcalltoomany 'simple-destructuring-error) (cons $xstkover 'stack-overflow-condition) (cons $xmemfull 'simple-storage-condition) this one needs 2 args (cons $xdivzro 'division-by-zero) (cons $xflovfl 'floating-point-overflow) (cons $xfunbnd 'undefined-function) (cons $xbadkeys 'simple-program-error) (cons $xcallnomatch 'simple-program-error) (cons $xnotfun 'call-special-operator-or-macro) (cons $xaccessnth 'sequence-index-type-error) (cons $ximproperlist 'improper-list) (cons $xnospread 'cant-construct-arglist) (cons $xnotelt 'array-element-type-error) )) (defparameter *simple-error-types* (vector nil 'simple-program-error 'simple-file-error)) (defconstant $pgm-err #x10000) (defparameter %type-error-typespecs% #(array bignum fixnum character integer list number sequence simple-string simple-vector string symbol macptr real cons unsigned-byte (integer 2 36) float rational ratio short-float double-float complex vector simple-base-string function (unsigned-byte 16) (unsigned-byte 8) (unsigned-byte 32) (signed-byte 32) (signed-byte 16) (signed-byte 8) base-char bit (unsigned-byte 24) ; (integer 0 (array-total-size-limit)) (unsigned-byte 64) (signed-byte 64) (unsigned-byte 56) (simple-array double-float (* *)) (simple-array single-float (* *)) (mod #x110000) (array * (* *)) ;2d array (array * (* * *)) ;3d array (array t) (array bit) (array (signed-byte 8)) (array (unsigned-byte 8)) (array (signed-byte 16)) (array (unsigned-byte 16)) (array (signed-byte 32)) (array (unsigned-byte 32)) (array (signed-byte 64)) (array (unsigned-byte 64)) (array fixnum) (array single-float) (array double-float) (array character) (array t (* *)) (array bit (* *)) (array (signed-byte 8) (* *)) (array (unsigned-byte 8) (* *)) (array (signed-byte 16) (* *)) (array (unsigned-byte 16) (* *)) (array (signed-byte 32) (* *)) (array (unsigned-byte 32) (* *)) (array (signed-byte 64) (* *)) (array (unsigned-byte 64) (* *)) (array fixnum (* *)) (array single-float (* *)) (array double-float (* *)) (array character (* *)) (simple-array t (* *)) (simple-array bit (* *)) (simple-array (signed-byte 8) (* *)) (simple-array (unsigned-byte 8) (* *)) (simple-array (signed-byte 16) (* *)) (simple-array (unsigned-byte 16) (* *)) (simple-array (signed-byte 32) (* *)) (simple-array (unsigned-byte 32) (* *)) (simple-array (signed-byte 64) (* *)) (simple-array (unsigned-byte 64) (* *)) (simple-array fixnum (* *)) (simple-array character (* *)) (array t (* * *)) (array bit (* * *)) (array (signed-byte 8) (* * *)) (array (unsigned-byte 8) (* * *)) (array (signed-byte 16) (* * *)) (array (unsigned-byte 16) (* * *)) (array (signed-byte 32) (* * *)) (array (unsigned-byte 32) (* * *)) (array (signed-byte 64) (* * *)) (array (unsigned-byte 64) (* * *)) (array fixnum (* * *)) (array single-float (* * *)) (array double-float (* * *)) (array character (* * *)) (simple-array t (* * *)) (simple-array bit (* * *)) (simple-array (signed-byte 8) (* * *)) (simple-array (unsigned-byte 8) (* * *)) (simple-array (signed-byte 16) (* * *)) (simple-array (unsigned-byte 16) (* * *)) (simple-array (signed-byte 32) (* * *)) (simple-array (unsigned-byte 32) (* * *)) (simple-array (signed-byte 64) (* * *)) (simple-array (unsigned-byte 64) (* * *)) (simple-array fixnum (* * *)) (simple-array single-float (* * *)) (simple-array double-float (* * *)) (simple-array character (* * *)) (vector t) bit-vector (vector (signed-byte 8)) (vector (unsigned-byte 8)) (vector (signed-byte 16)) (vector (unsigned-byte 16)) (vector (signed-byte 32)) (vector (unsigned-byte 32)) (vector (signed-byte 64)) (vector (unsigned-byte 64)) (vector fixnum) (vector single-float) (vector double-float) )) (defun %type-error-type (type) (if (fixnump type) (svref %type-error-typespecs% type) type)) (defun %typespec-id (typespec) (flet ((type-equivalent (t1 t2) (ignore-errors (and (subtypep t1 t2) (subtypep t2 t1))))) (position typespec %type-error-typespecs% :test #'type-equivalent))) (defmethod condition-p ((x t)) nil) (defmethod condition-p ((x condition)) t) (let* ((globals ())) (defun %check-error-globals () (let ((vars ()) (valfs ()) (oldvals ())) (dolist (g globals (values vars valfs oldvals)) (destructuring-bind (sym predicate newvalf) g (let* ((boundp (boundp sym)) (oldval (if boundp (symbol-value sym) (%unbound-marker-8)))) (unless (and boundp (funcall predicate oldval)) (push sym vars) (push oldval oldvals) (push newvalf valfs))))))) (defun check-error-global (sym checkfn newvalfn) (setq sym (require-type sym 'symbol) checkfn (require-type checkfn 'function) newvalfn (require-type newvalfn 'function)) (let ((found (assq sym globals))) (if found (setf (cadr found) checkfn (caddr found) newvalfn) (push (list sym checkfn newvalfn) globals)) sym)) ) (check-error-global '*package* #'packagep #'(lambda () (find-package "CL-USER"))) (flet ((io-stream-p (x) (and (streamp x) (eq (stream-direction x) :io))) (is-input-stream-p (x) (and (streamp x) (input-stream-p x))) (is-output-stream-p (x) (and (streamp x) (output-stream-p x))) (default-terminal-io () (make-echoing-two-way-stream *stdin* *stdout*)) (terminal-io () *terminal-io*) (standard-output () *standard-output*)) ;; Note that order matters. These need to come out of %check-error-globals with * terminal - io * first and * trace - output * last (check-error-global '*terminal-io* #'io-stream-p #'default-terminal-io) (check-error-global '*query-io* #'io-stream-p #'terminal-io) (check-error-global '*debug-io* #'io-stream-p #'terminal-io) (check-error-global '*standard-input* #'is-input-stream-p #'terminal-io) (check-error-global '*standard-output* #'is-output-stream-p #'terminal-io) (check-error-global '*error-output* #'is-output-stream-p #'standard-output) (check-error-global '*trace-output* #'is-output-stream-p #'standard-output))
null
https://raw.githubusercontent.com/Clozure/ccl/01cf6cd7f849d75bc61eeb3f25b034500da6b58b/level-1/l1-error-system.lisp
lisp
Package : CCL -*- you may not use this file except in compliance with the License. You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing, software 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. This file contains the error/condition system. Functions that signal/handle errors are defined later. *********************************** Error System *********************************** If this were a method, slot value might be faster someday. Accessors always faster ? And of course it's terribly important that this be as fast as humanly possible... Use accessors because they're documented and users can specialize them. Backward compatibility do we need this ANSI CL requires TYPE - ERRORs to be signalled in cases where a type-specifier is not of an appropriate subtype. The sleazy part is whether it's right to overload TYPE-ERROR like this. ((context :initarg :context :reader compile-time-program-error-context)) Miscellaneous error during compilation (caused by macroexpansion, transforms, compile-time evaluation, etc.) NOT program-errors. This condition is signalled whenever we make a UNKNOWN-TYPE so that compiler warnings can be emitted as appropriate. simple restart restart case restart bind with-simple-restart elicit an error if no such class elicit an error if forward refs. Here should dump all slots or something. For now... Never-tail-call. getting the function name for error functions. Some simple restarts for simple error conditions. Callable from the kernel. user should never see this. force error again if cancelled, var still not set. user should never see this almost-the-right-thing (tm) almost-the-right-thing (tm) This has to be defined fairly early (assuming, of course, that it "has" to be defined at all ... The Error Function (integer 0 (array-total-size-limit)) 2d array 3d array Note that order matters. These need to come out of %check-error-globals with
Copyright 1994 - 2009 Clozure Associates distributed under the License is distributed on an " AS IS " BASIS , (in-package "CCL") (defclass condition () ()) (defclass warning (condition) ()) (defclass serious-condition (condition) ()) (defclass error (serious-condition) ()) (defun check-condition-superclasses (cond supers) (let* ((bad nil)) (dolist (s supers) (let* ((class (find-class s nil))) (unless (and class (subtypep class 'condition)) (push s bad)))) (when bad (error "Parent types of condition named ~s being defined aren't known subtypes of CONDITION: ~s." cond bad)))) (define-condition simple-condition (condition) ((format-control :initarg :format-control :reader simple-condition-format-control) (format-arguments :initarg :format-arguments :initform nil :reader simple-condition-format-arguments)) (apply #'format stream (simple-condition-format-control c) (simple-condition-format-arguments c))))) (define-condition storage-condition (serious-condition) ()) (define-condition thread-condition (condition) ()) (define-condition process-reset (thread-condition) ((kill :initarg :kill :initform nil :reader process-reset-kill))) (define-condition encoding-problem (condition) ((character :initarg :character :reader encoding-problem-character) (destination :initarg :destination :reader encoding-problem-destination) (encoding-name :initarg :encoding-name :reader encoding-problem-encoding-name)) (:report (lambda (c s) (with-slots (character destination encoding-name) c (format s "Character ~c can't be written to ~a in encoding ~a." character destination encoding-name))))) (define-condition decoding-problem (condition) ((source :initarg :source :reader decoding-problem-source) (position :initarg :position :reader decoding-problem-position) (encoding-name :initarg :encoding-name :reader decoding-problem-encoding-name)) (:report (lambda (c stream) (with-slots (source position encoding-name) c (format stream "Contents of ~a" source) (when position (format stream ", near ~a ~d," (if (typep source 'stream) "position" "index") position)) (format stream " don't represent a valid character in ~s." encoding-name))))) (define-condition print-not-readable (error) ((object :initarg :object :reader print-not-readable-object) (stream :initarg :stream :reader print-not-readable-stream)) (:report (lambda (c stream) (let* ((*print-readably* nil)) (format stream "Attempt to print object ~S on stream ~S ." (print-not-readable-object c) (print-not-readable-stream c)))))) (define-condition simple-warning (simple-condition warning) ()) (define-condition compiler-warning (warning) ((function-name :initarg :function-name :initform nil :accessor compiler-warning-function-name) (source-note :initarg :source-note :initform nil :accessor compiler-warning-source-note) (warning-type :initarg :warning-type :reader compiler-warning-warning-type) (args :initarg :args :reader compiler-warning-args) (nrefs :initform () :accessor compiler-warning-nrefs)) (:report report-compiler-warning)) (defmethod compiler-warning-file-name ((w compiler-warning)) (source-note-filename (compiler-warning-source-note w))) (define-condition style-warning (compiler-warning) ((warning-type :initform :unsure) (args :initform nil))) (define-condition undefined-reference (style-warning) ()) (define-condition undefined-type-reference (undefined-reference) ()) (define-condition undefined-function-reference (undefined-reference) ()) (define-condition macro-used-before-definition (compiler-warning) ()) (define-condition invalid-type-warning (style-warning) ()) (define-condition invalid-arguments (style-warning) ()) (define-condition invalid-arguments-global (style-warning) ()) (define-condition undefined-keyword-reference (undefined-reference invalid-arguments) ()) (define-condition shadowed-typecase-clause (style-warning) ((construct :initarg :construct :initform 'typecase) (clause :initarg :clause) (by :initarg :by)) (:report (lambda (c s) (with-slots (construct clause by) c (format s "Clause ~S ignored in ~S form - shadowed by ~S ." clause construct by))))) (define-condition simple-error (simple-condition error) ()) (define-condition simple-storage-condition (simple-condition storage-condition) ()) (define-condition stack-overflow-condition (simple-storage-condition) ()) (define-condition invalid-memory-access (storage-condition) ((address :initarg :address) (write-p :initform nil :initarg :write-p)) (:report (lambda (c s) (with-slots (address write-p) c (format s "Fault during ~a memory address #x~x" (if write-p "write to" "read of") address))))) (define-condition invalid-memory-operation (storage-condition) () (:report (lambda (c s) (declare (ignore c)) (format s "Invalid memory operation.")))) (define-condition write-to-watched-object (storage-condition) ((object :initform nil :initarg :object :reader write-to-watched-object-object) (offset :initarg :offset :reader write-to-watched-object-offset) (instruction :initarg :instruction :reader write-to-watched-object-instruction)) (:report report-write-to-watched-object)) (defun report-write-to-watched-object (c s) (with-slots (object offset instruction) c (cond ((uvectorp object) (let* ((count (uvsize object)) (nbytes (if (ivectorp object) (subtag-bytes (typecode object) count) (* count target::node-size))) (bytes-per-element (/ nbytes count)) (offset (- offset target::misc-data-offset)) (index (/ offset bytes-per-element))) (format s "Write to watched uvector ~s at " object) (if (fixnump index) (format s "index ~s" index) (format s "an apparently unaligned byte offset ~s" offset)))) ((consp object) (format s "Write to ~a watched cons cell ~s" (cond ((= offset target::cons.cdr) "the CDR of") ((= offset target::cons.car) "the CAR of") (t (format nil "an apparently unaligned byte offset (~s) into" offset))) object)) (t (format s "Write to a strange object ~s at byte offset ~s" object offset))) (when instruction (format s "~&Faulting instruction: ~s" instruction)))) (define-condition allocation-disabled (storage-condition) () (:report (lambda (c s) (declare (ignore c)) (format s "Attempt to heap-allocate a lisp object when heap allocation is disabled.")))) (define-condition vector-size-limitation (storage-condition) ((subtag :initarg :subtag) (element-count :initarg :element-count)) (:report (lambda (c s) (let* ((subtag (slot-value c 'subtag)) (element-count (slot-value c 'element-count)) (typename (if (eql subtag target::subtag-bignum) 'bignum (if (eql subtag target::subtag-simple-vector) 'simple-vector (if (eql subtag target::subtag-simple-base-string) 'string (if (> subtag target::subtag-simple-vector) `(simple-array ,(element-subtype-type subtag) (*)) `(ccl::uvector ,subtag)))))) (qualifier (if (eql subtag target::subtag-bignum) "32-bit " ""))) (format s "Cannot allocate a ~s with ~d elements.~&Objects of type ~s can can have at most ~&~d ~aelements in this implementation." typename element-count (copy-tree typename) (1- target::array-total-size-limit) qualifier))))) (define-condition type-error (error) ((datum :initarg :datum) (expected-type :initarg :expected-type :reader type-error-expected-type) (format-control :initarg :format-control :initform (%rsc-string $xwrongtype) :reader type-error-format-control)) (:report (lambda (c s) (format s (type-error-format-control c) (type-error-datum c) (type-error-expected-type c))))) (define-condition bad-slot-type (type-error) ((slot-definition :initform nil :initarg :slot-definition) (instance :initform nil :initarg :instance)) (:report (lambda (c s) (format s "The value ~s can not be used to set the value of the slot ~s in ~s, because it is not of type ~s. " (type-error-datum c) (slot-definition-name (slot-value c 'slot-definition)) (slot-value c 'instance) (type-error-expected-type c))))) (define-condition bad-slot-type-from-initform (bad-slot-type) () (:report (lambda (c s) (let* ((slotd (slot-value c 'slot-definition))) (format s "The value ~s, derived from the initform ~s, can not be used to set the value of the slot ~s in ~s, because it is not of type ~s. " (type-error-datum c) (slot-definition-initform slotd) (slot-definition-name slotd) (slot-value c 'instance) (type-error-expected-type c)))))) (define-condition bad-slot-type-from-initarg (bad-slot-type) ((initarg-name :initarg :initarg-name)) (:report (lambda (c s) (let* ((slotd (slot-value c 'slot-definition))) (format s "The value ~s, derived from the initarg ~s, can not be used to set the value of the slot ~s in ~s, because it is not of type ~s. " (type-error-datum c) (slot-value c 'initarg-name) (slot-definition-name slotd) (slot-value c 'instance) (type-error-expected-type c)))))) (define-condition improper-list (type-error) ((expected-type :initform '(satisfies proper-list-p) :reader type-error-expected-type))) (define-condition cant-construct-arglist (improper-list) ()) (let* ((magic-token '("Unbound"))) (defmethod type-error-datum ((c type-error)) (let* ((datum-slot (slot-value c 'datum))) (if (eq magic-token datum-slot) (%unbound-marker-8) datum-slot))) (defun signal-type-error (datum expected &optional (format-string (%rsc-string $xwrongtype))) (let ((error #'error)) (funcall error (make-condition 'type-error :format-control format-string :datum (if (eq datum (%unbound-marker-8)) magic-token datum) :expected-type (%type-error-type expected))))) ) (define-condition sequence-index-type-error (type-error) ((sequence :initarg :sequence)) (:report (lambda (c s) (format s "~s is not a valid sequence index for ~s" (type-error-datum c) (slot-value c 'sequence))))) (define-condition invalid-subtype-error (type-error) () (:report (lambda (c s) (format s "The type specifier ~S is not determinably a subtype of the type ~S" (type-error-datum c) (type-error-expected-type c))))) (define-condition simple-type-error (simple-condition type-error) ()) (define-condition array-element-type-error (simple-type-error) ((array :initarg :array :reader array-element-type-error-array)) (:report (lambda (c s) (format s (simple-condition-format-control c) (type-error-datum c) (array-element-type-error-array c))))) (define-condition program-error (error) ()) (define-condition simple-program-error (simple-condition program-error) ((context :initarg :context :reader simple-program-error-context :initform nil))) (define-condition invalid-type-specifier (program-error) ((typespec :initarg :typespec :reader invalid-type-specifier-typespec)) (:report (lambda (c s) (with-slots (typespec) c (format s "Invalid type specifier: ~s ." typespec))))) (defun signal-program-error (string &rest args) (let* ((e #'error)) (funcall e (make-condition 'simple-program-error :format-control (if (fixnump string) (%rsc-string string) string) :format-arguments args)))) (define-condition simple-destructuring-error (simple-program-error) ()) (define-condition wrong-number-of-arguments (program-error) ((nargs :initform nil :initarg :nargs :reader wrong-number-of-arguments-nargs) (fn :initform nil :initarg :fn :reader wrong-number-of-arguments-fn)) (:report report-argument-mismatch)) (define-condition too-many-arguments (wrong-number-of-arguments) ()) (define-condition too-few-arguments (wrong-number-of-arguments) ()) (defun report-argument-mismatch (c s) (let* ((nargs-provided (wrong-number-of-arguments-nargs c)) (fn (wrong-number-of-arguments-fn c)) (too-many (typep c 'too-many-arguments))) (multiple-value-bind (min max scaled-nargs) (min-max-actual-args fn nargs-provided) (if (not min) (progn (format s "Function ~s called with too ~a arguments. " fn (if too-many "many" "few"))) (if too-many (format s "Too many arguments in call to ~s:~&~d argument~:p provided, at most ~d accepted. " fn scaled-nargs max) (format s "Too few arguments in call to ~s:~&~d argument~:p provided, at least ~d required. " fn scaled-nargs min)))))) (define-condition compile-time-program-error (simple-program-error) (:report (lambda (c s) (format s "While compiling ~a :~%~a" (simple-program-error-context c) (apply #'format nil (simple-condition-format-control c) (simple-condition-format-arguments c)))))) (define-condition compile-time-error (simple-error) ((context :initarg :context :reader compile-time-error-context)) (:report (lambda (c s) (format s "While compiling ~a :~%~a" (compile-time-error-context c) (format nil "~a" c))))) (define-condition control-error (error) ()) (define-condition cant-throw-error (control-error) ((tag :initarg :tag)) (:report (lambda (c s) (format s "Can't throw to tag ~s" (slot-value c 'tag))))) (define-condition inactive-restart (control-error) ((restart-name :initarg :restart-name)) (:report (lambda (c s) (format s "Restart ~s is not active" (slot-value c 'restart-name))))) (define-condition lock-protocol-error (control-error) ((lock :initarg :lock))) (define-condition not-lock-owner (lock-protocol-error) () (:report (lambda (c s) (format s "Current process ~s does not own lock ~s" *current-process* (slot-value c 'lock))))) (define-condition not-locked (lock-protocol-error) () (:report (lambda (c s) (format s "Lock ~s isn't locked." (slot-value c 'lock))))) (define-condition deadlock (lock-protocol-error) () (:report (lambda (c s) (format s "Requested operation on ~s would cause deadlock." (slot-value c 'lock))))) (define-condition package-error (error) ((package :initarg :package :reader package-error-package))) (define-condition no-such-package (package-error) () (:report (lambda (c s) (format s (%rsc-string $xnopkg) (package-error-package c))))) (define-condition unintern-conflict-error (package-error) ((sym-to-unintern :initarg :sym) (conflicting-syms :initarg :conflicts)) (:report (lambda (c s) (format s (%rsc-string $xunintc) (slot-value c 'sym-to-unintern) (package-error-package c) (slot-value c 'conflicting-syms))))) (define-condition simple-package-error (package-error simple-condition) ()) (defun signal-package-error (package format-control &rest format-args) (error 'simple-package-error :package package :format-control format-control :format-arguments format-args)) (defun signal-package-cerror (package continue-string format-control &rest format-args) (cerror continue-string 'simple-package-error :package package :format-control format-control :format-arguments format-args)) (define-condition import-conflict-error (package-error) ((imported-sym :initarg :imported-sym) (conflicting-sym :initarg :conflicting-sym) (conflict-external-p :initarg :conflict-external)) (:report (lambda (c s) (format s (%rsc-string (if (slot-value c 'conflict-external-p) $ximprtcx $ximprtc)) (slot-value c 'imported-sym) (package-error-package c) (slot-value c 'conflicting-sym))))) (define-condition use-package-conflict-error (package-error) ((package-to-use :initarg :package-to-use) (conflicts :initarg :conflicts) (external-p :initarg :external-p)) (:report (lambda (c s) (format s (%rsc-string (if (slot-value c 'external-p) $xusecX $xusec)) (slot-value c 'package-to-use) (package-error-package c) (slot-value c 'conflicts))))) (define-condition export-conflict-error (package-error) ((conflicts :initarg :conflicts)) (:report (lambda (c s) (format s "Name conflict~p detected by ~A :" (length (slot-value c 'conflicts)) 'export) (let* ((package (package-error-package c))) (dolist (conflict (slot-value c 'conflicts)) (destructuring-bind (inherited-p sym-to-export using-package conflicting-sym) conflict (format s "~&~A'ing ~S from ~S would cause a name conflict with ~&~ the ~a symbol ~S in the package ~s, which uses ~S." 'export sym-to-export package (if inherited-p "inherited" "present") conflicting-sym using-package package))))))) (define-condition export-requires-import (package-error) ((to-be-imported :initarg :to-be-imported)) (:report (lambda (c s) (let* ((p (package-error-package c))) (format s "The following symbols need to be imported to ~S before they can be exported ~& from that package:~%~s:" p (slot-value c 'to-be-imported)))))) (define-condition package-name-conflict-error (package-error simple-error) ()) (define-condition package-is-used-by (package-error) ((using-packages :initarg :using-packages)) (:report (lambda (c s) (format s "~S is used by ~S" (package-error-package c) (slot-value c 'using-packages))))) (define-condition symbol-name-not-accessible (package-error) ((symbol-name :initarg :symbol-name)) (:report (lambda (c s) (format s "No aymbol named ~S is accessible in package ~s" (slot-value c 'symbol-name) (package-error-package c))))) (define-condition stream-error (error) ((stream :initarg :stream :reader stream-error-stream))) (defun stream-error-context (condition) (let* ((stream (stream-error-stream condition))) (with-output-to-string (s) (format s "on ~s" stream) (let* ((pos (ignore-errors (stream-position stream)))) (when pos (format s ", near position ~d" pos))) (let* ((surrounding (stream-surrounding-characters stream))) (when surrounding (format s ", within ~s" surrounding)))))) (define-condition parse-error (error) ()) (define-condition parse-integer-not-integer-string (parse-error) ((string :initarg :string)) (:report (lambda (c s) (format s "Not an integer string: ~s" (slot-value c 'string))))) (define-condition reader-error (parse-error stream-error) ()) (define-condition end-of-file (stream-error) () (:report (lambda (c s) (format s "Unexpected end of file ~a" (stream-error-context c))))) (define-condition stream-is-closed-error (stream-error) () (:report (lambda (condition stream) (format stream "~s is closed" (stream-error-stream condition))))) (define-condition io-timeout (stream-error) ()) (define-condition input-timeout (io-timeout) () (:report (lambda (c s) (format s "Input timeout on ~s" (stream-error-stream c))))) (define-condition output-timeout (io-timeout) () (:report (lambda (c s) (format s "Output timeout on ~s" (stream-error-stream c))))) (define-condition communication-deadline-expired (io-timeout) () (:report (lambda (c s) (format s "Communication deadline timeout on ~s" (stream-error-stream c))))) (define-condition impossible-number (reader-error) ((token :initarg :token :reader impossible-number-token) (condition :initarg :condition :reader impossible-number-condition)) (:report (lambda (c s) (format s "Condition of type ~s raised ~&while trying to parse numeric token ~s ~&~s" (type-of (impossible-number-condition c)) (impossible-number-token c) (stream-error-context c))))) (define-condition simple-stream-error (stream-error simple-condition) () (:report (lambda (c s) (format s "~a : ~&~a" (stream-error-context c) (apply #'format nil (simple-condition-format-control c) (simple-condition-format-arguments c)))))) (define-condition file-error (error) ((pathname :initarg :pathname :initform "<unspecified>" :reader file-error-pathname) (error-type :initarg :error-type :initform "File error on file ~S")) (:report (lambda (c s) (format s (slot-value c 'error-type) (file-error-pathname c))))) (define-condition simple-file-error (simple-condition file-error) () (:report (lambda (c s) (apply #'format s (slot-value c 'error-type) (file-error-pathname c) (simple-condition-format-arguments c))))) (define-condition namestring-parse-error (error) ((complaint :reader namestring-parse-error-complaint :initarg :complaint) (arguments :reader namestring-parse-error-arguments :initarg :arguments :initform nil) (namestring :reader namestring-parse-error-namestring :initarg :namestring) (offset :reader namestring-parse-error-offset :initarg :offset)) (:report (lambda (condition stream) (format stream "Parse error in namestring: ~?~% ~A~% ~V@T^" (namestring-parse-error-complaint condition) (namestring-parse-error-arguments condition) (namestring-parse-error-namestring condition) (namestring-parse-error-offset condition))))) (define-condition cell-error (error) ((name :initarg :name :reader cell-error-name) (error-type :initarg :error-type :initform "Cell error" :reader cell-error-type)) (:report (lambda (c s) (format s "~A: ~S" (cell-error-type c) (cell-error-name c))))) (define-condition unbound-variable (cell-error) ((error-type :initform "Unbound variable"))) (define-condition undefined-function (cell-error) ((error-type :initform "Undefined function"))) (define-condition undefined-function-call (control-error undefined-function) ((function-arguments :initarg :function-arguments :reader undefined-function-call-arguments)) (:report (lambda (c s) (format s "Undefined function ~S called with arguments ~:S ." (cell-error-name c) (undefined-function-call-arguments c))))) (define-condition call-special-operator-or-macro (undefined-function-call) () (:report (lambda (c s) (format s "Special operator or global macro-function ~s can't be FUNCALLed or APPLYed" (cell-error-name c))))) (define-condition unbound-slot (cell-error) ((instance :initarg :instance :accessor unbound-slot-instance)) (:report (lambda (c s) (format s "Slot ~s is unbound in ~s" (cell-error-name c) (unbound-slot-instance c))))) (define-condition arithmetic-error (error) ((operation :initform nil :initarg :operation :reader arithmetic-error-operation) (operands :initform nil :initarg :operands :reader arithmetic-error-operands) (status :initform nil :initarg :status :reader arithmetic-error-status)) (:report (lambda (c s) (format s "~S detected" (type-of c)) (let* ((operands (arithmetic-error-operands c))) (when operands (format s "~&performing ~A on ~:S" (arithmetic-error-operation c) operands)))))) (define-condition division-by-zero (arithmetic-error) ()) (define-condition floating-point-underflow (arithmetic-error) ()) (define-condition floating-point-overflow (arithmetic-error) ()) (define-condition floating-point-inexact (arithmetic-error) ()) (define-condition floating-point-invalid-operation (arithmetic-error) ()) (define-condition compiler-bug (simple-error) () (:report (lambda (c stream) (format stream "Compiler bug or inconsistency:~%") (apply #'format stream (simple-condition-format-control c) (simple-condition-format-arguments c))))) (define-condition external-process-creation-failure (serious-condition) ((proc :initarg :proc)) (:report (lambda (c stream) (with-slots (proc) c (let* ((code (external-process-%exit-code proc))) (format stream "Fork failed in ~s: ~a. " proc (if (eql code -1) "random lisp error" (%strerror code)))))))) (define-condition simple-reader-error (reader-error simple-error) () (:report (lambda (c output-stream) (format output-stream "Reader error ~a:~%~?" (stream-error-context c) (simple-condition-format-control c) (simple-condition-format-arguments c))))) (define-condition parse-unknown-type (condition) ((specifier :reader parse-unknown-type-specifier :initarg :specifier)) (:report (lambda (c s) (print-unreadable-object (c s :type t) (format s "unknown type ~A" (parse-unknown-type-specifier c)))))) (define-condition no-applicable-method-exists (error) ((gf :initarg :gf) (args :initarg :args)) (:report (lambda (c s) (with-slots (gf args) c (format s "There is no applicable method for the generic function:~% ~s~%when called with arguments:~% ~s" gf args))))) (defun restartp (thing) (istruct-typep thing 'restart)) (setf (type-predicate 'restart) 'restartp) (defmethod print-object ((restart restart) stream) (let ((report (%restart-report restart))) (cond ((or *print-escape* (null report)) (print-unreadable-object (restart stream :identity t) (format stream "~S ~S" 'restart (%restart-name restart)))) ((stringp report) (write-string report stream)) (t (funcall report stream))))) (defun %make-restart (name action report interactive test) (%cons-restart name action report interactive test)) (defun make-restart (vector name action-function &key report-function interactive-function test-function) (unless vector (setq vector (%cons-restart nil nil nil nil nil))) (setf (%restart-name vector) name (%restart-action vector) (require-type action-function 'function) (%restart-report vector) (if report-function (require-type report-function 'function)) (%restart-interactive vector) (if interactive-function (require-type interactive-function 'function)) (%restart-test vector) (if test-function (require-type test-function 'function))) vector) (defun restart-name (restart) "Return the name of the given restart object." (%restart-name (require-type restart 'restart))) (defun applicable-restart-p (restart condition) (let* ((pair (if condition (assq restart *condition-restarts*))) (test (%restart-test restart))) (and (or (null pair) (eq (%cdr pair) condition)) (or (null test) (funcall test condition))))) (defun compute-restarts (&optional condition &aux restarts) "Return a list of all the currently active restarts ordered from most recently established to less recently established. If CONDITION is specified, then only restarts associated with CONDITION (or with no condition) will be returned." (dolist (cluster %restarts% (nreverse restarts)) (dolist (restart cluster) (when (applicable-restart-p restart condition) (push restart restarts))))) (defun find-restart (name &optional condition) "Return the first active restart named NAME. If NAME names a restart, the restart is returned if it is currently active. If no such restart is found, NIL is returned. It is an error to supply NIL as a name. If CONDITION is specified and not NIL, then only restarts associated with that condition (or with no condition) will be returned." (if (typep name 'restart) (dolist (cluster %restarts%) (dolist (restart cluster) (if (eq restart name) (return-from find-restart restart)))) (dolist (cluster %restarts%) (dolist (restart cluster) (when (and (eq (restart-name restart) name) (applicable-restart-p restart condition)) (return-from find-restart restart)))))) (defun %active-restart (name) (dolist (cluster %restarts%) (dolist (restart cluster) (when (or (eq restart name) (let* ((rname (%restart-name restart))) (and (eq rname name) (applicable-restart-p restart nil)))) (return-from %active-restart (values restart cluster))))) (error 'inactive-restart :restart-name name)) (defun invoke-restart (restart &rest values) "Calls the function associated with the given restart, passing any given arguments. If the argument restart is not a restart or a currently active non-nil restart name, then a CONTROL-ERROR is signalled." (multiple-value-bind (restart tag) (%active-restart restart) (let ((fn (%restart-action restart))) (unless (null values) (%err-disp $xtminps)) (throw tag nil)) (throw tag (cons fn values))) (apply fn values)) (throw tag (values nil t))))))) (define-condition restart-failure (control-error) ((restart :initarg :restart :reader restart-failure-restart)) (:report (lambda (c s) (format s "The ~a restart failed to transfer control dynamically as expected." (restart-name (restart-failure-restart c)))))) (defun invoke-restart-no-return (restart &rest values) (declare (dynamic-extent values)) (apply #'invoke-restart restart values) (error 'restart-failure :restart restart)) (defun invoke-restart-interactively (restart) "Calls the function associated with the given restart, prompting for any necessary arguments. If the argument restart is not a restart or a currently active non-NIL restart name, then a CONTROL-ERROR is signalled." (let* ((restart (%active-restart restart))) (format *error-output* "~&Invoking restart: ~a~&" restart) (let* ((argfn (%restart-interactive restart)) (values (when argfn (funcall argfn)))) (apply #'invoke-restart restart values)))) (defun maybe-invoke-restart (restart value condition) (let ((restart (find-restart restart condition))) (when restart (invoke-restart restart value)))) (defun use-value (value &optional condition) "Transfer control and VALUE to a restart named USE-VALUE, or return NIL if none exists." (maybe-invoke-restart 'use-value value condition)) (defun store-value (value &optional condition) "Transfer control and VALUE to a restart named STORE-VALUE, or return NIL if none exists." (maybe-invoke-restart 'store-value value condition)) (defun condition-arg (thing args type) (cond ((condition-p thing) (if args (%err-disp $xtminps) thing)) ((symbolp thing) (apply #'make-condition thing args)) (t (make-condition type :format-control thing :format-arguments args)))) (defun make-condition (name &rest init-list) "Make an instance of a condition object using the specified initargs." (declare (dynamic-extent init-list)) (if (subtypep name 'condition) (apply #'make-instance name init-list) (let ((class (if (classp name) name (unless (class-finalized-p class) (error "~S is not a condition class" class)))) (defmethod print-object ((c condition) stream) (if *print-escape* (call-next-method) (report-condition c stream))) (defmethod report-condition ((c condition) stream) (princ (cond ((typep c 'error) "Error ") ((typep c 'warning) "Warning ") (t "Condition ")) stream) (let ((*print-escape* t)) (print-object c stream))) (defun signal-simple-condition (class-name format-string &rest args) (funcall e (make-condition class-name :format-control format-string :format-arguments args)))) (defun signal-simple-program-error (format-string &rest args) (apply #'signal-simple-condition 'simple-program-error format-string args)) (defun %last-fn-on-stack (&optional (number 0) (s (%get-frame-ptr))) (let* ((fn nil)) (let ((p s)) (dotimes (i number) (declare (fixnum i)) (unless (setq p (parent-frame p nil)) (return))) (do* ((i number (1+ i))) ((null p)) (if (setq fn (cfp-lfun p)) (return (values fn i)) (setq p (parent-frame p nil))))))) (defun %err-fn-name (lfun) "given an lfun returns the name or the string \"Unknown\"" (if (lfunp lfun) (or (lfun-name lfun) lfun) (or lfun "Unknown"))) (defun %real-err-fn-name (error-pointer) (multiple-value-bind (fn p) (%last-fn-on-stack 0 error-pointer) (let ((name (%err-fn-name fn))) (if (and (memq name '( call-check-regs)) p) (%err-fn-name (%last-fn-on-stack (1+ p) error-pointer)) name)))) (defun find-unique-homonyms (name &optional (test (constantly t))) (delete-duplicates (loop with symbol = (if (consp name) (second name) name) with pname = (symbol-name symbol) for package in (list-all-packages) for other-package-symbol = (find-symbol pname package) for canditate = (and other-package-symbol (neq other-package-symbol symbol) (if (consp name) (list (first name) other-package-symbol) other-package-symbol)) when (and canditate (funcall test canditate)) collect canditate) :test #'equal)) (def-kernel-restart $xvunbnd %default-unbound-variable-restarts (frame-ptr cell-name) (unless *level-1-loaded* (let ((condition (make-condition 'unbound-variable :name cell-name)) (other-variables (find-unique-homonyms cell-name (lambda (name) (and (not (keywordp name)) (boundp name)))))) (flet ((new-value () (catch-cancel (return-from new-value (list (read-from-string (get-string-from-user (format nil "New value for ~s : " cell-name)))))) (restart-case (%error condition nil frame-ptr) (continue () :report (lambda (s) (format s "Retry getting the value of ~S." cell-name)) (symbol-value cell-name)) (use-homonym (homonym) :test (lambda (c) (and (or (null c) (eq c condition)) other-variables)) :report (lambda (s) (if (= 1 (length other-variables)) (format s "Use the value of ~s this time." (first other-variables)) (format s "Use one of the homonyms ~{~S or ~} this time." other-variables))) :interactive (lambda () (if (= 1 (length other-variables)) other-variables (select-item-from-list other-variables :window-title "Select homonym to use"))) (symbol-value homonym)) (use-value (value) :interactive new-value :report (lambda (s) (format s "Specify a value of ~S to use this time." cell-name)) value) (store-value (value) :interactive new-value :report (lambda (s) (format s "Specify a value of ~S to store and use." cell-name)) (setf (symbol-value cell-name) value)))))) (def-kernel-restart $xnopkg %default-no-package-restart (frame-ptr package-name) (or (and *autoload-lisp-package* (or (string-equal package-name "LISP") (string-equal package-name "USER")) (progn (require "LISP-PACKAGE") (find-package package-name))) (let* ((alias (or (%cdr (assoc package-name '(("LISP" . "COMMON-LISP") ("USER" . "CL-USER")) :test #'string-equal)) (if (packagep *package*) (package-name *package*)))) (condition (make-condition 'no-such-package :package package-name))) (flet ((try-again (p) (or (find-package p) (%kernel-restart $xnopkg p)))) (restart-case (restart-case (%error condition nil frame-ptr) (continue () :report (lambda (s) (format s "Retry finding package with name ~S." package-name)) (try-again package-name)) (use-value (value) :interactive (lambda () (block nil (catch-cancel (return (list (get-string-from-user "Find package named : ")))) (continue condition))) :report (lambda (s) (format s "Find specified package instead of ~S ." package-name)) (try-again value)) (make-nickname () :report (lambda (s) (format s "Make ~S be a nickname for package ~S." package-name alias)) (let ((p (try-again alias))) (push package-name (cdr (pkg.names p))) p))) (require-lisp-package () :test (lambda (c) (and (eq c condition) (or (string-equal package-name "LISP") (string-equal package-name "USER")))) :report (lambda (s) (format s "(require :lisp-package) and retry finding package ~s" package-name)) (require "LISP-PACKAGE") (try-again package-name))))))) (def-kernel-restart $xunintc unintern-conflict-restarts (frame-ptr sym package conflicts) (let ((condition (make-condition 'unintern-conflict-error :package package :sym sym :conflicts conflicts))) (restart-case (%error condition nil frame-ptr) (continue () :report (lambda (s) (format s "Try again to unintern ~s from ~s" sym package)) (unintern sym package)) (do-shadowing-import (ssym) :report (lambda (s) (format s "SHADOWING-IMPORT one of ~S in ~S." conflicts package)) :interactive (lambda () (block nil (catch-cancel (return (select-item-from-list conflicts :window-title (format nil "Shadowing-import one of the following in ~s" package) :table-print-function #'prin1))) (continue condition))) (shadowing-import (list ssym) package))))) (def-kernel-restart $xusec blub (frame-ptr package-to-use using-package conflicts) (resolve-use-package-conflict-error frame-ptr package-to-use using-package conflicts nil)) (def-kernel-restart $xusecX blub (frame-ptr package-to-use using-package conflicts) (resolve-use-package-conflict-error frame-ptr package-to-use using-package conflicts t)) (defun resolve-use-package-conflict-error (frame-ptr package-to-use using-package conflicts external-p) (let ((condition (make-condition 'use-package-conflict-error :package using-package :package-to-use package-to-use :conflicts conflicts :external-p external-p))) (flet ((external-test (&rest ignore) (declare (ignore ignore)) external-p) (present-test (&rest ignore) (declare (ignore ignore)) (not external-p))) (declare (dynamic-extent #'present-test #'external-test)) (restart-case (%error condition nil frame-ptr) (continue () :report (lambda (s) (format s "Try again to use ~s in ~s" package-to-use using-package))) (resolve-by-shadowing-import (&rest shadowing-imports) :test external-test :interactive (lambda () (mapcar #'(lambda (pair) (block nil (catch-cancel (return (car (select-item-from-list pair :window-title (format nil "Shadowing-import one of the following in ~s" using-package) :table-print-function #'prin1)))) (continue condition))) conflicts)) :report (lambda (s) (format s "SHADOWING-IMPORT one of each pair of conflicting symbols.")) (shadowing-import shadowing-imports using-package)) (unintern-all () :test present-test :report (lambda (s) (format s "UNINTERN all conflicting symbols from ~S" using-package)) (dolist (c conflicts) (unintern (car c) using-package))) (shadow-all () :test present-test :report (lambda (s) (format s "SHADOW all conflicting symbols in ~S" using-package)) (dolist (c conflicts) (shadow-1 using-package (car c)))) (resolve-by-unintern-or-shadow (&rest dispositions) :test present-test :interactive (lambda () (mapcar #'(lambda (pair) (let* ((present-sym (car pair))) (block nil (catch-cancel (return (car (select-item-from-list (list 'shadow 'unintern) :window-title (format nil "SHADOW ~S in, or UNINTERN ~S from ~S" present-sym present-sym using-package) :table-print-function #'prin1))) (continue condition))))) conflicts)) :report (lambda (s) (format s "SHADOW or UNINTERN the conflicting symbols in ~S." using-package)) (dolist (d dispositions) (let* ((sym (car (pop conflicts)))) (if (eq d 'shadow) (shadow-1 using-package sym) (unintern sym using-package))))))))) (defun resolve-export-conflicts (conflicts package) (let* ((first-inherited (caar conflicts)) (all-same (dolist (conflict (cdr conflicts) t) (unless (eq (car conflict) first-inherited) (return nil)))) (all-inherited (and all-same first-inherited)) (all-present (and all-same (not first-inherited))) (condition (make-condition 'export-conflict-error :conflicts conflicts :package package))) (flet ((check-again () (let* ((remaining-conflicts (check-export-conflicts (mapcar #'cadr conflicts) package))) (if remaining-conflicts (resolve-export-conflicts remaining-conflicts package))))) (restart-case (%error condition nil (%get-frame-ptr)) (resolve-all-by-shadowing-import-inherited () :test (lambda (&rest ignore) (declare (ignore ignore)) all-inherited) :report (lambda (s) (format s "SHADOWING-IMPORT all conflicting inherited symbol(s) in using package(s).")) (dolist (conflict conflicts (check-again)) (destructuring-bind (using-package inherited-sym) (cddr conflict) (shadowing-import-1 using-package inherited-sym)))) (resolve-all-by-shadowing-import-exported () :test (lambda (&rest ignore) (declare (ignore ignore)) all-inherited) :report (lambda (s) (format s "SHADOWING-IMPORT all conflicting symbol(s) to be exported in using package(s).")) (dolist (conflict conflicts (check-again)) (destructuring-bind (exported-sym using-package ignore) (cdr conflict) (declare (ignore ignore)) (shadowing-import-1 using-package exported-sym)))) (resolve-all-by-uninterning-present () :test (lambda (&rest ignore) (declare (ignore ignore)) all-present) :report (lambda (s) (format s "UNINTERN all present conflicting symbol(s) in using package(s).")) (dolist (conflict conflicts (check-again)) (destructuring-bind (using-package inherited-sym) (cddr conflict) (unintern inherited-sym using-package)))) (resolve-all-by-shadowing-present () :test (lambda (&rest ignore) (declare (ignore ignore)) all-present) :report (lambda (s) (format s "SHADOW all present conflicting symbol(s) in using package(s).")) (dolist (conflict conflicts (check-again)) (destructuring-bind (using-package inherited-sym) (cddr conflict) (shadow-1 using-package inherited-sym)))) (review-and-resolve (dispositions) :report (lambda (s) (format s "Review each name conflict and resolve individually.")) :interactive (lambda () (let* ((disp nil)) (block b (catch-cancel (dolist (conflict conflicts (return-from b (list disp))) (destructuring-bind (inherited-p exported-sym using-package conflicting-sym) conflict (let* ((syms (list exported-sym conflicting-sym))) (if inherited-p (push (list 'shadowing-import (select-item-from-list syms :window-title (format nil "Shadowing-import one of the following in ~s" using-package) :table-print-function #'prin1) using-package) disp) (let* ((selection (car (select-item-from-list syms :window-title (format nil "Shadow ~S or unintern ~s in ~s" exported-sym conflicting-sym using-package) :table-print-function #'prin1)))) (push (if (eq selection 'exported-sym) (list 'shadow (list exported-sym) using-package) (list 'unintern conflicting-sym using-package)) disp))))))) nil))) (dolist (disp dispositions (check-again)) (apply (car disp) (cdr disp)))))))) (def-kernel-restart $xwrongtype default-require-type-restarts (frame-ptr value typespec) (setq typespec (%type-error-type typespec)) (let ((condition (make-condition 'type-error :datum value :expected-type typespec))) (restart-case (%error condition nil frame-ptr) (use-value (newval) :report (lambda (s) (format s "Use a new value of type ~s instead of ~s." typespec value)) :interactive (lambda () (format *query-io* "~&New value of type ~S :" typespec) (list (read *query-io*))) (require-type newval typespec))))) (def-kernel-restart $xudfcall default-undefined-function-call-restarts (frame-ptr function-name args) (unless *level-1-loaded* (let ((condition (make-condition 'undefined-function-call :name function-name :function-arguments args)) (other-functions (find-unique-homonyms function-name #'fboundp))) (restart-case (%error condition nil frame-ptr) (continue () :report (lambda (s) (format s "Retry applying ~S to ~S." function-name args)) (apply function-name args)) (use-homonym (function-name) :test (lambda (c) (and (or (null c) (eq c condition)) other-functions)) :report (lambda (s) (if (= 1 (length other-functions)) (format s "Apply ~s to ~S this time." (first other-functions) args) (format s "Apply one of ~{~S or ~} to ~S this time." other-functions args))) :interactive (lambda () (if (= 1 (length other-functions)) other-functions (select-item-from-list other-functions :window-title "Select homonym to use"))) (apply (fdefinition function-name) args)) (use-value (function) :interactive (lambda () (format *query-io* "Function to apply instead of ~s :" function-name) (let ((f (read *query-io*))) (list (coerce f 'function)))) :report (lambda (s) (format s "Apply specified function to ~S this time." args)) (apply function args)) (store-value (function) :interactive (lambda () (format *query-io* "Function to apply as new definition of ~s :" function-name) (let ((f (read *query-io*))) (list (coerce f 'function)))) :report (lambda (s) (format s "Specify a function to use as the definition of ~S." function-name)) (apply (setf (symbol-function function-name) function) args))))) (defun %check-type (value typespec placename typename) (let ((condition (make-condition 'type-error :datum value :expected-type typespec))) (if typename (setf (slot-value condition 'format-control) (format nil "value ~~S is not ~A (~~S)." typename))) (restart-case (%error condition nil (%get-frame-ptr)) (store-value (newval) :report (lambda (s) (format s "Assign a new value of type ~a to ~s" typespec placename)) :interactive (lambda () (format *query-io* "~&New value for ~S :" placename) (list (eval (read)))) newval)))) (defun ensure-value-of-type (value typespec placename &optional typename) (tagbody again (unless (typep value typespec) (let ((condition (make-condition 'type-error :datum value :expected-type typespec))) (if typename (setf (slot-value condition 'format-control) (format nil "value ~~S is not ~A (~~S)." typename))) (restart-case (%error condition nil (%get-frame-ptr)) (store-value (newval) :report (lambda (s) (format s "Assign a new value of type ~a to ~s" typespec placename)) :interactive (lambda () (format *query-io* "~&New value for ~S :" placename) (list (eval (read)))) (setq value newval) (go again)))))) value) (defparameter *kernel-simple-error-classes* (list (cons $xcalltoofew 'simple-destructuring-error) (cons $xcalltoomany 'simple-destructuring-error) (cons $xstkover 'stack-overflow-condition) (cons $xmemfull 'simple-storage-condition) this one needs 2 args (cons $xdivzro 'division-by-zero) (cons $xflovfl 'floating-point-overflow) (cons $xfunbnd 'undefined-function) (cons $xbadkeys 'simple-program-error) (cons $xcallnomatch 'simple-program-error) (cons $xnotfun 'call-special-operator-or-macro) (cons $xaccessnth 'sequence-index-type-error) (cons $ximproperlist 'improper-list) (cons $xnospread 'cant-construct-arglist) (cons $xnotelt 'array-element-type-error) )) (defparameter *simple-error-types* (vector nil 'simple-program-error 'simple-file-error)) (defconstant $pgm-err #x10000) (defparameter %type-error-typespecs% #(array bignum fixnum character integer list number sequence simple-string simple-vector string symbol macptr real cons unsigned-byte (integer 2 36) float rational ratio short-float double-float complex vector simple-base-string function (unsigned-byte 16) (unsigned-byte 8) (unsigned-byte 32) (signed-byte 32) (signed-byte 16) (signed-byte 8) base-char bit (unsigned-byte 64) (signed-byte 64) (unsigned-byte 56) (simple-array double-float (* *)) (simple-array single-float (* *)) (mod #x110000) (array t) (array bit) (array (signed-byte 8)) (array (unsigned-byte 8)) (array (signed-byte 16)) (array (unsigned-byte 16)) (array (signed-byte 32)) (array (unsigned-byte 32)) (array (signed-byte 64)) (array (unsigned-byte 64)) (array fixnum) (array single-float) (array double-float) (array character) (array t (* *)) (array bit (* *)) (array (signed-byte 8) (* *)) (array (unsigned-byte 8) (* *)) (array (signed-byte 16) (* *)) (array (unsigned-byte 16) (* *)) (array (signed-byte 32) (* *)) (array (unsigned-byte 32) (* *)) (array (signed-byte 64) (* *)) (array (unsigned-byte 64) (* *)) (array fixnum (* *)) (array single-float (* *)) (array double-float (* *)) (array character (* *)) (simple-array t (* *)) (simple-array bit (* *)) (simple-array (signed-byte 8) (* *)) (simple-array (unsigned-byte 8) (* *)) (simple-array (signed-byte 16) (* *)) (simple-array (unsigned-byte 16) (* *)) (simple-array (signed-byte 32) (* *)) (simple-array (unsigned-byte 32) (* *)) (simple-array (signed-byte 64) (* *)) (simple-array (unsigned-byte 64) (* *)) (simple-array fixnum (* *)) (simple-array character (* *)) (array t (* * *)) (array bit (* * *)) (array (signed-byte 8) (* * *)) (array (unsigned-byte 8) (* * *)) (array (signed-byte 16) (* * *)) (array (unsigned-byte 16) (* * *)) (array (signed-byte 32) (* * *)) (array (unsigned-byte 32) (* * *)) (array (signed-byte 64) (* * *)) (array (unsigned-byte 64) (* * *)) (array fixnum (* * *)) (array single-float (* * *)) (array double-float (* * *)) (array character (* * *)) (simple-array t (* * *)) (simple-array bit (* * *)) (simple-array (signed-byte 8) (* * *)) (simple-array (unsigned-byte 8) (* * *)) (simple-array (signed-byte 16) (* * *)) (simple-array (unsigned-byte 16) (* * *)) (simple-array (signed-byte 32) (* * *)) (simple-array (unsigned-byte 32) (* * *)) (simple-array (signed-byte 64) (* * *)) (simple-array (unsigned-byte 64) (* * *)) (simple-array fixnum (* * *)) (simple-array single-float (* * *)) (simple-array double-float (* * *)) (simple-array character (* * *)) (vector t) bit-vector (vector (signed-byte 8)) (vector (unsigned-byte 8)) (vector (signed-byte 16)) (vector (unsigned-byte 16)) (vector (signed-byte 32)) (vector (unsigned-byte 32)) (vector (signed-byte 64)) (vector (unsigned-byte 64)) (vector fixnum) (vector single-float) (vector double-float) )) (defun %type-error-type (type) (if (fixnump type) (svref %type-error-typespecs% type) type)) (defun %typespec-id (typespec) (flet ((type-equivalent (t1 t2) (ignore-errors (and (subtypep t1 t2) (subtypep t2 t1))))) (position typespec %type-error-typespecs% :test #'type-equivalent))) (defmethod condition-p ((x t)) nil) (defmethod condition-p ((x condition)) t) (let* ((globals ())) (defun %check-error-globals () (let ((vars ()) (valfs ()) (oldvals ())) (dolist (g globals (values vars valfs oldvals)) (destructuring-bind (sym predicate newvalf) g (let* ((boundp (boundp sym)) (oldval (if boundp (symbol-value sym) (%unbound-marker-8)))) (unless (and boundp (funcall predicate oldval)) (push sym vars) (push oldval oldvals) (push newvalf valfs))))))) (defun check-error-global (sym checkfn newvalfn) (setq sym (require-type sym 'symbol) checkfn (require-type checkfn 'function) newvalfn (require-type newvalfn 'function)) (let ((found (assq sym globals))) (if found (setf (cadr found) checkfn (caddr found) newvalfn) (push (list sym checkfn newvalfn) globals)) sym)) ) (check-error-global '*package* #'packagep #'(lambda () (find-package "CL-USER"))) (flet ((io-stream-p (x) (and (streamp x) (eq (stream-direction x) :io))) (is-input-stream-p (x) (and (streamp x) (input-stream-p x))) (is-output-stream-p (x) (and (streamp x) (output-stream-p x))) (default-terminal-io () (make-echoing-two-way-stream *stdin* *stdout*)) (terminal-io () *terminal-io*) (standard-output () *standard-output*)) * terminal - io * first and * trace - output * last (check-error-global '*terminal-io* #'io-stream-p #'default-terminal-io) (check-error-global '*query-io* #'io-stream-p #'terminal-io) (check-error-global '*debug-io* #'io-stream-p #'terminal-io) (check-error-global '*standard-input* #'is-input-stream-p #'terminal-io) (check-error-global '*standard-output* #'is-output-stream-p #'terminal-io) (check-error-global '*error-output* #'is-output-stream-p #'standard-output) (check-error-global '*trace-output* #'is-output-stream-p #'standard-output))
c7626f6c0e2b9bcfa19842bbcfa5e7bb958a962858b17810dced6d540ad56e62
BitGameEN/bitgamex
hello2.erl
%% File : hello2.erl %% File : luerl/examples/hello/hello2.erl Purpose : Demonstration of the Luerl interface . Author : Use : $ cd examples / hello & & erlc hello2.erl & & erl -pa .. / .. /ebin -s hello2 run -s init stop -noshell %% Or : $ make examples -module(hello2). -export([run/0]). run() -> io:format("-------------------------------------------~n"), io:format("This is an assortment of samples and tests.~n"), io:format("-------------------------------------------~n"), io:format("It's a comprehensive demo of the interface.~n"), io:format("Please check out the source to learn more.~n"), % execute a string luerl:eval("print(\"(1) Hello, Robert!\")"), luerl:eval(<<"print(\"(2) Hello, Roberto!\")">>), luerl:do("print(\"(3) Hej, Robert!\")"), luerl:do(<<"print(\"(4) Olà, Roberto!\")">>), % execute a string, get a result {ok,A} = luerl:eval("return 1 + 1"), {ok,A} = luerl:eval(<<"return 1 + 1">>), io:format("(5) 1 + 1 = ~p!~n", [A]), % execute a file luerl:evalfile("./hello2-1.lua"), luerl:dofile("./hello2-1.lua"), % execute a file, get a result {ok,B} = luerl:evalfile("./hello2-2.lua"), {B,_} = luerl:dofile("./hello2-2.lua"), io:format("(7) 2137 * 42 = ~p?~n", [B]), % execute a standard function luerl:call_function([print], [<<"(8) Hello, standard print function!">>]), luerl:call_function([print], [<<"(9) Hello, standard print function!">>], luerl:init()), {Result1,_} = luerl:call_function([table,pack], [<<"a">>,<<"b">>,42]), {Result1,_} = luerl:call_function([table,pack], [<<"a">>,<<"b">>,42], luerl:init()), io:format("(10) ~p?~n", [Result1]), separately parse , then execute ( doubles ( 11 ) and Chunk1 as assertion ) St1A = luerl:init(), {ok,Chunk1,St1B} = luerl:load("print(\"(11) Hello, Chunk 1!\")", St1A), {ok,Chunk1,_} = luerl:load(<<"print(\"(11) Hello, Chunk 1!\")">>, St1A), luerl:eval(Chunk1, St1B), luerl:do(Chunk1, St1B), separately parse , then execute ( doubles ( 12 ) and Chunk2 as assertion ) St2A = luerl:init(), {ok,Chunk2,St2B} = luerl:load("function chunk2() print(\"(12) Hello, Chunk 2!\") end", St2A), {ok,Chunk2,_} = luerl:load(<<"function chunk2() print(\"(12) Hello, Chunk 2!\") end">>, St2A), {ok,Result2} = luerl:eval(Chunk2, St2B), {Result2,St2C} = luerl:do(Chunk2, St2B), {Result2,St2D} = luerl:do(<<"function chunk2() print(\"(12) Hello, Chunk 2!\") end">>, St2A), luerl:call_function([chunk2], [], St2C), luerl:call_function([chunk2], [], St2D), % separately parse, then execute a file. The file defines a function no() St3A = luerl:init(), {ok,Chunk3,St3B} = luerl:loadfile("./hello2-3.lua", St3A), {ok,Result3} = luerl:eval(Chunk3, St3B), {Result3,St3C} = luerl:do(Chunk3, St3B), {[],_} = luerl:call_function([no], [], St3C), % separately parse, then execute, get a result St4A = luerl:init(), {ok,Chunk4,St4B} = luerl:load("return '(17b) Marvelous wheater today, isn°t it!'", St4A), {ok,Chunk4,_} = luerl:load(<<"return '(17b) Marvelous wheater today, isn°t it!'">>, St4A), {ok,Result4} = luerl:eval(Chunk4, St4B), {Result4,_} = luerl:do(Chunk4, St4B), io:format("(17) And I say: ~p~n", [Result4]), % separately parse, then execute a file, get a result St5A = luerl:init(), {ok,Chunk5,St5B} = luerl:loadfile("./hello2-4.lua", St5A), {ok,Result5} = luerl:eval(Chunk5, St5B), {Result5,_} = luerl:do(Chunk5, St5B), io:format("(18) And he says: ~p~n", [Result5]), Same as above , passing State in all times . % create state New = luerl:init(), {_,_New2} = luerl:do("print '(19) hello generix'", New), % change state {_,State0} = luerl:do("a = 1000", New), {_,State01} = luerl:do("a = 1000", New), % execute a string, using passed in State0 luerl:eval("print('(20) ' .. a)", State0), luerl:eval(<<"print('(21) ' .. a+1)">>, State0), luerl:do("print('(22) ' .. a+2)", State0), luerl:do(<<"print('(23) ' .. a+3)">>, State0), % execute a string, get a result from passed in State0 {ok,E} = luerl:eval("return 4 * a", State0), {ok,E} = luerl:eval(<<"return 4 * a">>, State0), {E,_} = luerl:do("return 4 * a", State0), {E,_} = luerl:do(<<"return 4 * a">>, State0), io:format("(24) 4 x a = ~p!~n", [E]), % execute a string, get a result, change State0 {Z,State02} = luerl:do("a = 123; return a * 3", State01), {Z,State03} = luerl:do(<<"return (3 * a)">>, State02), io:format("(25) a = ~p~n", [Z]), % execute a file using passed in state luerl:evalfile("./hello2-5.lua", State03), luerl:dofile("./hello2-5.lua", State03), % execute a file that changes the State0 {_,State04} = luerl:dofile("./hello2-6.lua", State03), luerl:do("print('(27) (b) ' .. a)", State04), % execute a file, get a result {ok,F} = luerl:evalfile("./hello2-7.lua", State04), {F,State05} = luerl:dofile("./hello2-7.lua", State04), io:format("(28) F: ~s~n", [F]), % execute a file that changes the State0, and get a value back {F,State06} = luerl:dofile("./hello2-7.lua", State05), io:format("(29) F: ~s = ", [F]), luerl:do("print('(30) F: ' .. a)", State06), % separately parse, then execute {ok,Chunk11,_} = luerl:load("print(\"(31) Hello, \" .. a .. \"!\")", State06), {ok,Chunk11,_} = luerl:load(<<"print(\"(31) Hello, \" .. a .. \"!\")">>, State06), luerl:eval(Chunk11,State06), luerl:do(Chunk11,State06), % separately parse, then execute a file. The file defines a function old() {ok,Chunk12,St6} = luerl:loadfile("./hello2-8.lua", State06), {ok,Result12} = luerl:eval(Chunk12, St6), {Result12,State06A} = luerl:do(Chunk12,St6), luerl:call_function([old],[],State06A), % separately parse, then execute, get a result {ok,Chunk13,St7} = luerl:load("a = '(30a)' .. a .. ' (this is Greek)'; return a", State06), {ok,Chunk13,_} = luerl:load(<<"a = '(30a)' .. a .. ' (this is Greek)'; return a">>, State06), {ok,Result07} = luerl:eval(Chunk13, St7), {Result07,State07} = luerl:do(Chunk13, St7), io:format("(34) And again I said: ~s~n", [Result07]), % separately parse, then execute a file, get a result. The file defines confirm(p) {ok,Chunk14,St8} = luerl:loadfile("./hello2-9.lua", State07), {ok,Result14} = luerl:eval(Chunk14, St8), {Result14,State14} = luerl:do(Chunk14, St8), io:format("(35) And twice: ~s~n", [Result14]), {Result14A,_} = luerl:call_function([confirm], [<<"Is it?">>], State14), io:format("(36) Well: ~s~n", [Result14A]), % execute a file, get the decoded result of a table {ok,Result15} = luerl:evalfile("./hello2-10.lua", State14), io:format("(37) Decoded table: ~p~n", [Result15]), io:format("done~n").
null
https://raw.githubusercontent.com/BitGameEN/bitgamex/151ba70a481615379f9648581a5d459b503abe19/src/deps/luerl/examples/hello/hello2.erl
erlang
File : hello2.erl File : luerl/examples/hello/hello2.erl Or : $ make examples execute a string execute a string, get a result execute a file execute a file, get a result execute a standard function separately parse, then execute a file. The file defines a function no() separately parse, then execute, get a result separately parse, then execute a file, get a result create state change state execute a string, using passed in State0 execute a string, get a result from passed in State0 execute a string, get a result, change State0 execute a file using passed in state execute a file that changes the State0 execute a file, get a result execute a file that changes the State0, and get a value back separately parse, then execute separately parse, then execute a file. The file defines a function old() separately parse, then execute, get a result separately parse, then execute a file, get a result. The file defines confirm(p) execute a file, get the decoded result of a table
Purpose : Demonstration of the Luerl interface . Author : Use : $ cd examples / hello & & erlc hello2.erl & & erl -pa .. / .. /ebin -s hello2 run -s init stop -noshell -module(hello2). -export([run/0]). run() -> io:format("-------------------------------------------~n"), io:format("This is an assortment of samples and tests.~n"), io:format("-------------------------------------------~n"), io:format("It's a comprehensive demo of the interface.~n"), io:format("Please check out the source to learn more.~n"), luerl:eval("print(\"(1) Hello, Robert!\")"), luerl:eval(<<"print(\"(2) Hello, Roberto!\")">>), luerl:do("print(\"(3) Hej, Robert!\")"), luerl:do(<<"print(\"(4) Olà, Roberto!\")">>), {ok,A} = luerl:eval("return 1 + 1"), {ok,A} = luerl:eval(<<"return 1 + 1">>), io:format("(5) 1 + 1 = ~p!~n", [A]), luerl:evalfile("./hello2-1.lua"), luerl:dofile("./hello2-1.lua"), {ok,B} = luerl:evalfile("./hello2-2.lua"), {B,_} = luerl:dofile("./hello2-2.lua"), io:format("(7) 2137 * 42 = ~p?~n", [B]), luerl:call_function([print], [<<"(8) Hello, standard print function!">>]), luerl:call_function([print], [<<"(9) Hello, standard print function!">>], luerl:init()), {Result1,_} = luerl:call_function([table,pack], [<<"a">>,<<"b">>,42]), {Result1,_} = luerl:call_function([table,pack], [<<"a">>,<<"b">>,42], luerl:init()), io:format("(10) ~p?~n", [Result1]), separately parse , then execute ( doubles ( 11 ) and Chunk1 as assertion ) St1A = luerl:init(), {ok,Chunk1,St1B} = luerl:load("print(\"(11) Hello, Chunk 1!\")", St1A), {ok,Chunk1,_} = luerl:load(<<"print(\"(11) Hello, Chunk 1!\")">>, St1A), luerl:eval(Chunk1, St1B), luerl:do(Chunk1, St1B), separately parse , then execute ( doubles ( 12 ) and Chunk2 as assertion ) St2A = luerl:init(), {ok,Chunk2,St2B} = luerl:load("function chunk2() print(\"(12) Hello, Chunk 2!\") end", St2A), {ok,Chunk2,_} = luerl:load(<<"function chunk2() print(\"(12) Hello, Chunk 2!\") end">>, St2A), {ok,Result2} = luerl:eval(Chunk2, St2B), {Result2,St2C} = luerl:do(Chunk2, St2B), {Result2,St2D} = luerl:do(<<"function chunk2() print(\"(12) Hello, Chunk 2!\") end">>, St2A), luerl:call_function([chunk2], [], St2C), luerl:call_function([chunk2], [], St2D), St3A = luerl:init(), {ok,Chunk3,St3B} = luerl:loadfile("./hello2-3.lua", St3A), {ok,Result3} = luerl:eval(Chunk3, St3B), {Result3,St3C} = luerl:do(Chunk3, St3B), {[],_} = luerl:call_function([no], [], St3C), St4A = luerl:init(), {ok,Chunk4,St4B} = luerl:load("return '(17b) Marvelous wheater today, isn°t it!'", St4A), {ok,Chunk4,_} = luerl:load(<<"return '(17b) Marvelous wheater today, isn°t it!'">>, St4A), {ok,Result4} = luerl:eval(Chunk4, St4B), {Result4,_} = luerl:do(Chunk4, St4B), io:format("(17) And I say: ~p~n", [Result4]), St5A = luerl:init(), {ok,Chunk5,St5B} = luerl:loadfile("./hello2-4.lua", St5A), {ok,Result5} = luerl:eval(Chunk5, St5B), {Result5,_} = luerl:do(Chunk5, St5B), io:format("(18) And he says: ~p~n", [Result5]), Same as above , passing State in all times . New = luerl:init(), {_,_New2} = luerl:do("print '(19) hello generix'", New), {_,State0} = luerl:do("a = 1000", New), {_,State01} = luerl:do("a = 1000", New), luerl:eval("print('(20) ' .. a)", State0), luerl:eval(<<"print('(21) ' .. a+1)">>, State0), luerl:do("print('(22) ' .. a+2)", State0), luerl:do(<<"print('(23) ' .. a+3)">>, State0), {ok,E} = luerl:eval("return 4 * a", State0), {ok,E} = luerl:eval(<<"return 4 * a">>, State0), {E,_} = luerl:do("return 4 * a", State0), {E,_} = luerl:do(<<"return 4 * a">>, State0), io:format("(24) 4 x a = ~p!~n", [E]), {Z,State02} = luerl:do("a = 123; return a * 3", State01), {Z,State03} = luerl:do(<<"return (3 * a)">>, State02), io:format("(25) a = ~p~n", [Z]), luerl:evalfile("./hello2-5.lua", State03), luerl:dofile("./hello2-5.lua", State03), {_,State04} = luerl:dofile("./hello2-6.lua", State03), luerl:do("print('(27) (b) ' .. a)", State04), {ok,F} = luerl:evalfile("./hello2-7.lua", State04), {F,State05} = luerl:dofile("./hello2-7.lua", State04), io:format("(28) F: ~s~n", [F]), {F,State06} = luerl:dofile("./hello2-7.lua", State05), io:format("(29) F: ~s = ", [F]), luerl:do("print('(30) F: ' .. a)", State06), {ok,Chunk11,_} = luerl:load("print(\"(31) Hello, \" .. a .. \"!\")", State06), {ok,Chunk11,_} = luerl:load(<<"print(\"(31) Hello, \" .. a .. \"!\")">>, State06), luerl:eval(Chunk11,State06), luerl:do(Chunk11,State06), {ok,Chunk12,St6} = luerl:loadfile("./hello2-8.lua", State06), {ok,Result12} = luerl:eval(Chunk12, St6), {Result12,State06A} = luerl:do(Chunk12,St6), luerl:call_function([old],[],State06A), {ok,Chunk13,St7} = luerl:load("a = '(30a)' .. a .. ' (this is Greek)'; return a", State06), {ok,Chunk13,_} = luerl:load(<<"a = '(30a)' .. a .. ' (this is Greek)'; return a">>, State06), {ok,Result07} = luerl:eval(Chunk13, St7), {Result07,State07} = luerl:do(Chunk13, St7), io:format("(34) And again I said: ~s~n", [Result07]), {ok,Chunk14,St8} = luerl:loadfile("./hello2-9.lua", State07), {ok,Result14} = luerl:eval(Chunk14, St8), {Result14,State14} = luerl:do(Chunk14, St8), io:format("(35) And twice: ~s~n", [Result14]), {Result14A,_} = luerl:call_function([confirm], [<<"Is it?">>], State14), io:format("(36) Well: ~s~n", [Result14A]), {ok,Result15} = luerl:evalfile("./hello2-10.lua", State14), io:format("(37) Decoded table: ~p~n", [Result15]), io:format("done~n").
7da926c3378a6413fe0cebf7e7489e50adbfd1b07f4be6b8e5e754822f9a7ede
input-output-hk/cardano-sl
CborSpec.hs
# LANGUAGE TypeApplications # module Test.Pos.Block.CborSpec ( spec ) where import Universum import Test.Hspec (Spec, describe) import Test.Hspec.QuickCheck (modifyMaxSuccess) import qualified Pos.Chain.Block as Block import qualified Pos.Network.Block.Types as Block import Test.Pos.Binary.Helpers (binaryTest) import Test.Pos.Block.Arbitrary.Message () import Test.Pos.Core.Arbitrary () import Test.Pos.DB.Block.Arbitrary () spec :: Spec spec = do describe "Block network types" $ modifyMaxSuccess (min 10) $ do binaryTest @Block.MsgGetHeaders binaryTest @Block.MsgGetBlocks binaryTest @Block.MsgHeaders binaryTest @Block.MsgBlock binaryTest @Block.MsgStream binaryTest @Block.MsgStreamBlock describe "Block types defined in the block package" $ do describe "Bi instances" $ do describe "Undo" $ do binaryTest @Block.SlogUndo modifyMaxSuccess (min 50) $ do binaryTest @Block.Undo
null
https://raw.githubusercontent.com/input-output-hk/cardano-sl/1499214d93767b703b9599369a431e67d83f10a2/lib/test/Test/Pos/Block/CborSpec.hs
haskell
# LANGUAGE TypeApplications # module Test.Pos.Block.CborSpec ( spec ) where import Universum import Test.Hspec (Spec, describe) import Test.Hspec.QuickCheck (modifyMaxSuccess) import qualified Pos.Chain.Block as Block import qualified Pos.Network.Block.Types as Block import Test.Pos.Binary.Helpers (binaryTest) import Test.Pos.Block.Arbitrary.Message () import Test.Pos.Core.Arbitrary () import Test.Pos.DB.Block.Arbitrary () spec :: Spec spec = do describe "Block network types" $ modifyMaxSuccess (min 10) $ do binaryTest @Block.MsgGetHeaders binaryTest @Block.MsgGetBlocks binaryTest @Block.MsgHeaders binaryTest @Block.MsgBlock binaryTest @Block.MsgStream binaryTest @Block.MsgStreamBlock describe "Block types defined in the block package" $ do describe "Bi instances" $ do describe "Undo" $ do binaryTest @Block.SlogUndo modifyMaxSuccess (min 50) $ do binaryTest @Block.Undo
75838193e6b0c79f37fa9d74e6f2ef7332568930abb26ed27f88c2c2b736e4b6
zippy/anansi
email_bridge_out.clj
(ns anansi.test.streamscapes.channels.email-bridge-out (:use [anansi.streamscapes.channels.email-bridge-out] :reload) (:use [anansi.ceptr] [anansi.receptor.scape] [anansi.receptor.user :only [user-def]] [anansi.streamscapes.streamscapes] [anansi.streamscapes.channel :only [channel-def stream->send]] [anansi.streamscapes.contact :only [contact-def]] ) (:use [midje.sweet]) (:use [clojure.test]) (:use [clj-time.core :only [now]])) (deftest email-bridge-out (let [m (make-receptor user-def nil "eric") r (make-receptor streamscapes-def nil {:matrice-addr (address-of m) :attributes {:_password "password" :data {:datax "x"}}}) eric (make-receptor contact-def r {:attributes {:name "Eric"}}) cc-addr (s-> matrice->make-channel r {:name :email-stream}) cc (get-receptor r cc-addr) b (make-receptor email-bridge-out-def cc {:attributes {:host "mail.harris-braun.com" :account "" :password "some-password" :protocol "smtps" :port 25}}) ] (fact (receptor-state b false) => (contains {:host "mail.harris-braun.com" :account "" :password "some-password" :protocol "smtps" :port 25})) (testing "contents" (is (= "mail.harris-braun.com" (contents b :host)))) (facts "about restoring serialized receptor" (let [state (receptor-state b true)] state => (receptor-state (receptor-restore state nil) true) )) (testing "sending mail" (is (= (parent-of b) cc)) (let [ _ (s-> key->set (get-scape cc :deliverer) :deliverer [(address-of b) ["anansi.streamscapes.channels.email-bridge-out" "channel" "deliver"]]) i-to (s-> matrice->identify r {:identifiers {:email ""} :attributes {:name "Lewis"}}) i-from (s-> matrice->identify r {:identifiers {:email ""} :attributes {:name "Eric"}}) droplet-address (s-> matrice->incorporate r {:to i-to :from i-from :envelope {:subject "text/plain" :body "text/html"} :content {:subject "Hi there!" :body "<b>Hello world!</b>"}}) two lines bellow commented out to not actually send e - mail result ( s- { : droplet - address droplet - address } ) ; d (get-receptor r droplet-address) deliveries (get-scape r :delivery) ] (let [[time] (s-> address->resolve deliveries droplet-address)] ; commented out because e-mail not actually sent ( is (= result " javax.mail . AuthenticationFailedException : 535 Incorrect authentication data\n " ) ) (comment is (= (subs (str (now)) 0 19) (subs time 0 19))) ; hack off the milliseconds )))))
null
https://raw.githubusercontent.com/zippy/anansi/881aa279e5e7836f3002fc2ef7623f2ee1860c9a/test/anansi/test/streamscapes/channels/email_bridge_out.clj
clojure
d (get-receptor r droplet-address) commented out because e-mail not actually sent hack off the milliseconds
(ns anansi.test.streamscapes.channels.email-bridge-out (:use [anansi.streamscapes.channels.email-bridge-out] :reload) (:use [anansi.ceptr] [anansi.receptor.scape] [anansi.receptor.user :only [user-def]] [anansi.streamscapes.streamscapes] [anansi.streamscapes.channel :only [channel-def stream->send]] [anansi.streamscapes.contact :only [contact-def]] ) (:use [midje.sweet]) (:use [clojure.test]) (:use [clj-time.core :only [now]])) (deftest email-bridge-out (let [m (make-receptor user-def nil "eric") r (make-receptor streamscapes-def nil {:matrice-addr (address-of m) :attributes {:_password "password" :data {:datax "x"}}}) eric (make-receptor contact-def r {:attributes {:name "Eric"}}) cc-addr (s-> matrice->make-channel r {:name :email-stream}) cc (get-receptor r cc-addr) b (make-receptor email-bridge-out-def cc {:attributes {:host "mail.harris-braun.com" :account "" :password "some-password" :protocol "smtps" :port 25}}) ] (fact (receptor-state b false) => (contains {:host "mail.harris-braun.com" :account "" :password "some-password" :protocol "smtps" :port 25})) (testing "contents" (is (= "mail.harris-braun.com" (contents b :host)))) (facts "about restoring serialized receptor" (let [state (receptor-state b true)] state => (receptor-state (receptor-restore state nil) true) )) (testing "sending mail" (is (= (parent-of b) cc)) (let [ _ (s-> key->set (get-scape cc :deliverer) :deliverer [(address-of b) ["anansi.streamscapes.channels.email-bridge-out" "channel" "deliver"]]) i-to (s-> matrice->identify r {:identifiers {:email ""} :attributes {:name "Lewis"}}) i-from (s-> matrice->identify r {:identifiers {:email ""} :attributes {:name "Eric"}}) droplet-address (s-> matrice->incorporate r {:to i-to :from i-from :envelope {:subject "text/plain" :body "text/html"} :content {:subject "Hi there!" :body "<b>Hello world!</b>"}}) two lines bellow commented out to not actually send e - mail result ( s- { : droplet - address droplet - address } ) deliveries (get-scape r :delivery) ] (let [[time] (s-> address->resolve deliveries droplet-address)] ( is (= result " javax.mail . AuthenticationFailedException : 535 Incorrect authentication data\n " ) ) )))))
4223a557d77d6b6d90de5d371398e4b9b865664834716ccbff7aeaea3b6a966c
mcorbin/meuse
metric.clj
(ns meuse.api.public.metric (:require [meuse.api.public.http :refer [public-api!]] [meuse.metric :as metric])) (defmethod public-api! :metrics [_] {:status 200 :headers {"Content-Type" "text/plain"} :body (.getBytes (.scrape metric/registry))})
null
https://raw.githubusercontent.com/mcorbin/meuse/d2b74543fce37c8cde770ae6f6097cabb509a804/src/meuse/api/public/metric.clj
clojure
(ns meuse.api.public.metric (:require [meuse.api.public.http :refer [public-api!]] [meuse.metric :as metric])) (defmethod public-api! :metrics [_] {:status 200 :headers {"Content-Type" "text/plain"} :body (.getBytes (.scrape metric/registry))})
218161514357c09442c9648863094c876f25097d8a79fc96aae021adcd42701b
jaked/froc
froc_direct.mli
val direct : (unit -> 'a) -> 'a Froc.behavior val read : 'a Froc.behavior -> 'a val (~|) : (unit -> 'a) -> 'a Froc.behavior val (~.) : 'a Froc.behavior -> 'a
null
https://raw.githubusercontent.com/jaked/froc/6068a1fab883ed9254bfeb53a1f9c15e8af0bb20/src/froc-direct/froc_direct.mli
ocaml
val direct : (unit -> 'a) -> 'a Froc.behavior val read : 'a Froc.behavior -> 'a val (~|) : (unit -> 'a) -> 'a Froc.behavior val (~.) : 'a Froc.behavior -> 'a
16d31118a1e29a3d027d744272289a83508c2ba418159cb0448e56d3cd9d2964
owlbarn/owl_symbolic
owl_symbolic_ops_rnn.ml
* OWL - OCaml Scientific and Engineering Computing * Copyright ( c ) 2016 - 2020 < > * OWL - OCaml Scientific and Engineering Computing * Copyright (c) 2016-2020 Liang Wang <> *) * LSTM , RNN , GRU open Owl_symbolic_types module LSTM = struct type t = { mutable name : string ; mutable input : string array ; mutable output : string array ; mutable attrs : (string * attrvalue) array ; mutable out_shape : int array option array ; mutable activation_alpha : float array option ; mutable activation_beta : float array option ; mutable activations : activation array ; mutable clip : float option ; mutable direction : string ; mutable hidden_size : int ; mutable input_forget : int } let op_type = "LSTM" TODO : the optional inputs are omitted for now : sequence_lens , * initial_h , initial_c , P. * Also process the alpha and beta according to different activations . * initial_h, initial_c, P. * Also process the alpha and beta according to different activations. *) let create ?name ?output ?alpha ?beta ?clip ?activations ?(direction = "forward") ?(input_forget = 0) hidden_size ?b x w r = let attrs = [||] in let name = Owl_symbolic_utils.node_name ?name op_type in let input = match b with | Some b -> [| x; w; r; b |] | None -> [| x; w; r |] in let output = match output with | Some o -> o | None -> [| name |] in let activations = match activations with | Some a -> a | None -> [| Sigmoid; Tanh; Tanh |] in assert (Array.mem direction [| "forward"; "reverse"; "bidirectional" |]); TODO : what 's the implication of three optional outputs ? let out_shape = [| None; None; None |] in { name ; input ; output ; attrs ; out_shape ; activation_alpha = alpha ; activation_beta = beta ; activations ; clip ; direction ; hidden_size ; input_forget } end module RNN = struct type t = { mutable name : string ; mutable input : string array ; mutable output : string array ; mutable attrs : (string * attrvalue) array ; mutable out_shape : int array option array ; mutable activation_alpha : float array option ; mutable activation_beta : float array option ; mutable activations : activation array ; mutable clip : float option ; mutable direction : string ; mutable hidden_size : int } let op_type = "RNN" let create ?name ?output ?alpha ?beta ?clip ?activations ?(direction = "forward") hidden_size x w r b sequence_len initial_h = let attrs = [||] in let name = Owl_symbolic_utils.node_name ?name op_type in let input = [| x; w; r; b; sequence_len; initial_h |] in let output = match output with | Some o -> o | None -> [| name |] in let activations = match activations with | Some a -> a | None -> [| Sigmoid; Tanh; Tanh |] in assert (Array.mem direction [| "forward"; "reverse"; "bidirectional" |]); let out_shape = [| None; None |] in { name ; input ; output ; attrs ; out_shape ; activation_alpha = alpha ; activation_beta = beta ; activations ; clip ; direction ; hidden_size } end module GRU = struct type t = { mutable name : string ; mutable input : string array ; mutable output : string array ; mutable attrs : (string * attrvalue) array ; mutable out_shape : int array option array ; mutable activation_alpha : float array option ; mutable activation_beta : float array option ; mutable activations : activation array ; mutable clip : float option ; mutable direction : string ; mutable hidden_size : int ; mutable linear_before_reset : int } let op_type = "GRU" let create ?name ?output ?alpha ?beta ?clip ?activations ?(direction = "forward") ?(linear_before_reset = 0) hidden_size x w r b sequence_len initial_h = let attrs = [||] in let name = Owl_symbolic_utils.node_name ?name op_type in let input = [| x; w; r; b; sequence_len; initial_h |] in let output = match output with | Some o -> o | None -> [| name |] in let activations = match activations with | Some a -> a | None -> [| Sigmoid; Tanh; Tanh |] in assert (Array.mem direction [| "forward"; "reverse"; "bidirectional" |]); let out_shape = [| None; None |] in { name ; input ; output ; attrs ; out_shape ; activation_alpha = alpha ; activation_beta = beta ; activations ; clip ; direction ; hidden_size ; linear_before_reset } end
null
https://raw.githubusercontent.com/owlbarn/owl_symbolic/dc853a016757d3f143c5e07e50075e7ae605d969/src/ops/owl_symbolic_ops_rnn.ml
ocaml
* OWL - OCaml Scientific and Engineering Computing * Copyright ( c ) 2016 - 2020 < > * OWL - OCaml Scientific and Engineering Computing * Copyright (c) 2016-2020 Liang Wang <> *) * LSTM , RNN , GRU open Owl_symbolic_types module LSTM = struct type t = { mutable name : string ; mutable input : string array ; mutable output : string array ; mutable attrs : (string * attrvalue) array ; mutable out_shape : int array option array ; mutable activation_alpha : float array option ; mutable activation_beta : float array option ; mutable activations : activation array ; mutable clip : float option ; mutable direction : string ; mutable hidden_size : int ; mutable input_forget : int } let op_type = "LSTM" TODO : the optional inputs are omitted for now : sequence_lens , * initial_h , initial_c , P. * Also process the alpha and beta according to different activations . * initial_h, initial_c, P. * Also process the alpha and beta according to different activations. *) let create ?name ?output ?alpha ?beta ?clip ?activations ?(direction = "forward") ?(input_forget = 0) hidden_size ?b x w r = let attrs = [||] in let name = Owl_symbolic_utils.node_name ?name op_type in let input = match b with | Some b -> [| x; w; r; b |] | None -> [| x; w; r |] in let output = match output with | Some o -> o | None -> [| name |] in let activations = match activations with | Some a -> a | None -> [| Sigmoid; Tanh; Tanh |] in assert (Array.mem direction [| "forward"; "reverse"; "bidirectional" |]); TODO : what 's the implication of three optional outputs ? let out_shape = [| None; None; None |] in { name ; input ; output ; attrs ; out_shape ; activation_alpha = alpha ; activation_beta = beta ; activations ; clip ; direction ; hidden_size ; input_forget } end module RNN = struct type t = { mutable name : string ; mutable input : string array ; mutable output : string array ; mutable attrs : (string * attrvalue) array ; mutable out_shape : int array option array ; mutable activation_alpha : float array option ; mutable activation_beta : float array option ; mutable activations : activation array ; mutable clip : float option ; mutable direction : string ; mutable hidden_size : int } let op_type = "RNN" let create ?name ?output ?alpha ?beta ?clip ?activations ?(direction = "forward") hidden_size x w r b sequence_len initial_h = let attrs = [||] in let name = Owl_symbolic_utils.node_name ?name op_type in let input = [| x; w; r; b; sequence_len; initial_h |] in let output = match output with | Some o -> o | None -> [| name |] in let activations = match activations with | Some a -> a | None -> [| Sigmoid; Tanh; Tanh |] in assert (Array.mem direction [| "forward"; "reverse"; "bidirectional" |]); let out_shape = [| None; None |] in { name ; input ; output ; attrs ; out_shape ; activation_alpha = alpha ; activation_beta = beta ; activations ; clip ; direction ; hidden_size } end module GRU = struct type t = { mutable name : string ; mutable input : string array ; mutable output : string array ; mutable attrs : (string * attrvalue) array ; mutable out_shape : int array option array ; mutable activation_alpha : float array option ; mutable activation_beta : float array option ; mutable activations : activation array ; mutable clip : float option ; mutable direction : string ; mutable hidden_size : int ; mutable linear_before_reset : int } let op_type = "GRU" let create ?name ?output ?alpha ?beta ?clip ?activations ?(direction = "forward") ?(linear_before_reset = 0) hidden_size x w r b sequence_len initial_h = let attrs = [||] in let name = Owl_symbolic_utils.node_name ?name op_type in let input = [| x; w; r; b; sequence_len; initial_h |] in let output = match output with | Some o -> o | None -> [| name |] in let activations = match activations with | Some a -> a | None -> [| Sigmoid; Tanh; Tanh |] in assert (Array.mem direction [| "forward"; "reverse"; "bidirectional" |]); let out_shape = [| None; None |] in { name ; input ; output ; attrs ; out_shape ; activation_alpha = alpha ; activation_beta = beta ; activations ; clip ; direction ; hidden_size ; linear_before_reset } end
41651701c6a3d3aef15fd56dee7e2cafb088ec1f7ad6c66e408dc1909106692b
EMSL-NMR-EPR/Haskell-MFAPipe-Executable
MassFractionVector.hs
module MFAPipe.Csv.Types.MassFractionVector ( MassFractionVectorRecords(..) , MassFractionVectorRecord(..) , encode , encodeWith , IndexedMassFractionVectorRecords(..) , IndexedMassFractionVectorRecord(..) , encodeIndexed , encodeIndexedWith ) where import Data.ByteString.Lazy (ByteString) import qualified Data.Csv import Data.Csv (ToField(), ToNamedRecord(toNamedRecord), EncodeOptions, Header) import Data.IntMap.Strict (IntMap) import qualified Data.IntMap.Strict import Data.Map.Strict (Map) import qualified Data.Map.Strict import Data.Monoid.Conv (Conv(..)) import Foreign.Storable (Storable()) import MFAPipe.Csv.Constants import qualified Numeric.LinearAlgebra.HMatrix import Science.Chemistry.EMU.EMU (EMU) import qualified Science.Chemistry.EMU.HasSize.Class import Science.Chemistry.IsotopicLabeling.MassFraction (MassFraction) import qualified Science.Chemistry.IsotopicLabeling.MassFraction import Science.Chemistry.IsotopicLabeling.MassFractionVector (MassFractionVector(..)) import Text.PrettyPrint.Leijen.Text (Pretty()) data MassFractionVectorRecords k e = MassFractionVectorRecords {-# UNPACK #-} !Int (Map (EMU k) (MassFractionVector e)) deriving (Eq, Ord, Read, Show) data MassFractionVectorRecord k e = MassFractionVectorRecord [MassFraction] (EMU k) (MassFractionVector e) deriving (Eq, Ord, Read, Show) instance (Pretty k, Storable e, ToField k, ToField e) => ToNamedRecord (MassFractionVectorRecord k e) where toNamedRecord (MassFractionVectorRecord massFractions emu xs) = Data.Csv.namedRecord $ Data.Csv.namedField cEMUFieldName emu : zipWith Data.Csv.namedField (map Data.Csv.toField massFractions) (Numeric.LinearAlgebra.HMatrix.toList (getConv (getMassFractionVector xs))) encode :: (Pretty k, Storable e, ToField k, ToField e) => MassFractionVectorRecords k e -> IntMap ByteString encode = encodeWith Data.Csv.defaultEncodeOptions encodeWith :: (Pretty k, Storable e, ToField k, ToField e) => EncodeOptions -> MassFractionVectorRecords k e -> IntMap ByteString encodeWith opts (MassFractionVectorRecords base m) = Data.IntMap.Strict.mapWithKey (\n -> let massFractions = Science.Chemistry.IsotopicLabeling.MassFraction.massFractions base n in Data.Csv.encodeByNameWith opts (toHeader massFractions) . map (uncurry (MassFractionVectorRecord massFractions))) (Science.Chemistry.EMU.HasSize.Class.partitionBySizeWith fst (Data.Map.Strict.toAscList m)) toHeader :: [MassFraction] -> Header toHeader massFractions = Data.Csv.header $ cEMUFieldName : map Data.Csv.toField massFractions data IndexedMassFractionVectorRecords i k e = IndexedMassFractionVectorRecords {-# UNPACK #-} !Int (Map i (Map (EMU k) (MassFractionVector e))) deriving (Eq, Ord, Read, Show) data IndexedMassFractionVectorRecord i k e = IndexedMassFractionVectorRecord [MassFraction] i (EMU k) (MassFractionVector e) deriving (Eq, Ord, Read, Show) instance (Pretty k, Storable e, ToField i, ToField k, ToField e) => ToNamedRecord (IndexedMassFractionVectorRecord i k e) where toNamedRecord (IndexedMassFractionVectorRecord massFractions ix emu xs) = Data.Csv.namedRecord $ Data.Csv.namedField cFluxVarFieldName ix : Data.Csv.namedField cEMUFieldName emu : zipWith Data.Csv.namedField (map Data.Csv.toField massFractions) (Numeric.LinearAlgebra.HMatrix.toList (getConv (getMassFractionVector xs))) encodeIndexed :: (Pretty k, Storable e, ToField i, ToField k, ToField e) => IndexedMassFractionVectorRecords i k e -> IntMap ByteString encodeIndexed = encodeIndexedWith Data.Csv.defaultEncodeOptions encodeIndexedWith :: (Pretty k, Storable e, ToField i, ToField k, ToField e) => EncodeOptions -> IndexedMassFractionVectorRecords i k e -> IntMap ByteString encodeIndexedWith opts (IndexedMassFractionVectorRecords base m) = Data.IntMap.Strict.mapWithKey (\n -> let massFractions = Science.Chemistry.IsotopicLabeling.MassFraction.massFractions base n in Data.Csv.encodeByNameWith opts (toHeaderIndexed massFractions) . map (uncurry (uncurry . IndexedMassFractionVectorRecord massFractions))) (Science.Chemistry.EMU.HasSize.Class.partitionBySizeWith (fst . snd) (concatMap (uncurry (map . (,))) (Data.Map.Strict.toAscList (Data.Map.Strict.map Data.Map.Strict.toAscList m)))) toHeaderIndexed :: [MassFraction] -> Header toHeaderIndexed massFractions = Data.Csv.header $ cFluxVarFieldName : cEMUFieldName : map Data.Csv.toField massFractions
null
https://raw.githubusercontent.com/EMSL-NMR-EPR/Haskell-MFAPipe-Executable/8a7fd13202d3b6b7380af52d86e851e995a9b53e/MFAPipe/app/MFAPipe/Csv/Types/MassFractionVector.hs
haskell
# UNPACK # # UNPACK #
module MFAPipe.Csv.Types.MassFractionVector ( MassFractionVectorRecords(..) , MassFractionVectorRecord(..) , encode , encodeWith , IndexedMassFractionVectorRecords(..) , IndexedMassFractionVectorRecord(..) , encodeIndexed , encodeIndexedWith ) where import Data.ByteString.Lazy (ByteString) import qualified Data.Csv import Data.Csv (ToField(), ToNamedRecord(toNamedRecord), EncodeOptions, Header) import Data.IntMap.Strict (IntMap) import qualified Data.IntMap.Strict import Data.Map.Strict (Map) import qualified Data.Map.Strict import Data.Monoid.Conv (Conv(..)) import Foreign.Storable (Storable()) import MFAPipe.Csv.Constants import qualified Numeric.LinearAlgebra.HMatrix import Science.Chemistry.EMU.EMU (EMU) import qualified Science.Chemistry.EMU.HasSize.Class import Science.Chemistry.IsotopicLabeling.MassFraction (MassFraction) import qualified Science.Chemistry.IsotopicLabeling.MassFraction import Science.Chemistry.IsotopicLabeling.MassFractionVector (MassFractionVector(..)) import Text.PrettyPrint.Leijen.Text (Pretty()) deriving (Eq, Ord, Read, Show) data MassFractionVectorRecord k e = MassFractionVectorRecord [MassFraction] (EMU k) (MassFractionVector e) deriving (Eq, Ord, Read, Show) instance (Pretty k, Storable e, ToField k, ToField e) => ToNamedRecord (MassFractionVectorRecord k e) where toNamedRecord (MassFractionVectorRecord massFractions emu xs) = Data.Csv.namedRecord $ Data.Csv.namedField cEMUFieldName emu : zipWith Data.Csv.namedField (map Data.Csv.toField massFractions) (Numeric.LinearAlgebra.HMatrix.toList (getConv (getMassFractionVector xs))) encode :: (Pretty k, Storable e, ToField k, ToField e) => MassFractionVectorRecords k e -> IntMap ByteString encode = encodeWith Data.Csv.defaultEncodeOptions encodeWith :: (Pretty k, Storable e, ToField k, ToField e) => EncodeOptions -> MassFractionVectorRecords k e -> IntMap ByteString encodeWith opts (MassFractionVectorRecords base m) = Data.IntMap.Strict.mapWithKey (\n -> let massFractions = Science.Chemistry.IsotopicLabeling.MassFraction.massFractions base n in Data.Csv.encodeByNameWith opts (toHeader massFractions) . map (uncurry (MassFractionVectorRecord massFractions))) (Science.Chemistry.EMU.HasSize.Class.partitionBySizeWith fst (Data.Map.Strict.toAscList m)) toHeader :: [MassFraction] -> Header toHeader massFractions = Data.Csv.header $ cEMUFieldName : map Data.Csv.toField massFractions deriving (Eq, Ord, Read, Show) data IndexedMassFractionVectorRecord i k e = IndexedMassFractionVectorRecord [MassFraction] i (EMU k) (MassFractionVector e) deriving (Eq, Ord, Read, Show) instance (Pretty k, Storable e, ToField i, ToField k, ToField e) => ToNamedRecord (IndexedMassFractionVectorRecord i k e) where toNamedRecord (IndexedMassFractionVectorRecord massFractions ix emu xs) = Data.Csv.namedRecord $ Data.Csv.namedField cFluxVarFieldName ix : Data.Csv.namedField cEMUFieldName emu : zipWith Data.Csv.namedField (map Data.Csv.toField massFractions) (Numeric.LinearAlgebra.HMatrix.toList (getConv (getMassFractionVector xs))) encodeIndexed :: (Pretty k, Storable e, ToField i, ToField k, ToField e) => IndexedMassFractionVectorRecords i k e -> IntMap ByteString encodeIndexed = encodeIndexedWith Data.Csv.defaultEncodeOptions encodeIndexedWith :: (Pretty k, Storable e, ToField i, ToField k, ToField e) => EncodeOptions -> IndexedMassFractionVectorRecords i k e -> IntMap ByteString encodeIndexedWith opts (IndexedMassFractionVectorRecords base m) = Data.IntMap.Strict.mapWithKey (\n -> let massFractions = Science.Chemistry.IsotopicLabeling.MassFraction.massFractions base n in Data.Csv.encodeByNameWith opts (toHeaderIndexed massFractions) . map (uncurry (uncurry . IndexedMassFractionVectorRecord massFractions))) (Science.Chemistry.EMU.HasSize.Class.partitionBySizeWith (fst . snd) (concatMap (uncurry (map . (,))) (Data.Map.Strict.toAscList (Data.Map.Strict.map Data.Map.Strict.toAscList m)))) toHeaderIndexed :: [MassFraction] -> Header toHeaderIndexed massFractions = Data.Csv.header $ cFluxVarFieldName : cEMUFieldName : map Data.Csv.toField massFractions
92f05e9ca63ee66eeb892c9f32fc491ade38f385c08bff4a8de0deb849a6ac65
tomjaguarpaw/product-profunctors
Newtype.hs
module Data.Profunctor.Product.Newtype where import qualified Data.Profunctor as P class Newtype t where constructor :: a -> t a field :: t a -> a pNewtype :: (P.Profunctor p, Newtype t) => p a b -> p (t a) (t b) pNewtype = P.dimap field constructor
null
https://raw.githubusercontent.com/tomjaguarpaw/product-profunctors/db78428cb2be7eddddf1f9f98899003efb9c8c56/Data/Profunctor/Product/Newtype.hs
haskell
module Data.Profunctor.Product.Newtype where import qualified Data.Profunctor as P class Newtype t where constructor :: a -> t a field :: t a -> a pNewtype :: (P.Profunctor p, Newtype t) => p a b -> p (t a) (t b) pNewtype = P.dimap field constructor
5c8ecf1e388653bb5604e2927edb9c66d16ddd64ba3582b722f35010952a9a8a
johnwhitington/ocamli
exercise06.ml
let concat ss = let b = Buffer.create 100 in List.iter (Buffer.add_string b) ss; Buffer.contents b
null
https://raw.githubusercontent.com/johnwhitington/ocamli/28da5d87478a51583a6cb792bf3a8ee44b990e9f/OCaml%20from%20the%20Very%20Beginning/Chapter%2015/exercise06.ml
ocaml
let concat ss = let b = Buffer.create 100 in List.iter (Buffer.add_string b) ss; Buffer.contents b
cc46c9c93120085a84f2abdb51062f17a9dd3fe3b4ed834598b51a63f7357e10
well-typed/large-records
HL070.hs
module Common.HListOfSize.HL070 (Fields) where import Bench.Types type Fields = '[ -- 00 .. 09 T 00 , T 01 , T 02 , T 03 , T 04 , T 05 , T 06 , T 07 , T 08 , T 09 10 .. 19 , T 10 , T 11 , T 12 , T 13 , T 14 , T 15 , T 16 , T 17 , T 18 , T 19 20 .. 29 , T 20 , T 21 , T 22 , T 23 , T 24 , T 25 , T 26 , T 27 , T 28 , T 29 30 .. 39 , T 30 , T 31 , T 32 , T 33 , T 34 , T 35 , T 36 , T 37 , T 38 , T 39 40 .. 49 , T 40 , T 41 , T 42 , T 43 , T 44 , T 45 , T 46 , T 47 , T 48 , T 49 50 .. 59 , T 50 , T 51 , T 52 , T 53 , T 54 , T 55 , T 56 , T 57 , T 58 , T 59 60 .. 69 , T 60 , T 61 , T 62 , T 63 , T 64 , T 65 , T 66 , T 67 , T 68 , T 69 ]
null
https://raw.githubusercontent.com/well-typed/large-records/551f265845fbe56346988a6b484dca40ef380609/large-records-benchmarks/bench/typelet/Common/HListOfSize/HL070.hs
haskell
00 .. 09
module Common.HListOfSize.HL070 (Fields) where import Bench.Types type Fields = '[ T 00 , T 01 , T 02 , T 03 , T 04 , T 05 , T 06 , T 07 , T 08 , T 09 10 .. 19 , T 10 , T 11 , T 12 , T 13 , T 14 , T 15 , T 16 , T 17 , T 18 , T 19 20 .. 29 , T 20 , T 21 , T 22 , T 23 , T 24 , T 25 , T 26 , T 27 , T 28 , T 29 30 .. 39 , T 30 , T 31 , T 32 , T 33 , T 34 , T 35 , T 36 , T 37 , T 38 , T 39 40 .. 49 , T 40 , T 41 , T 42 , T 43 , T 44 , T 45 , T 46 , T 47 , T 48 , T 49 50 .. 59 , T 50 , T 51 , T 52 , T 53 , T 54 , T 55 , T 56 , T 57 , T 58 , T 59 60 .. 69 , T 60 , T 61 , T 62 , T 63 , T 64 , T 65 , T 66 , T 67 , T 68 , T 69 ]
0a7d768b207f36ac84d28323e8bc17c03c27261adb6c4f126e3847bae08472ad
MarkCurtiss/sicp
3_28_to_3_37.scm
3.28 ; ======================================================================== (define (logical-or signal1 signal2) (or signal1 signal2)) (define (or-gate wire1 wire2 output-wire) (define (or-action-procedure) (let ((new-value (logical-or (get-signal wire1) (get-signal wire2)))) (after-delay or-gate-delay (lambda () (set-signal! output-wire new-value))))) (add-action! wire1 or-action-procedure) (add-action! wire2 or-action-procedure) 'ok) 3.29 ; ======================================================================== (define (and-gate a1 a2 output) (define (and-action-procedure) (let ((new-value (logical-and (get-signal a1) (get-signal a2)))) (after-delay and-gate-delay (lambda () (set-signal! output new-value))))) (add-action! a1 and-action-procedure) (add-action! a2 and-action-procedure) 'ok) (define (inverter input output) (define (invert-input) (let ((new-value (logical-not (get-signal input)))) (after-delay inverter-delay (lambda () (set-signal! output new-value))))) (add-action! input invert-input) 'ok) (define (logical-and signal1 signal2) (and signal1 signal2)) (define (logical-not s) (cond ((= s 0) 1) ((= s 1) 0) (else (error "Invalid signal" s)))) (define (or-gate wire1 wire2 output-wire) (let ((wire3 (make-wire)) (wire4 (make-wire))) (inverter wire1 wire3) (inverter wire2 wire4) (and-gate wire3 wire4 output-wire))) ;; The delay time is equal to ;; (+ inverter-delay inverter-delay and-gate-delay) 3.30 ; ======================================================================== (define (ripple-carry-adder a-list b-list sum-list carry-in) (let ((carry-out (make-wire))) (if (null? (cdr a-list)) (full-adder (car a-list) (car b-list) carry-in (car s-list) carry-out) (ripple-carry-adder (cdr a-list b-list sum-list carry-out))))) ;; The delay time will be n * ( 2 * ( half - adder + or - gate ) ) = = n * ( ( 2 * ( or - gate + ( 2 * and - gate ) + inverter ) ) + or - gate ) 3.31 ; ======================================================================== ;; If we didn't invoke the callback right away we wouldn't actually place events in the agenda when we construct half - adders and or - gates and such . ;; Thus, the simulation wouldn't produce any output. 3.32 ; ======================================================================== ;; queue ( A 0 - > 1 , B 0 - > 1 , A 1 - > 0 , B 1 - > 0 ) ;; stack ;; (B 1 -> 0, A 1 -> 0, B 0 -> 1, A 0 -> 1) ;; If a stack were used, the AND gate would appear to go (incorrectly): ;; False, False, False, True ;; If the queue is used, the AND gate properly signals: ;; False, True, False, False. 3.33 ; ======================================================================== ;; Here comes a few pages of copypasta: (define (adder a1 a2 sum) (define (process-new-value) (cond ((and (has-value? a1) (has-value? a2)) (set-value! sum (+ (get-value a1) (get-value a2)) me)) ((and (has-value? a1) (has-value? sum)) (set-value! a2 (- (get-value sum) (get-value a1)) me)) ((and (has-value? a2) (has-value? sum)) (set-value! a1 (- (get-value sum) (get-value a2)) me)))) (define (process-forget-value) (forget-value! sum me) (forget-value! a1 me) (forget-value! a2 me) (process-new-value)) (define (me request) (cond ((eq? request 'I-have-a-value) (process-new-value)) ((eq? request 'I-lost-my-value) (process-forget-value)) (else (error "Unknown request -- ADDER" request)))) (connect a1 me) (connect a2 me) (connect sum me) me) (define (inform-about-value constraint) (constraint 'I-have-a-value)) (define (inform-about-no-value constraint) (constraint 'I-lost-my-value)) (define (multiplier m1 m2 product) (define (process-new-value) (cond ((or (and (has-value? m1) (= (get-value m1) 0)) (and (has-value? m2) (= (get-value m2) 0))) (set-value! product 0 me)) ((and (has-value? m1) (has-value? m2)) (set-value! product (* (get-value m1) (get-value m2)) me)) ((and (has-value? product) (has-value? m1)) (set-value! m2 (/ (get-value product) (get-value m1)) me)) ((and (has-value? product) (has-value? m2)) (set-value! m1 (/ (get-value product) (get-value m2)) me)))) (define (process-forget-value) (forget-value! product me) (forget-value! m1 me) (forget-value! m2 me) (process-new-value)) (define (me request) (cond ((eq? request 'I-have-a-value) (process-new-value)) ((eq? request 'I-lost-my-value) (process-forget-value)) (else (error "Unknown request -- MULTIPLIER" request)))) (connect m1 me) (connect m2 me) (connect product me) me) (define (constant value connector) (define (me request) (error "Unknown request -- CONSTANT" request)) (connect connector me) (set-value! connector value me) me) (define (probe name connector) (define (print-probe value) (newline) (display "Probe: ") (display name) (display " = ") (display value)) (define (process-new-value) (print-probe (get-value connector))) (define (process-forget-value) (print-probe "?")) (define (me request) (cond ((eq? request 'I-have-a-value) (process-new-value)) ((eq? request 'I-lost-my-value) (process-forget-value)) (else (error "Unknown request -- PROBE" request)))) (connect connector me) me) (define (make-connector) (let ((value false) (informant false) (constraints '())) (define (set-my-value newval setter) (cond ((not (has-value? me)) (set! value newval) (set! informant setter) (for-each-except setter inform-about-value constraints)) ((not (= value newval)) (error "Contradiction" (list value newval))) (else 'ignored))) (define (forget-my-value retractor) (if (eq? retractor informant) (begin (set! informant false) (for-each-except retractor inform-about-no-value constraints)) 'ignored)) (define (connect new-constraint) (if (not (memq new-constraint constraints)) (set! constraints (cons new-constraint constraints))) (if (has-value? me) (inform-about-value new-constraint)) 'done) (define (me request) (cond ((eq? request 'has-value?) (if informant true false)) ((eq? request 'value) value) ((eq? request 'set-value!) set-my-value) ((eq? request 'forget) forget-my-value) ((eq? request 'connect) connect) (else (error "Unknown operation -- CONNECTOR" request)))) me)) (define (for-each-except exception procedure list) (define (loop items) (cond ((null? items) 'done) ((eq? (car items) exception) (loop (cdr items))) (else (procedure (car items)) (loop (cdr items))))) (loop list)) (define (has-value? connector) (connector 'has-value?)) (define (get-value connector) (connector 'value)) (define (set-value! connector new-value informant) ((connector 'set-value!) new-value informant)) (define (forget-value! connector retractor) ((connector 'forget) retractor)) (define (connect connector new-constraint) ((connector 'connect) new-constraint)) ;; Okay now here is some new code. (define (averager a b c) (let ((twoc (make-connector)) (u (make-connector)) (v (make-connector))) (multiplier c twoc u) (constant 2 twoc) (adder a b u)) 'ok) (define A (make-connector)) (define B (make-connector)) (define C (make-connector)) (averager A B C) (probe "A" A) (probe "B" B) (probe "C" C) (set-value! A 9 'user) (set-value! B 11 'user) Probe : A = 9 Probe : B = 11 Probe : C = 10 ;; ;Value: done 3.34 ; ======================================================================== ;; Changes to the value of b won't propagate back to a. ;; 1 ]=> (define (squarer a b) ;; (multiplier a a b)) ;; Value: squarer ;; 1 ]=> (define R (make-connector)) ;; Value: r ;; 1 ]=> (define S (make-connector)) ;; Value: s ;; 1 ]=> (probe "R" R) Value 5 : # [ compound - procedure 5 me ] ;; 1 ]=> (probe "S" S) Value 6 : # [ compound - procedure 6 me ] ;; 1 ]=> (squarer R S) Value 7 : # [ compound - procedure 7 me ] ;; 1 ]=> (set-value! R 4 'user) Probe : S = 16 Probe : R = 4 ;; Value: done ;; So far so good. But now, observe: ;; 1 ]=> (forget-value! R 'user) ;; Probe: S = ? ;; Probe: R = ? ;; Value: done ;; 1 ]=> (set-value! S 16 'user) Probe : S = 16 ;; Value: done ;; Notice that we don't see the value of R change. ;; This is because none of the conditionals in (process-new-value) in ( multiplier product ) will ever be hit - although product has a value neither m1 nor have a value in implementation . 3.35 ; ======================================================================== (define (squarer a b) (define (process-new-value) (if (has-value? b) (if (< (get-value b) 0) (error "square less than 0 -- SQUARER" (get-value b)) (set-value! a (sqrt (get-value b)) me)) (if (has-value? a) (set-value! b (square (get-value a)) me)))) (define (process-forget-value) (forget-value! a me) (forget-value! b me) (process-new-value)) (define (me request) (cond ((eq? request 'I-have-a-value) (process-new-value)) ((eq? request 'I-lost-my-value) (process-forget-value)) (else (error "Unknown request -- SQUARER" request)))) (connect a me) (connect b me) me) ;; 1 ]=> (define R (make-connector)) ;; Value: r ;; 1 ]=> (define S (make-connector)) ;; Value: s ;; 1 ]=> (probe "R" R) Value 8 : # [ compound - procedure 8 me ] ;; 1 ]=> (probe "S" S) Value 9 : # [ compound - procedure 9 me ] ;; 1 ]=> (squarer R S) Value 10 : # [ compound - procedure 10 me ] ;; 1 ]=> (set-value! R 4 'user) Probe : S = 16 Probe : R = 4 ;; Value: done ;; 1 ]=> (forget-value! R 'user) ;; Probe: S = ? ;; Probe: R = ? ;; Value: done ;; 1 ]=> (set-value! S 16 'user) Probe : R = 4 Probe : S = 16 ;; Value: done 3.36 ; ======================================================================== " +--------------------------------------+ global-env+--->| | | |<------------------------+ | | | +-----------+a b+--------+ | | +--------------------------------------+ | | | ^ | | | | | | | | | +-------+--------+ | +---------+------+ v E2+-->|value: false | v E1+-->|value: 10 | +-+ |informant: false| +-+ |informant: 'user|<-----------+ |+-------> |constraints: () | |+------->|constraints: () | | +-+ +----------------+ +-+ +----------------+ | |+------+ +--+| | +-+ | | +-+ | | | | | v +-----------+-----------------+ v params: request E3+-->|exception: 'user | params: request body: |procedure: inform-about-value| body: (cond ((eq? request 'has... |list: () | (cond ((eq? request 'has... +-----------------------------+ +-+ ^ |+------------------+ +-+ +-----------+| v +-+ params: exception, procedure, list body: (define (loop items) ... " 3.37 ; ======================================================================== (define (c+ x y) (let ((z (make-connector))) (adder x y z) z)) (define (c* x y) (let ((z (make-connector))) (multiplier x y z) z)) (define (c/ x y) (let ((z (make-connector))) (multiplier z y x) z)) (define (cv x) (let ((z (make-connector))) (constant x z) z)) (define (celsius-fahrenheit-converter x) (c+ (c* (c/ (cv 9) (cv 5)) x) (cv 32))) (define C (make-connector)) (define F (celsius-fahrenheit-converter C)) ;; 1 ]=> (probe "Celsius temp" C) Value 8 : # [ compound - procedure 8 me ] 1 ]= > ( probe " temp " F ) Value 9 : # [ compound - procedure 9 me ] ;; 1 ]=> (set-value! C 25 'user) Probe : Celsius temp = 25 Probe : temp = 77 ;; Value: done
null
https://raw.githubusercontent.com/MarkCurtiss/sicp/8b55a3371458014c815ba8792218b6440127ab40/chapter_3_exercises/3_28_to_3_37.scm
scheme
======================================================================== ======================================================================== The delay time is equal to (+ inverter-delay inverter-delay and-gate-delay) ======================================================================== The delay time will be ======================================================================== If we didn't invoke the callback right away we wouldn't actually place Thus, the simulation wouldn't produce any output. ======================================================================== queue stack (B 1 -> 0, A 1 -> 0, B 0 -> 1, A 0 -> 1) If a stack were used, the AND gate would appear to go (incorrectly): False, False, False, True If the queue is used, the AND gate properly signals: False, True, False, False. ======================================================================== Here comes a few pages of copypasta: Okay now here is some new code. ;Value: done ======================================================================== Changes to the value of b won't propagate back to a. 1 ]=> (define (squarer a b) (multiplier a a b)) Value: squarer 1 ]=> (define R (make-connector)) Value: r 1 ]=> (define S (make-connector)) Value: s 1 ]=> (probe "R" R) 1 ]=> (probe "S" S) 1 ]=> (squarer R S) 1 ]=> (set-value! R 4 'user) Value: done So far so good. But now, observe: 1 ]=> (forget-value! R 'user) Probe: S = ? Probe: R = ? Value: done 1 ]=> (set-value! S 16 'user) Value: done Notice that we don't see the value of R change. This is because none of the conditionals in (process-new-value) in ======================================================================== 1 ]=> (define R (make-connector)) Value: r 1 ]=> (define S (make-connector)) Value: s 1 ]=> (probe "R" R) 1 ]=> (probe "S" S) 1 ]=> (squarer R S) 1 ]=> (set-value! R 4 'user) Value: done 1 ]=> (forget-value! R 'user) Probe: S = ? Probe: R = ? Value: done 1 ]=> (set-value! S 16 'user) Value: done ======================================================================== ======================================================================== 1 ]=> (probe "Celsius temp" C) 1 ]=> (set-value! C 25 'user) Value: done
3.28 (define (logical-or signal1 signal2) (or signal1 signal2)) (define (or-gate wire1 wire2 output-wire) (define (or-action-procedure) (let ((new-value (logical-or (get-signal wire1) (get-signal wire2)))) (after-delay or-gate-delay (lambda () (set-signal! output-wire new-value))))) (add-action! wire1 or-action-procedure) (add-action! wire2 or-action-procedure) 'ok) 3.29 (define (and-gate a1 a2 output) (define (and-action-procedure) (let ((new-value (logical-and (get-signal a1) (get-signal a2)))) (after-delay and-gate-delay (lambda () (set-signal! output new-value))))) (add-action! a1 and-action-procedure) (add-action! a2 and-action-procedure) 'ok) (define (inverter input output) (define (invert-input) (let ((new-value (logical-not (get-signal input)))) (after-delay inverter-delay (lambda () (set-signal! output new-value))))) (add-action! input invert-input) 'ok) (define (logical-and signal1 signal2) (and signal1 signal2)) (define (logical-not s) (cond ((= s 0) 1) ((= s 1) 0) (else (error "Invalid signal" s)))) (define (or-gate wire1 wire2 output-wire) (let ((wire3 (make-wire)) (wire4 (make-wire))) (inverter wire1 wire3) (inverter wire2 wire4) (and-gate wire3 wire4 output-wire))) 3.30 (define (ripple-carry-adder a-list b-list sum-list carry-in) (let ((carry-out (make-wire))) (if (null? (cdr a-list)) (full-adder (car a-list) (car b-list) carry-in (car s-list) carry-out) (ripple-carry-adder (cdr a-list b-list sum-list carry-out))))) n * ( 2 * ( half - adder + or - gate ) ) = = n * ( ( 2 * ( or - gate + ( 2 * and - gate ) + inverter ) ) + or - gate ) 3.31 events in the agenda when we construct half - adders and or - gates and such . 3.32 ( A 0 - > 1 , B 0 - > 1 , A 1 - > 0 , B 1 - > 0 ) 3.33 (define (adder a1 a2 sum) (define (process-new-value) (cond ((and (has-value? a1) (has-value? a2)) (set-value! sum (+ (get-value a1) (get-value a2)) me)) ((and (has-value? a1) (has-value? sum)) (set-value! a2 (- (get-value sum) (get-value a1)) me)) ((and (has-value? a2) (has-value? sum)) (set-value! a1 (- (get-value sum) (get-value a2)) me)))) (define (process-forget-value) (forget-value! sum me) (forget-value! a1 me) (forget-value! a2 me) (process-new-value)) (define (me request) (cond ((eq? request 'I-have-a-value) (process-new-value)) ((eq? request 'I-lost-my-value) (process-forget-value)) (else (error "Unknown request -- ADDER" request)))) (connect a1 me) (connect a2 me) (connect sum me) me) (define (inform-about-value constraint) (constraint 'I-have-a-value)) (define (inform-about-no-value constraint) (constraint 'I-lost-my-value)) (define (multiplier m1 m2 product) (define (process-new-value) (cond ((or (and (has-value? m1) (= (get-value m1) 0)) (and (has-value? m2) (= (get-value m2) 0))) (set-value! product 0 me)) ((and (has-value? m1) (has-value? m2)) (set-value! product (* (get-value m1) (get-value m2)) me)) ((and (has-value? product) (has-value? m1)) (set-value! m2 (/ (get-value product) (get-value m1)) me)) ((and (has-value? product) (has-value? m2)) (set-value! m1 (/ (get-value product) (get-value m2)) me)))) (define (process-forget-value) (forget-value! product me) (forget-value! m1 me) (forget-value! m2 me) (process-new-value)) (define (me request) (cond ((eq? request 'I-have-a-value) (process-new-value)) ((eq? request 'I-lost-my-value) (process-forget-value)) (else (error "Unknown request -- MULTIPLIER" request)))) (connect m1 me) (connect m2 me) (connect product me) me) (define (constant value connector) (define (me request) (error "Unknown request -- CONSTANT" request)) (connect connector me) (set-value! connector value me) me) (define (probe name connector) (define (print-probe value) (newline) (display "Probe: ") (display name) (display " = ") (display value)) (define (process-new-value) (print-probe (get-value connector))) (define (process-forget-value) (print-probe "?")) (define (me request) (cond ((eq? request 'I-have-a-value) (process-new-value)) ((eq? request 'I-lost-my-value) (process-forget-value)) (else (error "Unknown request -- PROBE" request)))) (connect connector me) me) (define (make-connector) (let ((value false) (informant false) (constraints '())) (define (set-my-value newval setter) (cond ((not (has-value? me)) (set! value newval) (set! informant setter) (for-each-except setter inform-about-value constraints)) ((not (= value newval)) (error "Contradiction" (list value newval))) (else 'ignored))) (define (forget-my-value retractor) (if (eq? retractor informant) (begin (set! informant false) (for-each-except retractor inform-about-no-value constraints)) 'ignored)) (define (connect new-constraint) (if (not (memq new-constraint constraints)) (set! constraints (cons new-constraint constraints))) (if (has-value? me) (inform-about-value new-constraint)) 'done) (define (me request) (cond ((eq? request 'has-value?) (if informant true false)) ((eq? request 'value) value) ((eq? request 'set-value!) set-my-value) ((eq? request 'forget) forget-my-value) ((eq? request 'connect) connect) (else (error "Unknown operation -- CONNECTOR" request)))) me)) (define (for-each-except exception procedure list) (define (loop items) (cond ((null? items) 'done) ((eq? (car items) exception) (loop (cdr items))) (else (procedure (car items)) (loop (cdr items))))) (loop list)) (define (has-value? connector) (connector 'has-value?)) (define (get-value connector) (connector 'value)) (define (set-value! connector new-value informant) ((connector 'set-value!) new-value informant)) (define (forget-value! connector retractor) ((connector 'forget) retractor)) (define (connect connector new-constraint) ((connector 'connect) new-constraint)) (define (averager a b c) (let ((twoc (make-connector)) (u (make-connector)) (v (make-connector))) (multiplier c twoc u) (constant 2 twoc) (adder a b u)) 'ok) (define A (make-connector)) (define B (make-connector)) (define C (make-connector)) (averager A B C) (probe "A" A) (probe "B" B) (probe "C" C) (set-value! A 9 'user) (set-value! B 11 'user) Probe : A = 9 Probe : B = 11 Probe : C = 10 3.34 Value 5 : # [ compound - procedure 5 me ] Value 6 : # [ compound - procedure 6 me ] Value 7 : # [ compound - procedure 7 me ] Probe : S = 16 Probe : R = 4 Probe : S = 16 ( multiplier product ) will ever be hit - although product has a value neither m1 nor have a value in implementation . 3.35 (define (squarer a b) (define (process-new-value) (if (has-value? b) (if (< (get-value b) 0) (error "square less than 0 -- SQUARER" (get-value b)) (set-value! a (sqrt (get-value b)) me)) (if (has-value? a) (set-value! b (square (get-value a)) me)))) (define (process-forget-value) (forget-value! a me) (forget-value! b me) (process-new-value)) (define (me request) (cond ((eq? request 'I-have-a-value) (process-new-value)) ((eq? request 'I-lost-my-value) (process-forget-value)) (else (error "Unknown request -- SQUARER" request)))) (connect a me) (connect b me) me) Value 8 : # [ compound - procedure 8 me ] Value 9 : # [ compound - procedure 9 me ] Value 10 : # [ compound - procedure 10 me ] Probe : S = 16 Probe : R = 4 Probe : R = 4 Probe : S = 16 3.36 " +--------------------------------------+ global-env+--->| | | |<------------------------+ | | | +-----------+a b+--------+ | | +--------------------------------------+ | | | ^ | | | | | | | | | +-------+--------+ | +---------+------+ v E2+-->|value: false | v E1+-->|value: 10 | +-+ |informant: false| +-+ |informant: 'user|<-----------+ |+-------> |constraints: () | |+------->|constraints: () | | +-+ +----------------+ +-+ +----------------+ | |+------+ +--+| | +-+ | | +-+ | | | | | v +-----------+-----------------+ v params: request E3+-->|exception: 'user | params: request body: |procedure: inform-about-value| body: (cond ((eq? request 'has... |list: () | (cond ((eq? request 'has... +-----------------------------+ +-+ ^ |+------------------+ +-+ +-----------+| v +-+ params: exception, procedure, list body: (define (loop items) ... " 3.37 (define (c+ x y) (let ((z (make-connector))) (adder x y z) z)) (define (c* x y) (let ((z (make-connector))) (multiplier x y z) z)) (define (c/ x y) (let ((z (make-connector))) (multiplier z y x) z)) (define (cv x) (let ((z (make-connector))) (constant x z) z)) (define (celsius-fahrenheit-converter x) (c+ (c* (c/ (cv 9) (cv 5)) x) (cv 32))) (define C (make-connector)) (define F (celsius-fahrenheit-converter C)) Value 8 : # [ compound - procedure 8 me ] 1 ]= > ( probe " temp " F ) Value 9 : # [ compound - procedure 9 me ] Probe : Celsius temp = 25 Probe : temp = 77
874db743df282014dd0d80d9f6b3f5d0d844c8b57058c225b242cb46d6402f39
titola/incudine
gen-envelope.lisp
(in-package :incudine-tests) (defun gen-envelope-test-1 (env &key periodic-p normalize-p (mult 1)) (with-cleanup (mapcar #'sample->fixnum (buffer->list (scale-buffer (make-buffer 64 :fill-function (gen:envelope env :periodic-p periodic-p :normalize-p normalize-p)) mult))))) (deftest gen-envelope.1 (with-cleanup (gen-envelope-test-1 (make-envelope '(-1000 300 0) '(.5 1.2)))) (-1000 -928 -856 -784 -712 -639 -567 -495 -423 -351 -278 -206 -134 -62 11 83 155 227 300 293 286 279 273 266 259 253 246 239 233 226 219 213 206 199 193 186 180 173 166 160 153 146 140 133 126 120 113 106 100 93 86 80 73 66 60 53 46 40 33 26 20 13 6 0)) (deftest gen-envelope.2 (with-cleanup (gen-envelope-test-1 (make-envelope '(-1000 300 0) '(.5 1.2)) :periodic-p t)) (-1000 -928 -856 -784 -712 -639 -567 -495 -423 -351 -278 -206 -134 -62 11 83 155 227 300 293 286 280 273 267 260 254 247 241 234 228 221 215 208 202 195 189 182 176 169 163 156 149 143 136 130 123 117 110 104 97 91 84 78 71 65 58 52 45 39 32 26 19 13 6)) (deftest gen-envelope.3 (with-cleanup (gen-envelope-test-1 (make-envelope '(-35 8 -9 0) '(.5 .2 1.3)) :normalize-p t :mult 1000)) (-1000 -919 -837 -755 -673 -591 -509 -427 -345 -263 -181 -100 -18 64 146 228 147 66 -15 -96 -177 -258 -252 -245 -239 -233 -227 -221 -215 -209 -203 -196 -190 -184 -178 -172 -166 -160 -154 -147 -141 -135 -129 -123 -117 -111 -105 -98 -92 -86 -80 -74 -68 -62 -56 -49 -43 -37 -31 -25 -19 -13 -7 0)) (deftest gen-envelope.4 (with-cleanup (gen-envelope-test-1 (make-envelope '(-35 8 -9 0) '(.5 .2 1.3)) :periodic-p t :normalize-p t :mult 1000)) (-1000 -924 -847 -770 -693 -617 -540 -463 -386 -309 -233 -156 -79 -2 75 151 228 147 66 -15 -96 -177 -258 -252 -245 -239 -233 -227 -221 -215 -209 -203 -196 -190 -184 -178 -172 -166 -160 -154 -147 -141 -135 -129 -123 -117 -111 -105 -98 -92 -86 -80 -74 -68 -62 -56 -49 -43 -37 -31 -25 -19 -13 -7))
null
https://raw.githubusercontent.com/titola/incudine/325174a54a540f4daa67bcbb29780073c35b7b80/tests/gen-envelope.lisp
lisp
(in-package :incudine-tests) (defun gen-envelope-test-1 (env &key periodic-p normalize-p (mult 1)) (with-cleanup (mapcar #'sample->fixnum (buffer->list (scale-buffer (make-buffer 64 :fill-function (gen:envelope env :periodic-p periodic-p :normalize-p normalize-p)) mult))))) (deftest gen-envelope.1 (with-cleanup (gen-envelope-test-1 (make-envelope '(-1000 300 0) '(.5 1.2)))) (-1000 -928 -856 -784 -712 -639 -567 -495 -423 -351 -278 -206 -134 -62 11 83 155 227 300 293 286 279 273 266 259 253 246 239 233 226 219 213 206 199 193 186 180 173 166 160 153 146 140 133 126 120 113 106 100 93 86 80 73 66 60 53 46 40 33 26 20 13 6 0)) (deftest gen-envelope.2 (with-cleanup (gen-envelope-test-1 (make-envelope '(-1000 300 0) '(.5 1.2)) :periodic-p t)) (-1000 -928 -856 -784 -712 -639 -567 -495 -423 -351 -278 -206 -134 -62 11 83 155 227 300 293 286 280 273 267 260 254 247 241 234 228 221 215 208 202 195 189 182 176 169 163 156 149 143 136 130 123 117 110 104 97 91 84 78 71 65 58 52 45 39 32 26 19 13 6)) (deftest gen-envelope.3 (with-cleanup (gen-envelope-test-1 (make-envelope '(-35 8 -9 0) '(.5 .2 1.3)) :normalize-p t :mult 1000)) (-1000 -919 -837 -755 -673 -591 -509 -427 -345 -263 -181 -100 -18 64 146 228 147 66 -15 -96 -177 -258 -252 -245 -239 -233 -227 -221 -215 -209 -203 -196 -190 -184 -178 -172 -166 -160 -154 -147 -141 -135 -129 -123 -117 -111 -105 -98 -92 -86 -80 -74 -68 -62 -56 -49 -43 -37 -31 -25 -19 -13 -7 0)) (deftest gen-envelope.4 (with-cleanup (gen-envelope-test-1 (make-envelope '(-35 8 -9 0) '(.5 .2 1.3)) :periodic-p t :normalize-p t :mult 1000)) (-1000 -924 -847 -770 -693 -617 -540 -463 -386 -309 -233 -156 -79 -2 75 151 228 147 66 -15 -96 -177 -258 -252 -245 -239 -233 -227 -221 -215 -209 -203 -196 -190 -184 -178 -172 -166 -160 -154 -147 -141 -135 -129 -123 -117 -111 -105 -98 -92 -86 -80 -74 -68 -62 -56 -49 -43 -37 -31 -25 -19 -13 -7))
f363b1d5be6fd028eb1f38ec803c33352378a405378aa9ba7cad9c58a973c8fa
nomeata/arbtt
MyText.hs
module Data.MyText where import qualified Data.ByteString.UTF8 as BSU import qualified Data.ByteString.Lazy.UTF8 as BLU import qualified Data.ByteString.Lazy as LBS import qualified Data.ByteString as BS import Data.Binary.Get import Data.Binary import Control.Applicative ((<$>)) import Control.Arrow (first) import Prelude hiding (length, map, null) import qualified Prelude import GHC.Exts( IsString(..) ) import Control.DeepSeq import Control.Monad newtype Text = Text { toBytestring :: BSU.ByteString } deriving (Eq, Ord) instance Show Text where showsPrec i t = showsPrec i (toBytestring t) instance Read Text where readsPrec i s = Prelude.map (first Text) $ readsPrec i s instance IsString Text where fromString = pack -- Binary instance compatible with Binary String instance Binary Text where put = put . unpack get = pack <$> get The following code exploits that the Binary instance uses UTF8 as well The downside is that it quietly suceeds for broken input -- Unfortunately, with binary-0.7, it is no longer possible to implement -- this nice and lazily, so go via String :-( get = do n < - get : : Get Int bs < - lookAhead $ getRemainingLazyByteString let utf8bs = BLU.take ( fromIntegral n ) bs unless ( BLU.length utf8bs = = n ) $ fail $ " Coult not parse the expected " + + show n + + " utf8 characters . " let sbs = LBS.toStrict utf8bs skip $ BS.length sbs return $ Text sbs get = do n <- get :: Get Int bs <- lookAhead $ getRemainingLazyByteString let utf8bs = BLU.take (fromIntegral n) bs unless (BLU.length utf8bs == n) $ fail $ "Coult not parse the expected " ++ show n ++ " utf8 characters." let sbs = LBS.toStrict utf8bs skip $ BS.length sbs return $ Text sbs -} Possible speedup with a version of binary that provides access to the internals , as the instance is actually UTF8 , but the length bit is chars , not bytes . instance Binary Text where put = put . unpack get = do n < - get : : Get Int let go = do s < - GI.get let utf8s = BSU.take n s if BSU.length utf8s = = n then ( B.length utf8s ) > > return utf8s else GI.demandInput > > go go internals, as the Char instance is actually UTF8, but the length bit is chars, not bytes. instance Binary Text where put = put . unpack get = do n <- get :: Get Int let go = do s <- GI.get let utf8s = BSU.take n s if BSU.length utf8s == n then GI.skip (B.length utf8s) >> return utf8s else GI.demandInput >> go go -} instance NFData Text where rnf (Text a) = a `seq` () length :: Text -> Int length (Text bs) = BSU.length bs decodeUtf8 :: BS.ByteString -> Text decodeUtf8 = Text encodeUtf8 :: Text -> BS.ByteString encodeUtf8 = toBytestring unpack :: Text -> String unpack = BSU.toString . toBytestring pack :: String -> Text pack = Text . BSU.fromString map :: (Char -> Char) -> Text -> Text map f = pack . Prelude.map f . unpack concat :: [Text] -> Text concat = Text . BS.concat . Prelude.map toBytestring null :: Text -> Bool null = BS.null . toBytestring
null
https://raw.githubusercontent.com/nomeata/arbtt/5e9bf42785e075adaa574bf853f7adbc3408e7f4/src/Data/MyText.hs
haskell
Binary instance compatible with Binary String Unfortunately, with binary-0.7, it is no longer possible to implement this nice and lazily, so go via String :-(
module Data.MyText where import qualified Data.ByteString.UTF8 as BSU import qualified Data.ByteString.Lazy.UTF8 as BLU import qualified Data.ByteString.Lazy as LBS import qualified Data.ByteString as BS import Data.Binary.Get import Data.Binary import Control.Applicative ((<$>)) import Control.Arrow (first) import Prelude hiding (length, map, null) import qualified Prelude import GHC.Exts( IsString(..) ) import Control.DeepSeq import Control.Monad newtype Text = Text { toBytestring :: BSU.ByteString } deriving (Eq, Ord) instance Show Text where showsPrec i t = showsPrec i (toBytestring t) instance Read Text where readsPrec i s = Prelude.map (first Text) $ readsPrec i s instance IsString Text where fromString = pack instance Binary Text where put = put . unpack get = pack <$> get The following code exploits that the Binary instance uses UTF8 as well The downside is that it quietly suceeds for broken input get = do n < - get : : Get Int bs < - lookAhead $ getRemainingLazyByteString let utf8bs = BLU.take ( fromIntegral n ) bs unless ( BLU.length utf8bs = = n ) $ fail $ " Coult not parse the expected " + + show n + + " utf8 characters . " let sbs = LBS.toStrict utf8bs skip $ BS.length sbs return $ Text sbs get = do n <- get :: Get Int bs <- lookAhead $ getRemainingLazyByteString let utf8bs = BLU.take (fromIntegral n) bs unless (BLU.length utf8bs == n) $ fail $ "Coult not parse the expected " ++ show n ++ " utf8 characters." let sbs = LBS.toStrict utf8bs skip $ BS.length sbs return $ Text sbs -} Possible speedup with a version of binary that provides access to the internals , as the instance is actually UTF8 , but the length bit is chars , not bytes . instance Binary Text where put = put . unpack get = do n < - get : : Get Int let go = do s < - GI.get let utf8s = BSU.take n s if BSU.length utf8s = = n then ( B.length utf8s ) > > return utf8s else GI.demandInput > > go go internals, as the Char instance is actually UTF8, but the length bit is chars, not bytes. instance Binary Text where put = put . unpack get = do n <- get :: Get Int let go = do s <- GI.get let utf8s = BSU.take n s if BSU.length utf8s == n then GI.skip (B.length utf8s) >> return utf8s else GI.demandInput >> go go -} instance NFData Text where rnf (Text a) = a `seq` () length :: Text -> Int length (Text bs) = BSU.length bs decodeUtf8 :: BS.ByteString -> Text decodeUtf8 = Text encodeUtf8 :: Text -> BS.ByteString encodeUtf8 = toBytestring unpack :: Text -> String unpack = BSU.toString . toBytestring pack :: String -> Text pack = Text . BSU.fromString map :: (Char -> Char) -> Text -> Text map f = pack . Prelude.map f . unpack concat :: [Text] -> Text concat = Text . BS.concat . Prelude.map toBytestring null :: Text -> Bool null = BS.null . toBytestring
eddc8473b3bcfbd916b6831b4d51f9bbfa6b35ec05b52199126afc7843958a59
DSiSc/why3
eliminate_if.ml
(********************************************************************) (* *) The Why3 Verification Platform / The Why3 Development Team Copyright 2010 - 2018 -- Inria - CNRS - Paris - Sud University (* *) (* This software is distributed under the terms of the GNU Lesser *) General Public License version 2.1 , with the special exception (* on linking described in file LICENSE. *) (* *) (********************************************************************) open Ident open Term open Decl (** Eliminate if-then-else in terms *) let rec has_if t = match t.t_node with | Tif _ -> true | _ -> TermTF.t_any has_if Util.ffalse t let rec elim_t contT t = let contTl e = contT (t_attr_copy t e) in match t.t_node with | Tlet (t1,tb) -> let u,t2,close = t_open_bound_cb tb in let cont_in t1 t2 = contTl (t_let t1 (close u t2)) in let cont_let_t t1 = elim_t (cont_in t1) t2 in let cont_let_f t1 = t_let_close u t1 (elim_t contT t2) in elim_t (if has_if t2 then cont_let_f else cont_let_t) t1 | Tif (f,t1,t2) -> let f = elim_f (fun f -> f) f in t_if f (elim_t contT t1) (elim_t contT t2) | Tcase (t1, bl) -> let bl = List.rev_map t_open_branch_cb bl in let fi = List.exists (fun (_,t,_) -> has_if t) bl in let fnB ctB (p,t,cl) = elim_t (fun t -> ctB (cl p t)) t in let cont_with t1 bl = contTl (t_case t1 (List.rev bl)) in let cont_case_t t1 = list_map_cont fnB (cont_with t1) bl in let close (p,t,_) = t_close_branch p (elim_t contT t) in let cont_case_f t1 = t_case t1 (List.rev_map close bl) in elim_t (if fi then cont_case_f else cont_case_t) t1 | _ -> TermTF.t_map_cont elim_t elim_f contT t and elim_f contF f = match f.t_node with | Tapp _ | Tlet _ | Tcase _ -> contF (TermTF.t_map_cont elim_t elim_f (fun f -> f) f) | _ -> TermTF.t_map_cont elim_tr elim_f contF f (* the only terms we still can meet are the terms in triggers *) and elim_tr contT t = match t.t_node with | Tif _ -> Printer.unsupportedTerm t "cannot eliminate 'if-then-else' in trigger terms" | _ -> TermTF.t_map_cont elim_tr elim_f contT t let elim_f f = elim_f (fun f -> f) f let rec elim_t t = TermTF.t_map elim_t elim_f t let add_ld (ls,ld) (abst,defn,axl) = let vl,e,close = open_ls_defn_cb ld in match e.t_ty with | Some _ when has_if e -> let nm = ls.ls_name.id_string ^ "_def" in let pr = create_prsymbol (id_derive nm ls.ls_name) in let hd = t_app ls (List.map t_var vl) e.t_ty in let ax = t_forall_close vl [] (elim_f (t_equ hd e)) in let ax = create_prop_decl Paxiom pr ax in let ld = create_param_decl ls in ld :: abst, defn, ax :: axl | _ -> let d = close ls vl (TermTF.t_select elim_t elim_f e) in abst, d :: defn, axl let elim_d d = match d.d_node with | Dlogic l -> let abst,defn,axl = List.fold_right add_ld l ([],[],[]) in let defn = if defn = [] then [] else [create_logic_decl defn] in abst @ defn @ axl | Dind (s, l) -> let rec clause f = match f.t_node with | Tquant (Tforall, f) -> let vs,tr,f = t_open_quant f in List.map (t_forall_close vs tr) (clause f) | Tbinop (Timplies, g, f) -> List.map (t_implies g) (clause f) | Tlet (t, bf) -> let v, f = t_open_bound bf in List.map (t_let_close v t) (clause f) (* need to eliminate if to get a clause *) | Tif (f1,f2,f3) -> clause (t_implies f1 f2) @ clause (t_implies (t_not f1) f3) | _ -> [f] in let fn (pr,f) = match clause (elim_f f) with | [] -> assert false keep the same symbol when one clause | l -> List.map (fun f -> create_prsymbol (id_clone pr.pr_name), f) l in let fn (ps,l) = ps, List.concat (List.map fn l) in [create_ind_decl s (List.map fn l)] | _ -> [DeclTF.decl_map (fun _ -> assert false) elim_f d] let eliminate_if_term = Trans.decl elim_d None (** Eliminate if-then-else in formulas *) let rec elim_t t = TermTF.t_map elim_t (elim_f true) t and elim_f sign f = match f.t_node with | Tif (f1,f2,f3) -> let f1p = elim_f sign f1 in let f1n = elim_f (not sign) f1 in let f2 = elim_f sign f2 in let f3 = elim_f sign f3 in if sign then t_and (t_implies f1n f2) (t_implies (t_not f1p) f3) else t_or (t_and f1p f2) (t_and (t_not f1n) f3) | _ -> TermTF.t_map_sign (Util.const elim_t) elim_f sign f let eliminate_if_fmla = Trans.rewriteTF elim_t (elim_f true) None let eliminate_if = Trans.compose eliminate_if_term eliminate_if_fmla let () = Trans.register_transform "eliminate_if_term" eliminate_if_term ~desc:"Replaces@ terms@ of@ the@ form@ [if f1 then t2 else t3]@ by@ \ lifting@ them@ at@ the@ level@ of@ formulas."; Trans.register_transform "eliminate_if_fmla" eliminate_if_fmla ~desc:"Eliminate@ formulas@ of@ the@ form@ [if f1 then f2 else f3]."; Trans.register_transform "eliminate_if" eliminate_if ~desc:"Eliminate@ all@ if-expressions."
null
https://raw.githubusercontent.com/DSiSc/why3/8ba9c2287224b53075adc51544bc377bc8ea5c75/src/transform/eliminate_if.ml
ocaml
****************************************************************** This software is distributed under the terms of the GNU Lesser on linking described in file LICENSE. ****************************************************************** * Eliminate if-then-else in terms the only terms we still can meet are the terms in triggers need to eliminate if to get a clause * Eliminate if-then-else in formulas
The Why3 Verification Platform / The Why3 Development Team Copyright 2010 - 2018 -- Inria - CNRS - Paris - Sud University General Public License version 2.1 , with the special exception open Ident open Term open Decl let rec has_if t = match t.t_node with | Tif _ -> true | _ -> TermTF.t_any has_if Util.ffalse t let rec elim_t contT t = let contTl e = contT (t_attr_copy t e) in match t.t_node with | Tlet (t1,tb) -> let u,t2,close = t_open_bound_cb tb in let cont_in t1 t2 = contTl (t_let t1 (close u t2)) in let cont_let_t t1 = elim_t (cont_in t1) t2 in let cont_let_f t1 = t_let_close u t1 (elim_t contT t2) in elim_t (if has_if t2 then cont_let_f else cont_let_t) t1 | Tif (f,t1,t2) -> let f = elim_f (fun f -> f) f in t_if f (elim_t contT t1) (elim_t contT t2) | Tcase (t1, bl) -> let bl = List.rev_map t_open_branch_cb bl in let fi = List.exists (fun (_,t,_) -> has_if t) bl in let fnB ctB (p,t,cl) = elim_t (fun t -> ctB (cl p t)) t in let cont_with t1 bl = contTl (t_case t1 (List.rev bl)) in let cont_case_t t1 = list_map_cont fnB (cont_with t1) bl in let close (p,t,_) = t_close_branch p (elim_t contT t) in let cont_case_f t1 = t_case t1 (List.rev_map close bl) in elim_t (if fi then cont_case_f else cont_case_t) t1 | _ -> TermTF.t_map_cont elim_t elim_f contT t and elim_f contF f = match f.t_node with | Tapp _ | Tlet _ | Tcase _ -> contF (TermTF.t_map_cont elim_t elim_f (fun f -> f) f) | _ -> TermTF.t_map_cont elim_tr elim_f contF f and elim_tr contT t = match t.t_node with | Tif _ -> Printer.unsupportedTerm t "cannot eliminate 'if-then-else' in trigger terms" | _ -> TermTF.t_map_cont elim_tr elim_f contT t let elim_f f = elim_f (fun f -> f) f let rec elim_t t = TermTF.t_map elim_t elim_f t let add_ld (ls,ld) (abst,defn,axl) = let vl,e,close = open_ls_defn_cb ld in match e.t_ty with | Some _ when has_if e -> let nm = ls.ls_name.id_string ^ "_def" in let pr = create_prsymbol (id_derive nm ls.ls_name) in let hd = t_app ls (List.map t_var vl) e.t_ty in let ax = t_forall_close vl [] (elim_f (t_equ hd e)) in let ax = create_prop_decl Paxiom pr ax in let ld = create_param_decl ls in ld :: abst, defn, ax :: axl | _ -> let d = close ls vl (TermTF.t_select elim_t elim_f e) in abst, d :: defn, axl let elim_d d = match d.d_node with | Dlogic l -> let abst,defn,axl = List.fold_right add_ld l ([],[],[]) in let defn = if defn = [] then [] else [create_logic_decl defn] in abst @ defn @ axl | Dind (s, l) -> let rec clause f = match f.t_node with | Tquant (Tforall, f) -> let vs,tr,f = t_open_quant f in List.map (t_forall_close vs tr) (clause f) | Tbinop (Timplies, g, f) -> List.map (t_implies g) (clause f) | Tlet (t, bf) -> let v, f = t_open_bound bf in List.map (t_let_close v t) (clause f) | Tif (f1,f2,f3) -> clause (t_implies f1 f2) @ clause (t_implies (t_not f1) f3) | _ -> [f] in let fn (pr,f) = match clause (elim_f f) with | [] -> assert false keep the same symbol when one clause | l -> List.map (fun f -> create_prsymbol (id_clone pr.pr_name), f) l in let fn (ps,l) = ps, List.concat (List.map fn l) in [create_ind_decl s (List.map fn l)] | _ -> [DeclTF.decl_map (fun _ -> assert false) elim_f d] let eliminate_if_term = Trans.decl elim_d None let rec elim_t t = TermTF.t_map elim_t (elim_f true) t and elim_f sign f = match f.t_node with | Tif (f1,f2,f3) -> let f1p = elim_f sign f1 in let f1n = elim_f (not sign) f1 in let f2 = elim_f sign f2 in let f3 = elim_f sign f3 in if sign then t_and (t_implies f1n f2) (t_implies (t_not f1p) f3) else t_or (t_and f1p f2) (t_and (t_not f1n) f3) | _ -> TermTF.t_map_sign (Util.const elim_t) elim_f sign f let eliminate_if_fmla = Trans.rewriteTF elim_t (elim_f true) None let eliminate_if = Trans.compose eliminate_if_term eliminate_if_fmla let () = Trans.register_transform "eliminate_if_term" eliminate_if_term ~desc:"Replaces@ terms@ of@ the@ form@ [if f1 then t2 else t3]@ by@ \ lifting@ them@ at@ the@ level@ of@ formulas."; Trans.register_transform "eliminate_if_fmla" eliminate_if_fmla ~desc:"Eliminate@ formulas@ of@ the@ form@ [if f1 then f2 else f3]."; Trans.register_transform "eliminate_if" eliminate_if ~desc:"Eliminate@ all@ if-expressions."
6e1a69d961ed5065a6fd2002dedd0f87edbe2358128528d71c6309888f9f035f
thoughtstem/morugamu
emoji-bool.rkt
#lang racket (provide theme) (require 2htdp/image) (define theme (list (bitmap "./emojis/and.png") (bitmap "./emojis/or.png") (bitmap "./emojis/not.png") (bitmap "./emojis/true.png") (bitmap "./emojis/false.png") (text "if" 24 'black)))
null
https://raw.githubusercontent.com/thoughtstem/morugamu/a9095ddebe364adffb036c3faed95c873a4d9f3c/themes/emoji-bool.rkt
racket
#lang racket (provide theme) (require 2htdp/image) (define theme (list (bitmap "./emojis/and.png") (bitmap "./emojis/or.png") (bitmap "./emojis/not.png") (bitmap "./emojis/true.png") (bitmap "./emojis/false.png") (text "if" 24 'black)))
a508d9cd79728064667123213398467ac29ee154dfb3279652738c6c93a36348
karimarttila/clojure
session_common.clj
(ns simpleserver.sessiondb.session-common (:require [clojure.tools.logging :as log] [buddy.sign.jwt :as buddy-jwt] [clj-time.core :as c-time] [simpleserver.util.prop :as ss-prop] )) ;; The rational we have it here is that we can change the value in ;; remote REPL for debugging purposes, i.e. test token invalidation ;; dynamically. (def my-expiration-time "Atom to store the JSON Web Token expiration as seconds. The rational we have it here is that we can change the value in remote REPL for debugging purposes, i.e. test token invalidation dynamically." (atom (ss-prop/get-int-value "json-web-token-expiration-as-seconds"))) (def my-hex-secret "Creates dynamically a hex secret when the server boots." ((fn [] (let [my-chars (->> (range (int \a) (inc (int \z))) (map char)) my-ints (->> (range (int \0) (inc (int \9))) (map char)) my-set (lazy-cat my-chars my-ints) hexify (fn [s] (apply str (map #(format "%02x" (int %)) s)))] (hexify (repeatedly 24 #(rand-nth my-set))))))) (defn create-json-web-token [email] (log/debug (str "ENTER create-json-web-token, email: " email)) (let [my-secret my-hex-secret exp-time (c-time/plus (c-time/now) (c-time/seconds @my-expiration-time)) my-claim {:email email :exp exp-time} json-web-token (buddy-jwt/sign my-claim my-secret)] json-web-token)) (defn validate-token [token get-token remove-token] (log/debug (str "ENTER validate-token, token: " token)) (let [found-token (get-token token)] Part # 1 of validation . (if (nil? token) (do (log/warn (str "Token not found in my sessions - unknown token: " token)) nil) Part # 2 of validation . (try (buddy-jwt/unsign token my-hex-secret) (catch Exception e (if (.contains (.getMessage e) "Token is expired") (do (log/debug (str "Token is expired, removing it from my sessions and returning nil: " token)) (remove-token token) nil) ; Some other issue, throw it. (do (log/error (str "Some unknown exception when handling expired token, exception: " (.getMessage e)) ", token: " token) (throw e))))))))
null
https://raw.githubusercontent.com/karimarttila/clojure/ee1261b9a8e6be92cb47aeb325f82a278f2c1ed3/clj-ring-cljs-reagent-demo/simple-server/src/simpleserver/sessiondb/session_common.clj
clojure
The rational we have it here is that we can change the value in remote REPL for debugging purposes, i.e. test token invalidation dynamically. Some other issue, throw it.
(ns simpleserver.sessiondb.session-common (:require [clojure.tools.logging :as log] [buddy.sign.jwt :as buddy-jwt] [clj-time.core :as c-time] [simpleserver.util.prop :as ss-prop] )) (def my-expiration-time "Atom to store the JSON Web Token expiration as seconds. The rational we have it here is that we can change the value in remote REPL for debugging purposes, i.e. test token invalidation dynamically." (atom (ss-prop/get-int-value "json-web-token-expiration-as-seconds"))) (def my-hex-secret "Creates dynamically a hex secret when the server boots." ((fn [] (let [my-chars (->> (range (int \a) (inc (int \z))) (map char)) my-ints (->> (range (int \0) (inc (int \9))) (map char)) my-set (lazy-cat my-chars my-ints) hexify (fn [s] (apply str (map #(format "%02x" (int %)) s)))] (hexify (repeatedly 24 #(rand-nth my-set))))))) (defn create-json-web-token [email] (log/debug (str "ENTER create-json-web-token, email: " email)) (let [my-secret my-hex-secret exp-time (c-time/plus (c-time/now) (c-time/seconds @my-expiration-time)) my-claim {:email email :exp exp-time} json-web-token (buddy-jwt/sign my-claim my-secret)] json-web-token)) (defn validate-token [token get-token remove-token] (log/debug (str "ENTER validate-token, token: " token)) (let [found-token (get-token token)] Part # 1 of validation . (if (nil? token) (do (log/warn (str "Token not found in my sessions - unknown token: " token)) nil) Part # 2 of validation . (try (buddy-jwt/unsign token my-hex-secret) (catch Exception e (if (.contains (.getMessage e) "Token is expired") (do (log/debug (str "Token is expired, removing it from my sessions and returning nil: " token)) (remove-token token) nil) (do (log/error (str "Some unknown exception when handling expired token, exception: " (.getMessage e)) ", token: " token) (throw e))))))))
7113c083fbda3b56cb861bc0bece76b29b318394c6874f421b5c019928645831
janestreet/incr_dom
row.mli
open! Core open! Incr_dom open! Import module Model : sig type t [@@deriving compare] val columns : t Column.t list val matches_pattern : t -> string -> bool val apply_edit : t -> column:string -> string -> t end module Action : sig type t [@@deriving sexp] val kick_price : t val kick_position : t end module Mode : sig type t = | Unfocused | Focused | Editing [@@deriving sexp] end val apply_action : Action.t -> Model.t -> Model.t val view : Model.t Incr.t -> mode:Mode.t Incr.t -> sort_columns:int list -> focused_column:int option Incr.t -> focus_me:unit Vdom.Effect.t -> focus_nth_column:(int -> unit Vdom.Effect.t) -> remember_edit:(column:string -> string -> unit Vdom.Effect.t) -> Row_node_spec.t Incr.t val random_row : unit -> Model.t val random_rows : int -> Model.t list
null
https://raw.githubusercontent.com/janestreet/incr_dom/f2dfcf932d252aec523ccbe3da02b5d264e4a1a2/example/ts_gui/row.mli
ocaml
open! Core open! Incr_dom open! Import module Model : sig type t [@@deriving compare] val columns : t Column.t list val matches_pattern : t -> string -> bool val apply_edit : t -> column:string -> string -> t end module Action : sig type t [@@deriving sexp] val kick_price : t val kick_position : t end module Mode : sig type t = | Unfocused | Focused | Editing [@@deriving sexp] end val apply_action : Action.t -> Model.t -> Model.t val view : Model.t Incr.t -> mode:Mode.t Incr.t -> sort_columns:int list -> focused_column:int option Incr.t -> focus_me:unit Vdom.Effect.t -> focus_nth_column:(int -> unit Vdom.Effect.t) -> remember_edit:(column:string -> string -> unit Vdom.Effect.t) -> Row_node_spec.t Incr.t val random_row : unit -> Model.t val random_rows : int -> Model.t list
ec50e0d0006bf03a7ab94df2444a2a24d01f6732f935ff7fb76c1dd918bdce62
sgbj/MaximaSharp
cobyla-interface.lisp
;;; -*- Mode: lisp -*- Simple Maxima interface to COBYLA , Constrained Optimization BY ;;; Linear Approximations. (in-package #-gcl #:maxima #+gcl "MAXIMA") ;; Variable that will hold the function that calculates the function ;; value and the constraints. (defvar *calcfc*) (in-package #-gcl #:cobyla #+gcl "COBYLA") COBYLA always calls CALCFC to compute the function value and the ;; constraint equations. But we want to be able to specify different versions . So , COBYLA calls CALCFC , which then calls * CALCFC * to ;; do the real compuation. (defun calcfc (n m x f con) (declare (ignore f)) (funcall maxima::*calcfc* n m x con)) (in-package #-gcl #:maxima #+gcl "MAXIMA") The actual interface to COBYLA . Take the inputs from maxima , massage them into a suitable Lisp form , and call COBYLA to find the ;; answer. (defun %cobyla (vars init-x f &key (ineq (list '(mlist))) eq (rhobeg .5d0) (rhoend 1d-6) (iprint 0) (maxfun 1000)) (when (and eq (cdr eq)) ;; If there are equality constraints, append them to the list of ;; inequality constraints, and then append the negative of the ;; equality constraints too. That is, if the equality constraint is ;; h(X) = 0, then we add inequality constraints h(X) >= 0 and -h(X) ;; >= 0. (setf ineq (append ineq (cdr eq) (mapcar #'(lambda (e) (mul -1 e)) (cdr eq))))) (let* ((n (length (cdr vars))) (m (length (cdr ineq))) (x (make-array n :element-type 'double-float :initial-contents (mapcar #'(lambda (z) (let ((r ($float z))) (if (floatp r) r (merror "Does not evaluate to a float: ~M" z)))) (cdr init-x)))) Real work array for . (w (make-array (+ (* n (+ (* 3 n) (* 2 m) 11)) (+ (* 4 m) 6) 6) :element-type 'double-float)) Integer work array for . (iact (make-array (+ m 1) :element-type 'f2cl-lib::integer4)) (fv (coerce-float-fun f vars)) (cv (coerce-float-fun ineq vars)) (*calcfc* #'(lambda (nn mm xval cval) ;; Compute the function and the constraints at ;; the given xval. The function value is ;; returned is returned, and the constraint ;; values are stored in cval. (declare (fixnum nn mm) (type (cl:array double-float (*)) xval cval)) (let* ((x-list (coerce xval 'list)) (f (apply fv x-list)) (c (apply cv x-list))) ;; Do we really need these checks? (unless (floatp f) (merror "The objective function did not evaluate to a number at ~M" (list* '(mlist) x-list))) (unless (every #'floatp (cdr c)) (let ((bad-cons (loop for cval in (cdr c) for k from 1 unless (floatp cval) collect k))) ;; List the constraints that did not ;; evaluate to a number to make it easier ;; for the user to figure out which ;; constraints were bad. (mformat t "At the point ~M:~%" (list* '(mlist) x-list)) (merror (with-output-to-string (msg) (loop for index in bad-cons do (mformat msg "Constraint ~M: ~M did not evaluate to a number.~%" index (elt ineq index))))))) (replace cval c :start2 1) ;; This is the f2cl calling convention for CALCFC . For some reason , thinks n ;; and m are modified, so they must be ;; returned. (values nn mm nil f nil))))) (multiple-value-bind (null-0 null-1 null-2 null-3 null-4 null-5 neval null-6 null-7 ierr) (cobyla:cobyla n m x rhobeg rhoend iprint maxfun w iact 0) (declare (ignore null-0 null-1 null-2 null-3 null-4 null-5 null-6 null-7)) ;; Should we put a check here if the number of function ;; evaluations equals maxfun? When iprint is not 0, the output from COBYLA makes it clear that something bad happened . (let ((x-list (coerce x 'list))) ;; Return the optimum function value, the point that gives the ;; optimum, the value of the constraints, and the number of ;; function evaluations. For convenience. Only the point and ;; the number of evaluations is really needed. (values (apply fv x-list) x neval ierr))))) Interface . See fmin_cobyla.mac for documentation . (defun $%fmin_cobyla (f vars init-x options) (let* ((args (lispify-maxima-keyword-options (cdr options) '($ineq $eq $rhobeg $rhoend $iprint $maxfun)))) ;; Some rudimentary checks. (unless (= (length (cdr vars)) (length (cdr init-x))) (merror "Number of initial values (~M) does not match the number of variables ~M~%" (length (cdr init-x)) (length (cdr vars)))) (multiple-value-bind (fmin xopt neval ierr) (apply #'%cobyla vars init-x f args) (list '(mlist) (list* '(mlist) (mapcar #'(lambda (var val) `((mequal) ,var ,val)) (cdr vars) (coerce xopt 'list))) fmin neval ierr))))
null
https://raw.githubusercontent.com/sgbj/MaximaSharp/75067d7e045b9ed50883b5eb09803b4c8f391059/Test/bin/Debug/Maxima-5.30.0/share/maxima/5.30.0/share/cobyla/cobyla-interface.lisp
lisp
-*- Mode: lisp -*- Linear Approximations. Variable that will hold the function that calculates the function value and the constraints. constraint equations. But we want to be able to specify different do the real compuation. answer. If there are equality constraints, append them to the list of inequality constraints, and then append the negative of the equality constraints too. That is, if the equality constraint is h(X) = 0, then we add inequality constraints h(X) >= 0 and -h(X) >= 0. Compute the function and the constraints at the given xval. The function value is returned is returned, and the constraint values are stored in cval. Do we really need these checks? List the constraints that did not evaluate to a number to make it easier for the user to figure out which constraints were bad. This is the f2cl calling convention for and m are modified, so they must be returned. Should we put a check here if the number of function evaluations equals maxfun? When iprint is not 0, the output Return the optimum function value, the point that gives the optimum, the value of the constraints, and the number of function evaluations. For convenience. Only the point and the number of evaluations is really needed. Some rudimentary checks.
Simple Maxima interface to COBYLA , Constrained Optimization BY (in-package #-gcl #:maxima #+gcl "MAXIMA") (defvar *calcfc*) (in-package #-gcl #:cobyla #+gcl "COBYLA") COBYLA always calls CALCFC to compute the function value and the versions . So , COBYLA calls CALCFC , which then calls * CALCFC * to (defun calcfc (n m x f con) (declare (ignore f)) (funcall maxima::*calcfc* n m x con)) (in-package #-gcl #:maxima #+gcl "MAXIMA") The actual interface to COBYLA . Take the inputs from maxima , massage them into a suitable Lisp form , and call COBYLA to find the (defun %cobyla (vars init-x f &key (ineq (list '(mlist))) eq (rhobeg .5d0) (rhoend 1d-6) (iprint 0) (maxfun 1000)) (when (and eq (cdr eq)) (setf ineq (append ineq (cdr eq) (mapcar #'(lambda (e) (mul -1 e)) (cdr eq))))) (let* ((n (length (cdr vars))) (m (length (cdr ineq))) (x (make-array n :element-type 'double-float :initial-contents (mapcar #'(lambda (z) (let ((r ($float z))) (if (floatp r) r (merror "Does not evaluate to a float: ~M" z)))) (cdr init-x)))) Real work array for . (w (make-array (+ (* n (+ (* 3 n) (* 2 m) 11)) (+ (* 4 m) 6) 6) :element-type 'double-float)) Integer work array for . (iact (make-array (+ m 1) :element-type 'f2cl-lib::integer4)) (fv (coerce-float-fun f vars)) (cv (coerce-float-fun ineq vars)) (*calcfc* #'(lambda (nn mm xval cval) (declare (fixnum nn mm) (type (cl:array double-float (*)) xval cval)) (let* ((x-list (coerce xval 'list)) (f (apply fv x-list)) (c (apply cv x-list))) (unless (floatp f) (merror "The objective function did not evaluate to a number at ~M" (list* '(mlist) x-list))) (unless (every #'floatp (cdr c)) (let ((bad-cons (loop for cval in (cdr c) for k from 1 unless (floatp cval) collect k))) (mformat t "At the point ~M:~%" (list* '(mlist) x-list)) (merror (with-output-to-string (msg) (loop for index in bad-cons do (mformat msg "Constraint ~M: ~M did not evaluate to a number.~%" index (elt ineq index))))))) (replace cval c :start2 1) CALCFC . For some reason , thinks n (values nn mm nil f nil))))) (multiple-value-bind (null-0 null-1 null-2 null-3 null-4 null-5 neval null-6 null-7 ierr) (cobyla:cobyla n m x rhobeg rhoend iprint maxfun w iact 0) (declare (ignore null-0 null-1 null-2 null-3 null-4 null-5 null-6 null-7)) from COBYLA makes it clear that something bad happened . (let ((x-list (coerce x 'list))) (values (apply fv x-list) x neval ierr))))) Interface . See fmin_cobyla.mac for documentation . (defun $%fmin_cobyla (f vars init-x options) (let* ((args (lispify-maxima-keyword-options (cdr options) '($ineq $eq $rhobeg $rhoend $iprint $maxfun)))) (unless (= (length (cdr vars)) (length (cdr init-x))) (merror "Number of initial values (~M) does not match the number of variables ~M~%" (length (cdr init-x)) (length (cdr vars)))) (multiple-value-bind (fmin xopt neval ierr) (apply #'%cobyla vars init-x f args) (list '(mlist) (list* '(mlist) (mapcar #'(lambda (var val) `((mequal) ,var ,val)) (cdr vars) (coerce xopt 'list))) fmin neval ierr))))
9a75f52bdf8dbde1a63e8af03b1624ab858b551ac2b7817fe0c411fb7176ea09
hammerlab/coclobas
local_docker_job.ml
open Internal_pervasives module Specification = struct type t = { image: string; command: string list [@main]; volume_mounts: [ `Local of string * string ] list; memory: [ `GB of int | `MB of int ] option; cpus: float option; } [@@deriving yojson, show, make] end let job_section id = ["job"; id; "commands"] let command_must_succeed ~log ?additional_json ~id cmd = Hyper_shell.command_must_succeed ~log cmd ?additional_json ~section:(job_section id) let command_must_succeed_with_output ~log ?additional_json ~id cmd = Hyper_shell.command_must_succeed_with_output ~log cmd ?additional_json ~section:(job_section id) let exec c = List.map c ~f:Filename.quote |> String.concat ~sep:" " let start ~log ~id ~specification = let open Specification in let additional_json = [ "specification", Specification.to_yojson specification; ] in let mounts = specification.volume_mounts |> List.map ~f:(function `Local (one, two) -> ["-v"; sprintf "%s:%s" one two] ) |> List.concat in let cpus = Option.value_map ~default:[] specification.cpus ~f:(fun c -> [ sprintf " --cpus=%f " c ] - > This option is for ≥ 1.13 Cf . /#cpu Cf. /#cpu *) let period = 1000 in [sprintf "--cpu-period=%d" period; sprintf "--cpu-quota=%d" (c *. float period |> int_of_float)]) in let memory = Option.value_map ~default:[] specification.memory ~f:(function | `GB g -> [sprintf "--memory=%dg" g] | `MB m -> [sprintf "--memory=%dm" m]) in command_must_succeed ~additional_json ~log ~id (["docker"; "run"; "--name"; id; "-d"] @ mounts @ cpus @ memory @ [specification.image] @ specification.command |> exec) let describe ~storage ~log ~id = let save_path tag = Job_common.save_path ~tag id `Describe_output in Hyper_shell.Saved_command.run ~storage ~log ~path:(save_path "stats") ~section:(job_section id) ~keep_the:`Latest ~cmd:(["docker"; "stats"; "--no-stream"; id] |> exec) >>= fun stat_result -> Hyper_shell.Saved_command.run ~storage ~log ~path:(save_path "inspect") ~section:(job_section id) ~keep_the:`Latest ~cmd:(["docker"; "inspect"; id] |> exec) >>= fun inspect_result -> return ["Stats", `Saved_command stat_result; "Inspection", `Saved_command inspect_result] let get_logs ~storage ~log ~id = let save_path = Job_common.save_path id `Logs_output in Hyper_shell.Saved_command.run ~storage ~log ~path:save_path ~section:(job_section id) ~keep_the:`Latest ~cmd:(["docker"; "logs"; id] |> exec) >>= fun logres -> return (Job_common.Query_result.one_saved "Logs" logres) let kill ~log ~id = command_must_succeed ~log ~id (["docker"; "kill"; id] |> exec) let get_update ~log ~id = command_must_succeed_with_output ~log ~id (["docker"; "inspect"; id] |> exec) >>= fun (stdout, stderr) -> Deferred_result.wrap_deferred ~on_exn:(fun e -> `Job (`Docker_inspect_json_parsing (stdout, `Exn e))) (fun () -> Yojson.Safe.from_string stdout |> Lwt.return) >>= fun json -> let fail_parsing reason = fail (`Job (`Docker_inspect_json_parsing (stdout, `String reason))) in begin match json with | `List [`Assoc l] -> let status = ref None in let exit_code = ref None in List.iter l ~f:begin function | "State", `Assoc json_assoc -> List.iter json_assoc ~f:begin function | "Status", `String phase -> status := Some phase | "ExitCode", `Int i -> exit_code := Some i | _ -> () end | _ -> () end; begin match !status, !exit_code with | Some "running", _ -> return `Running | Some "exited", Some 0 -> return `Succeeded | Some "exited", Some other -> return `Failed | Some other, _ -> ksprintf fail_parsing "Unknown State/Status: %s" other | None, _ -> fail_parsing "Cannot find State/Status in 'inspect' JSON" end | _ -> fail_parsing "JSON is not an `Assoc _" end module Error = struct let to_string = function | `Docker_inspect_json_parsing (blob, `Exn e) -> sprintf "Parsing JSON output of kube-get-pod: %s, %s" (Printexc.to_string e) blob | `Docker_inspect_json_parsing (blob, `String e) -> sprintf "Parsing JSON output of kube-get-pod: %s, %s" e blob end
null
https://raw.githubusercontent.com/hammerlab/coclobas/5341ea53fdb5bcea0dfac3e4bd94213b34a48bb9/src/lib/local_docker_job.ml
ocaml
open Internal_pervasives module Specification = struct type t = { image: string; command: string list [@main]; volume_mounts: [ `Local of string * string ] list; memory: [ `GB of int | `MB of int ] option; cpus: float option; } [@@deriving yojson, show, make] end let job_section id = ["job"; id; "commands"] let command_must_succeed ~log ?additional_json ~id cmd = Hyper_shell.command_must_succeed ~log cmd ?additional_json ~section:(job_section id) let command_must_succeed_with_output ~log ?additional_json ~id cmd = Hyper_shell.command_must_succeed_with_output ~log cmd ?additional_json ~section:(job_section id) let exec c = List.map c ~f:Filename.quote |> String.concat ~sep:" " let start ~log ~id ~specification = let open Specification in let additional_json = [ "specification", Specification.to_yojson specification; ] in let mounts = specification.volume_mounts |> List.map ~f:(function `Local (one, two) -> ["-v"; sprintf "%s:%s" one two] ) |> List.concat in let cpus = Option.value_map ~default:[] specification.cpus ~f:(fun c -> [ sprintf " --cpus=%f " c ] - > This option is for ≥ 1.13 Cf . /#cpu Cf. /#cpu *) let period = 1000 in [sprintf "--cpu-period=%d" period; sprintf "--cpu-quota=%d" (c *. float period |> int_of_float)]) in let memory = Option.value_map ~default:[] specification.memory ~f:(function | `GB g -> [sprintf "--memory=%dg" g] | `MB m -> [sprintf "--memory=%dm" m]) in command_must_succeed ~additional_json ~log ~id (["docker"; "run"; "--name"; id; "-d"] @ mounts @ cpus @ memory @ [specification.image] @ specification.command |> exec) let describe ~storage ~log ~id = let save_path tag = Job_common.save_path ~tag id `Describe_output in Hyper_shell.Saved_command.run ~storage ~log ~path:(save_path "stats") ~section:(job_section id) ~keep_the:`Latest ~cmd:(["docker"; "stats"; "--no-stream"; id] |> exec) >>= fun stat_result -> Hyper_shell.Saved_command.run ~storage ~log ~path:(save_path "inspect") ~section:(job_section id) ~keep_the:`Latest ~cmd:(["docker"; "inspect"; id] |> exec) >>= fun inspect_result -> return ["Stats", `Saved_command stat_result; "Inspection", `Saved_command inspect_result] let get_logs ~storage ~log ~id = let save_path = Job_common.save_path id `Logs_output in Hyper_shell.Saved_command.run ~storage ~log ~path:save_path ~section:(job_section id) ~keep_the:`Latest ~cmd:(["docker"; "logs"; id] |> exec) >>= fun logres -> return (Job_common.Query_result.one_saved "Logs" logres) let kill ~log ~id = command_must_succeed ~log ~id (["docker"; "kill"; id] |> exec) let get_update ~log ~id = command_must_succeed_with_output ~log ~id (["docker"; "inspect"; id] |> exec) >>= fun (stdout, stderr) -> Deferred_result.wrap_deferred ~on_exn:(fun e -> `Job (`Docker_inspect_json_parsing (stdout, `Exn e))) (fun () -> Yojson.Safe.from_string stdout |> Lwt.return) >>= fun json -> let fail_parsing reason = fail (`Job (`Docker_inspect_json_parsing (stdout, `String reason))) in begin match json with | `List [`Assoc l] -> let status = ref None in let exit_code = ref None in List.iter l ~f:begin function | "State", `Assoc json_assoc -> List.iter json_assoc ~f:begin function | "Status", `String phase -> status := Some phase | "ExitCode", `Int i -> exit_code := Some i | _ -> () end | _ -> () end; begin match !status, !exit_code with | Some "running", _ -> return `Running | Some "exited", Some 0 -> return `Succeeded | Some "exited", Some other -> return `Failed | Some other, _ -> ksprintf fail_parsing "Unknown State/Status: %s" other | None, _ -> fail_parsing "Cannot find State/Status in 'inspect' JSON" end | _ -> fail_parsing "JSON is not an `Assoc _" end module Error = struct let to_string = function | `Docker_inspect_json_parsing (blob, `Exn e) -> sprintf "Parsing JSON output of kube-get-pod: %s, %s" (Printexc.to_string e) blob | `Docker_inspect_json_parsing (blob, `String e) -> sprintf "Parsing JSON output of kube-get-pod: %s, %s" e blob end
002cded405a31391083032a4d24215de64a47ad0edd222f5164e91ac2f1cb74d
monky-hs/monky
Memory.hs
Copyright 2015,2016 , This file is part of . is free software : you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation , either version 3 of the License , or ( at your option ) any later version . 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 Lesser General Public License for more details . You should have received a copy of the GNU Lesser General Public License along with . If not , see < / > . Copyright 2015,2016 Markus Ongyerth, Stephan Guenther This file is part of Monky. Monky is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Monky 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with Monky. If not, see </>. -} {-# LANGUAGE OverloadedStrings #-} | Module : . Memory Description : Allows to access information about they systems main memory Maintainer : ongy Stability : testing Portability : Linux Module : Monky.Memory Description : Allows to access information about they systems main memory Maintainer : ongy Stability : testing Portability : Linux -} module Monky.Memory ( MemoryHandle , getMemoryAvailable , getMemoryHandle , getMemoryTotal , getMemoryUsed , getMemoryFree , getMemoryStats ) where import Monky.Utility (fopen, readContent, File) import Data.Maybe (fromMaybe, listToMaybe) import Data.ByteString (ByteString) import qualified Data.ByteString.Char8 as BS -- |The memory handle used for all functions newtype MemoryHandle = MemoryH File path :: String path = "/proc/meminfo" getVal :: ByteString -> Int getVal = fst . fromMaybe (error "Failed to read as int in memory module") . BS.readInt . (!! 1) . BS.words findLine :: ByteString -> [ByteString] -> Maybe ByteString findLine x = listToMaybe . filter (x `BS.isPrefixOf`) {- |Return the memory available to userspace This is accurate (read from kernel) for current kernels. Old kernel (~3.13) estimates this. Old kernels may overestimate. -} getMemoryAvailable :: MemoryHandle -> IO Int getMemoryAvailable (MemoryH f) = do contents <- readContent f let line = findLine "MemAvailable" contents case line of Nothing -> do let buffs = fromMaybe err $ findLine "Buffers" contents cached = fromMaybe err $ findLine "Cached" contents free <- getMemoryFree (MemoryH f) return $ getVal buffs + getVal cached + free (Just x) -> return . getVal $ x where err = error "Could not find one of the fallback values for MemAvailable, please report this together with the content of /proc/meminfo" -- |Get the total amount of memory in the system getMemoryTotal :: MemoryHandle -> IO Int getMemoryTotal (MemoryH f) = do contents <- readContent f return . getVal . fromMaybe err . findLine "MemTotal" $ contents where err = error "Could not find MemTotal in /proc/meminfo. Please report this bug with the content of /proc/meminfo" -- |Get the amount of memory rported as free by the kernel getMemoryFree :: MemoryHandle -> IO Int getMemoryFree (MemoryH f) = do contents <- readContent f return . getVal . fromMaybe err . findLine "MemFree" $ contents where err = error "Could not find MemFree in /proc/meminfo. Please report this bug with the content of /proc/meminfo" -- |Get the amount of memory used by the kernel and processes getMemoryUsed :: MemoryHandle -> IO Int getMemoryUsed h = do (_, _, _, used) <- getMemoryStats h return used |Get memory statistics in one got ( with only one read ) ( total , avail , free , used ) getMemoryStats :: MemoryHandle -> IO (Int, Int, Int, Int) getMemoryStats (MemoryH f) = do contents <- readContent f let avail = getVal . fromMaybe "a 0" . findLine "MemAvailable" $ contents total = getVal . fromMaybe "a 0" . findLine "MemTotal" $ contents free = getVal . fromMaybe "a 0" . findLine "MemFree" $ contents used = total - avail return (total, avail, free, used) -- |Get a memory handle getMemoryHandle :: IO MemoryHandle getMemoryHandle = do file <- fopen path return $MemoryH file
null
https://raw.githubusercontent.com/monky-hs/monky/5430352258622bdb0a54f6a197090cc4ef03102f/Monky/Memory.hs
haskell
# LANGUAGE OverloadedStrings # |The memory handle used for all functions |Return the memory available to userspace This is accurate (read from kernel) for current kernels. Old kernel (~3.13) estimates this. Old kernels may overestimate. |Get the total amount of memory in the system |Get the amount of memory rported as free by the kernel |Get the amount of memory used by the kernel and processes |Get a memory handle
Copyright 2015,2016 , This file is part of . is free software : you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation , either version 3 of the License , or ( at your option ) any later version . 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 Lesser General Public License for more details . You should have received a copy of the GNU Lesser General Public License along with . If not , see < / > . Copyright 2015,2016 Markus Ongyerth, Stephan Guenther This file is part of Monky. Monky is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Monky 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with Monky. If not, see </>. -} | Module : . Memory Description : Allows to access information about they systems main memory Maintainer : ongy Stability : testing Portability : Linux Module : Monky.Memory Description : Allows to access information about they systems main memory Maintainer : ongy Stability : testing Portability : Linux -} module Monky.Memory ( MemoryHandle , getMemoryAvailable , getMemoryHandle , getMemoryTotal , getMemoryUsed , getMemoryFree , getMemoryStats ) where import Monky.Utility (fopen, readContent, File) import Data.Maybe (fromMaybe, listToMaybe) import Data.ByteString (ByteString) import qualified Data.ByteString.Char8 as BS newtype MemoryHandle = MemoryH File path :: String path = "/proc/meminfo" getVal :: ByteString -> Int getVal = fst . fromMaybe (error "Failed to read as int in memory module") . BS.readInt . (!! 1) . BS.words findLine :: ByteString -> [ByteString] -> Maybe ByteString findLine x = listToMaybe . filter (x `BS.isPrefixOf`) getMemoryAvailable :: MemoryHandle -> IO Int getMemoryAvailable (MemoryH f) = do contents <- readContent f let line = findLine "MemAvailable" contents case line of Nothing -> do let buffs = fromMaybe err $ findLine "Buffers" contents cached = fromMaybe err $ findLine "Cached" contents free <- getMemoryFree (MemoryH f) return $ getVal buffs + getVal cached + free (Just x) -> return . getVal $ x where err = error "Could not find one of the fallback values for MemAvailable, please report this together with the content of /proc/meminfo" getMemoryTotal :: MemoryHandle -> IO Int getMemoryTotal (MemoryH f) = do contents <- readContent f return . getVal . fromMaybe err . findLine "MemTotal" $ contents where err = error "Could not find MemTotal in /proc/meminfo. Please report this bug with the content of /proc/meminfo" getMemoryFree :: MemoryHandle -> IO Int getMemoryFree (MemoryH f) = do contents <- readContent f return . getVal . fromMaybe err . findLine "MemFree" $ contents where err = error "Could not find MemFree in /proc/meminfo. Please report this bug with the content of /proc/meminfo" getMemoryUsed :: MemoryHandle -> IO Int getMemoryUsed h = do (_, _, _, used) <- getMemoryStats h return used |Get memory statistics in one got ( with only one read ) ( total , avail , free , used ) getMemoryStats :: MemoryHandle -> IO (Int, Int, Int, Int) getMemoryStats (MemoryH f) = do contents <- readContent f let avail = getVal . fromMaybe "a 0" . findLine "MemAvailable" $ contents total = getVal . fromMaybe "a 0" . findLine "MemTotal" $ contents free = getVal . fromMaybe "a 0" . findLine "MemFree" $ contents used = total - avail return (total, avail, free, used) getMemoryHandle :: IO MemoryHandle getMemoryHandle = do file <- fopen path return $MemoryH file
803a2c38ffc2f8f92edb2403777b7ab520a2d44cc74d223e5262d86051a5036e
swarmpit/swarmpit
subscription.clj
(ns swarmpit.event.rules.subscription (:refer-clojure :exclude [list]) (:require [swarmpit.api :as api] [swarmpit.docker.utils :as du] [swarmpit.stats :as stats] [swarmpit.event.rules.predicate :refer :all] [clojure.tools.logging :as log])) (defn- service-id [service-event-message] (or (get-in service-event-message [:Actor :Attributes :com.docker.swarm.service.id]) (get-in service-event-message [:Actor :ID]))) (defn- service-name [service-event-message] (or (get-in service-event-message [:Actor :Attributes :com.docker.swarm.service.name]) (get-in service-event-message [:Actor :Attributes :name]))) (defn- node-id [node-event-message] (or (get-in node-event-message [:Actor :Attributes :com.docker.swarm.node.id]) (get-in node-event-message [:Actor :ID]))) ;; Subscribed Data (defn dashboard-data [user] (let [stats (when (stats/ready?) (stats/cluster)) nodes-ts (when (stats/influx-configured?) (stats/hosts-timeseries-memo)) services-ts-cpu (when (stats/influx-configured?) (stats/services-cpu-timeseries-memo)) services-ts-memory (when (stats/influx-configured?) (stats/services-memory-timeseries-memo)) dashboard-user (api/user-by-username user)] {:stats stats :services (api/services) :services-dashboard (:service-dashboard dashboard-user) :services-ts-cpu services-ts-cpu :services-ts-memory services-ts-memory :nodes (api/nodes) :nodes-dashboard (:node-dashboard dashboard-user) :nodes-ts nodes-ts})) (defn- service-info-data [service-event-message] (let [service-id (or (service-id service-event-message) (service-name service-event-message)) service (api/service service-id) tasks (api/service-tasks service-id) networks (api/service-networks service-id) stats (when (stats/ready?) (stats/cluster))] {:service service :tasks tasks :networks networks :stats stats})) (defn- node-info-data [node-event-message] (let [node-id (node-id node-event-message) node (api/node node-id) tasks (api/node-tasks node-id)] {:node node :tasks tasks})) (defn- stack-info-data [service-event-message] (let [service-name (service-name service-event-message) stack-name (du/hypothetical-stack service-name) stack-tasks (api/stack-tasks stack-name) stats (when (stats/ready?) (stats/cluster))] (merge (api/stack stack-name) {:tasks stack-tasks :stats stats}))) ;; Rules (defprotocol Rule (match? [this type message]) (subscription [this message]) (subscribed-data [this message user])) (def refresh-dashboard (reify Rule (match? [_ type message] (and (event? type) (or (service-event? message) (node-event? message)))) (subscription [_ message] {:handler :index :params {}}) (subscribed-data [_ message user] (dashboard-data user)))) (def refresh-service-list (reify Rule (match? [_ type message] (and (event? type) (or (service-event? message) (service-task-event? message)))) (subscription [_ message] {:handler :service-list :params {}}) (subscribed-data [_ message user] (api/services)))) (def refresh-service-info-by-name (reify Rule (match? [_ type message] (and (event? type) (or (service-event? message) (service-task-event? message)))) (subscription [_ message] {:handler :service-info :params {:id (service-name message)}}) (subscribed-data [_ message user] (service-info-data message)))) (def refresh-service-info-by-id (reify Rule (match? [_ type message] (and (event? type) (or (service-event? message) (service-task-event? message)))) (subscription [_ message] {:handler :service-info :params {:id (service-id message)}}) (subscribed-data [_ message user] (service-info-data message)))) (def refresh-task-list (reify Rule (match? [_ type message] (and (event? type) (service-task-event? message))) (subscription [_ message] {:handler :task-list :params {}}) (subscribed-data [_ message user] (api/tasks-memo)))) (def refresh-task-info (reify Rule (match? [_ type message] (and (event? type) (service-task-event? message))) (subscription [_ message] {:handler :task-info :params {:serviceName (service-name message)}}) (subscribed-data [_ message user] (api/service-tasks (service-name message))))) (def refresh-node-info (reify Rule (match? [_ type message] (and (event? type) (node-event? message))) (subscription [_ message] {:handler :node-info :params {:id (node-id message)}}) (subscribed-data [_ message user] (node-info-data message)))) (def refresh-node-list (reify Rule (match? [_ type message] (and (event? type) (node-event? message))) (subscription [_ message] {:handler :node-list :params {}}) (subscribed-data [_ message user] (api/nodes)))) (def refresh-stack-list (reify Rule (match? [_ type message] (and (event? type) (service-event? message))) (subscription [_ message] {:handler :stack-list :params {}}) (subscribed-data [_ message user] (api/stacks)))) (def refresh-stack-info (reify Rule (match? [_ type message] (and (event? type) (or (service-event? message) (service-task-event? message)))) (subscription [_ message] (let [service-name (service-name message) stack-name (du/hypothetical-stack service-name)] {:handler :stack-info :params {:name stack-name}})) (subscribed-data [_ message user] (stack-info-data message)))) (def list [refresh-dashboard refresh-service-list refresh-service-info-by-name refresh-service-info-by-id refresh-task-list refresh-task-info refresh-node-list refresh-node-info refresh-stack-list refresh-stack-info])
null
https://raw.githubusercontent.com/swarmpit/swarmpit/38ffbe08e717d8620bf433c99f2e85a9e5984c32/src/clj/swarmpit/event/rules/subscription.clj
clojure
Subscribed Data Rules
(ns swarmpit.event.rules.subscription (:refer-clojure :exclude [list]) (:require [swarmpit.api :as api] [swarmpit.docker.utils :as du] [swarmpit.stats :as stats] [swarmpit.event.rules.predicate :refer :all] [clojure.tools.logging :as log])) (defn- service-id [service-event-message] (or (get-in service-event-message [:Actor :Attributes :com.docker.swarm.service.id]) (get-in service-event-message [:Actor :ID]))) (defn- service-name [service-event-message] (or (get-in service-event-message [:Actor :Attributes :com.docker.swarm.service.name]) (get-in service-event-message [:Actor :Attributes :name]))) (defn- node-id [node-event-message] (or (get-in node-event-message [:Actor :Attributes :com.docker.swarm.node.id]) (get-in node-event-message [:Actor :ID]))) (defn dashboard-data [user] (let [stats (when (stats/ready?) (stats/cluster)) nodes-ts (when (stats/influx-configured?) (stats/hosts-timeseries-memo)) services-ts-cpu (when (stats/influx-configured?) (stats/services-cpu-timeseries-memo)) services-ts-memory (when (stats/influx-configured?) (stats/services-memory-timeseries-memo)) dashboard-user (api/user-by-username user)] {:stats stats :services (api/services) :services-dashboard (:service-dashboard dashboard-user) :services-ts-cpu services-ts-cpu :services-ts-memory services-ts-memory :nodes (api/nodes) :nodes-dashboard (:node-dashboard dashboard-user) :nodes-ts nodes-ts})) (defn- service-info-data [service-event-message] (let [service-id (or (service-id service-event-message) (service-name service-event-message)) service (api/service service-id) tasks (api/service-tasks service-id) networks (api/service-networks service-id) stats (when (stats/ready?) (stats/cluster))] {:service service :tasks tasks :networks networks :stats stats})) (defn- node-info-data [node-event-message] (let [node-id (node-id node-event-message) node (api/node node-id) tasks (api/node-tasks node-id)] {:node node :tasks tasks})) (defn- stack-info-data [service-event-message] (let [service-name (service-name service-event-message) stack-name (du/hypothetical-stack service-name) stack-tasks (api/stack-tasks stack-name) stats (when (stats/ready?) (stats/cluster))] (merge (api/stack stack-name) {:tasks stack-tasks :stats stats}))) (defprotocol Rule (match? [this type message]) (subscription [this message]) (subscribed-data [this message user])) (def refresh-dashboard (reify Rule (match? [_ type message] (and (event? type) (or (service-event? message) (node-event? message)))) (subscription [_ message] {:handler :index :params {}}) (subscribed-data [_ message user] (dashboard-data user)))) (def refresh-service-list (reify Rule (match? [_ type message] (and (event? type) (or (service-event? message) (service-task-event? message)))) (subscription [_ message] {:handler :service-list :params {}}) (subscribed-data [_ message user] (api/services)))) (def refresh-service-info-by-name (reify Rule (match? [_ type message] (and (event? type) (or (service-event? message) (service-task-event? message)))) (subscription [_ message] {:handler :service-info :params {:id (service-name message)}}) (subscribed-data [_ message user] (service-info-data message)))) (def refresh-service-info-by-id (reify Rule (match? [_ type message] (and (event? type) (or (service-event? message) (service-task-event? message)))) (subscription [_ message] {:handler :service-info :params {:id (service-id message)}}) (subscribed-data [_ message user] (service-info-data message)))) (def refresh-task-list (reify Rule (match? [_ type message] (and (event? type) (service-task-event? message))) (subscription [_ message] {:handler :task-list :params {}}) (subscribed-data [_ message user] (api/tasks-memo)))) (def refresh-task-info (reify Rule (match? [_ type message] (and (event? type) (service-task-event? message))) (subscription [_ message] {:handler :task-info :params {:serviceName (service-name message)}}) (subscribed-data [_ message user] (api/service-tasks (service-name message))))) (def refresh-node-info (reify Rule (match? [_ type message] (and (event? type) (node-event? message))) (subscription [_ message] {:handler :node-info :params {:id (node-id message)}}) (subscribed-data [_ message user] (node-info-data message)))) (def refresh-node-list (reify Rule (match? [_ type message] (and (event? type) (node-event? message))) (subscription [_ message] {:handler :node-list :params {}}) (subscribed-data [_ message user] (api/nodes)))) (def refresh-stack-list (reify Rule (match? [_ type message] (and (event? type) (service-event? message))) (subscription [_ message] {:handler :stack-list :params {}}) (subscribed-data [_ message user] (api/stacks)))) (def refresh-stack-info (reify Rule (match? [_ type message] (and (event? type) (or (service-event? message) (service-task-event? message)))) (subscription [_ message] (let [service-name (service-name message) stack-name (du/hypothetical-stack service-name)] {:handler :stack-info :params {:name stack-name}})) (subscribed-data [_ message user] (stack-info-data message)))) (def list [refresh-dashboard refresh-service-list refresh-service-info-by-name refresh-service-info-by-id refresh-task-list refresh-task-info refresh-node-list refresh-node-info refresh-stack-list refresh-stack-info])
f051ea1c384080c2202a1d4df43e3d458c04de08c05a16ee147bba04b84f11bc
coccinelle/coccinelle
bool.mli
type t = bool = | false | true val not : bool -> bool external (&&) : bool -> bool -> bool = "%sequand" external (||) : bool -> bool -> bool = "%sequor" val equal : bool -> bool -> bool val compare : bool -> bool -> int val to_int : bool -> int val to_float : bool -> float val to_string : bool -> string
null
https://raw.githubusercontent.com/coccinelle/coccinelle/5448bb2bd03491ffec356bf7bd6ddcdbf4d36bc9/bundles/stdcompat/stdcompat-current/interfaces/4.14/bool.mli
ocaml
type t = bool = | false | true val not : bool -> bool external (&&) : bool -> bool -> bool = "%sequand" external (||) : bool -> bool -> bool = "%sequor" val equal : bool -> bool -> bool val compare : bool -> bool -> int val to_int : bool -> int val to_float : bool -> float val to_string : bool -> string
4cd6cd0dbde1f0ea05ed28e22cf7034a11a4aa35f2e89571578a293598a75c3b
aryx/lfs
inotify.ml
* Copyright ( C ) 2006 - 2008 < > * * This program is free software ; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation ; version 2.1 only . with the special * exception on linking described in file LICENSE . * * 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 Lesser General Public License for more details . * * binding * Copyright (C) 2006-2008 Vincent Hanquez <> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation; version 2.1 only. with the special * exception on linking described in file LICENSE. * * 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 Lesser General Public License for more details. * * Inotify OCaml binding *) type select_event = | S_Access | S_Attrib | S_Close_write | S_Close_nowrite | S_Create | S_Delete | S_Delete_self | S_Modify | S_Move_self | S_Moved_from | S_Moved_to | S_Open | S_Dont_follow | S_Mask_add | S_Oneshot | S_Onlydir (* convenience *) | S_Move | S_Close | S_All type type_event = | Access | Attrib | Close_write | Close_nowrite | Create | Delete | Delete_self | Modify | Move_self | Moved_from | Moved_to | Open | Ignored | Isdir | Q_overflow | Unmount let string_of_event = function | Access -> "ACCESS" | Attrib -> "ATTRIB" | Close_write -> "CLOSE_WRITE" | Close_nowrite -> "CLOSE_NOWRITE" | Create -> "CREATE" | Delete -> "DELETE" | Delete_self -> "DELETE_SELF" | Modify -> "MODIFY" | Move_self -> "MOVE_SELF" | Moved_from -> "MOVED_FROM" | Moved_to -> "MOVED_TO" | Open -> "OPEN" | Ignored -> "IGNORED" | Isdir -> "ISDIR" | Q_overflow -> "Q_OVERFLOW" | Unmount -> "UNMOUNT" let int_of_wd wd = wd type wd = int type event = wd * type_event list * int32 * string option external init : unit -> Unix.file_descr = "stub_inotify_init" external add_watch : Unix.file_descr -> string -> select_event list -> wd = "stub_inotify_add_watch" external rm_watch : Unix.file_descr -> wd -> unit = "stub_inotify_rm_watch" external convert : string -> (wd * type_event list * int32 * int) = "stub_inotify_convert" external struct_size : unit -> int = "stub_inotify_struct_size" external to_read : Unix.file_descr -> int = "stub_inotify_ioctl_fionread" let read fd = let ss = struct_size () in let toread = to_read fd in let ret = ref [] in let buf = String.make toread '\000' in let toread = Unix.read fd buf 0 toread in let i = ref 0 in while !i < toread do let wd, l, cookie, len = convert (String.sub buf !i ss) in let s = if len > 0 then Some (String.sub buf (!i + ss) len) else None in ret := (wd, l, cookie, s) :: !ret; i := !i + (ss + len); done; List.rev !ret
null
https://raw.githubusercontent.com/aryx/lfs/b931530c7132b77dfaf3c99d452dc044fce37589/ocamlinotify/inotify.ml
ocaml
convenience
* Copyright ( C ) 2006 - 2008 < > * * This program is free software ; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation ; version 2.1 only . with the special * exception on linking described in file LICENSE . * * 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 Lesser General Public License for more details . * * binding * Copyright (C) 2006-2008 Vincent Hanquez <> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation; version 2.1 only. with the special * exception on linking described in file LICENSE. * * 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 Lesser General Public License for more details. * * Inotify OCaml binding *) type select_event = | S_Access | S_Attrib | S_Close_write | S_Close_nowrite | S_Create | S_Delete | S_Delete_self | S_Modify | S_Move_self | S_Moved_from | S_Moved_to | S_Open | S_Dont_follow | S_Mask_add | S_Oneshot | S_Onlydir | S_Move | S_Close | S_All type type_event = | Access | Attrib | Close_write | Close_nowrite | Create | Delete | Delete_self | Modify | Move_self | Moved_from | Moved_to | Open | Ignored | Isdir | Q_overflow | Unmount let string_of_event = function | Access -> "ACCESS" | Attrib -> "ATTRIB" | Close_write -> "CLOSE_WRITE" | Close_nowrite -> "CLOSE_NOWRITE" | Create -> "CREATE" | Delete -> "DELETE" | Delete_self -> "DELETE_SELF" | Modify -> "MODIFY" | Move_self -> "MOVE_SELF" | Moved_from -> "MOVED_FROM" | Moved_to -> "MOVED_TO" | Open -> "OPEN" | Ignored -> "IGNORED" | Isdir -> "ISDIR" | Q_overflow -> "Q_OVERFLOW" | Unmount -> "UNMOUNT" let int_of_wd wd = wd type wd = int type event = wd * type_event list * int32 * string option external init : unit -> Unix.file_descr = "stub_inotify_init" external add_watch : Unix.file_descr -> string -> select_event list -> wd = "stub_inotify_add_watch" external rm_watch : Unix.file_descr -> wd -> unit = "stub_inotify_rm_watch" external convert : string -> (wd * type_event list * int32 * int) = "stub_inotify_convert" external struct_size : unit -> int = "stub_inotify_struct_size" external to_read : Unix.file_descr -> int = "stub_inotify_ioctl_fionread" let read fd = let ss = struct_size () in let toread = to_read fd in let ret = ref [] in let buf = String.make toread '\000' in let toread = Unix.read fd buf 0 toread in let i = ref 0 in while !i < toread do let wd, l, cookie, len = convert (String.sub buf !i ss) in let s = if len > 0 then Some (String.sub buf (!i + ss) len) else None in ret := (wd, l, cookie, s) :: !ret; i := !i + (ss + len); done; List.rev !ret
1a56d9bdc40ba7c2b21516b2f14a0debf858bc4afea64f6fb93c52b2b940cdbb
hstreamdb/hstream
server.hs
# LANGUAGE CPP # {-# LANGUAGE DataKinds #-} # LANGUAGE GADTs # # LANGUAGE LambdaCase # {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE PatternSynonyms #-} {-# LANGUAGE QuasiQuotes #-} {-# LANGUAGE RecordWildCards #-} # LANGUAGE ScopedTypeVariables # # LANGUAGE TypeApplications # import Control.Concurrent (MVar, forkIO, newMVar, readMVar, swapMVar) import qualified Control.Concurrent.Async as Async import Control.Concurrent.STM (TVar, atomically, retry, writeTVar) import Control.Exception (handle) import Control.Monad (forM_, join, void, when) import Data.ByteString (ByteString) import qualified Data.ByteString.Short as BS import qualified Data.Map as Map import qualified Data.Text as T import Data.Text.Encoding (encodeUtf8) import Data.Word (Word16) import qualified HsGrpc.Server as HsGrpc import qualified Network.GRPC.HighLevel as GRPC import qualified Network.GRPC.HighLevel.Client as GRPC import qualified Network.GRPC.HighLevel.Generated as GRPC import Network.HTTP.Client (defaultManagerSettings, newManager) import System.IO (hPutStrLn, stderr) import Text.RawString.QQ (r) import Z.Data.CBytes (CBytes) import ZooKeeper (withResource, zookeeperResInit) import ZooKeeper.Types (ZHandle, ZooEvent, ZooState, pattern ZooConnectedState, pattern ZooConnectingState, pattern ZooSessionEvent) import HStream.Common.ConsistentHashing (HashRing, constructServerMap) import HStream.Exception import HStream.Gossip (GossipContext (..), defaultGossipOpts, initGossipContext, startGossip, waitGossipBoot) import HStream.Gossip.Types (Epoch, InitType (Gossip)) import HStream.Gossip.Utils (getMemberListWithEpochSTM) import qualified HStream.Logger as Log import HStream.MetaStore.Types (MetaHandle (..), MetaStore (..), RHandle (..)) import HStream.Server.Config (AdvertisedListeners, ListenersSecurityProtocolMap, MetaStoreAddr (..), SecurityProtocolMap, ServerOpts (..), TlsConfig, advertisedListenersToPB, getConfig) import HStream.Server.Handler (handlers) import qualified HStream.Server.HsGrpcHandler as HsGrpc import HStream.Server.HStreamApi (NodeState (..), hstreamApiServer) import qualified HStream.Server.HStreamInternal as I import HStream.Server.Initialization (initializeServer, initializeTlsConfig, readTlsPemFile) import HStream.Server.MetaData (TaskAllocation, clusterStartTimeId, initializeAncestors, initializeFile, initializeTables) import HStream.Server.Types (ServerContext (..), ServerState) import qualified HStream.Store.Logger as Log import qualified HStream.ThirdParty.Protobuf as Proto import HStream.Utils (getProtoTimestamp, pattern EnumPB, setupSigsegvHandler) main :: IO () main = getConfig >>= app app :: ServerOpts -> IO () app config@ServerOpts{..} = do setupSigsegvHandler Log.setLogLevel _serverLogLevel _serverLogWithColor Log.setLogDeviceDbgLevel' _ldLogLevel case _metaStore of ZkAddr addr -> do let zkRes = zookeeperResInit addr Nothing 5000 Nothing 0 withResource zkRes $ \zk -> initializeAncestors zk >> action (ZkHandle zk) RqAddr addr -> do m <- newManager defaultManagerSettings let rq = RHandle m addr initializeTables rq action $ RLHandle rq FileAddr addr -> do initializeFile addr action $ FileHandle addr where action h = do let serverNode = I.ServerNode { serverNodeId = _serverID , serverNodePort = fromIntegral _serverPort , serverNodeAdvertisedAddress = encodeUtf8 . T.pack $ _serverAddress , serverNodeGossipPort = fromIntegral _serverInternalPort , serverNodeGossipAddress = encodeUtf8 . T.pack $ _serverGossipAddress , serverNodeAdvertisedListeners = advertisedListenersToPB _serverAdvertisedListeners } gossipContext <- initGossipContext defaultGossipOpts mempty serverNode _seedNodes serverContext <- initializeServer config gossipContext h void . forkIO $ updateHashRing gossipContext (loadBalanceHashRing serverContext) Async.withAsync (serve _serverHost _serverPort _securityProtocolMap serverContext _serverAdvertisedListeners _listenersSecurityProtocolMap) $ \a -> do a1 <- startGossip _serverHost gossipContext Async.link2Only (const True) a a1 waitGossipBoot gossipContext Async.wait a serve :: ByteString -> Word16 -> SecurityProtocolMap -> ServerContext -> AdvertisedListeners -> ListenersSecurityProtocolMap -> IO () serve host port securityMap sc@ServerContext{..} listeners listenerSecurityMap = do Log.i "************************" hPutStrLn stderr $ [r| _ _ __ _____ ___ ___ __ __ __ | || |/' _/_ _| _ \ __|/ \| V | | >< |`._`. | | | v / _|| /\ | \_/ | |_||_||___/ |_| |_|_\___|_||_|_| |_| |] Log.i "************************" let serverOnStarted = do Log.info $ "Server is started on port " <> Log.buildInt port <> ", waiting for cluster to get ready" void $ forkIO $ do void (readMVar (clusterReady gossipContext)) >> Log.i "Cluster is ready!" readMVar (clusterInited gossipContext) >>= \case Gossip -> return () _ -> do getProtoTimestamp >>= \x -> upsertMeta @Proto.Timestamp clusterStartTimeId x metaHandle handle (\(_ :: RQLiteRowNotFound) -> return ()) $ deleteAllMeta @TaskAllocation metaHandle #ifdef HStreamUseGrpcHaskell let sslOpts = initializeTlsConfig <$> join (Map.lookup "tls" securityMap) #else sslOpts <- mapM readTlsPemFile $ join (Map.lookup "tls" securityMap) #endif let grpcOpts = #ifdef HStreamUseGrpcHaskell GRPC.defaultServiceOptions { GRPC.serverHost = GRPC.Host host , GRPC.serverPort = GRPC.Port $ fromIntegral port , GRPC.serverOnStarted = Just serverOnStarted , GRPC.sslConfig = sslOpts } #else HsGrpc.ServerOptions { HsGrpc.serverHost = BS.toShort host , HsGrpc.serverPort = fromIntegral port , HsGrpc.serverParallelism = 0 , HsGrpc.serverSslOptions = sslOpts , HsGrpc.serverOnStarted = Just serverOnStarted } #endif forM_ (Map.toList listeners) $ \(key, vs) -> forM_ vs $ \I.Listener{..} -> do Log.debug $ "Starting advertised listener, " <> "key: " <> Log.buildText key <> ", " <> "address: " <> Log.buildText listenerAddress <> ", " <> "port: " <> Log.buildInt listenerPort forkIO $ do let listenerOnStarted = Log.info $ "Extra listener is started on port " <> Log.buildInt listenerPort let sc' = sc{scAdvertisedListenersKey = Just key} #ifdef HStreamUseGrpcHaskell let newSslOpts = initializeTlsConfig <$> join ((`Map.lookup` securityMap) =<< Map.lookup key listenerSecurityMap ) let grpcOpts' = grpcOpts { GRPC.serverPort = GRPC.Port $ fromIntegral listenerPort , GRPC.serverOnStarted = Just listenerOnStarted , GRPC.sslConfig = newSslOpts } api <- handlers sc' hstreamApiServer api grpcOpts' #else newSslOpts <- mapM readTlsPemFile $ join ((`Map.lookup` securityMap) =<< Map.lookup key listenerSecurityMap ) let grpcOpts' = grpcOpts { HsGrpc.serverPort = fromIntegral listenerPort , HsGrpc.serverOnStarted = Just listenerOnStarted , HsGrpc.serverSslOptions = newSslOpts } HsGrpc.runServer grpcOpts' (HsGrpc.handlers sc') #endif #ifdef HStreamUseGrpcHaskell Log.info "Starting server with grpc-haskell..." api <- handlers sc hstreamApiServer api grpcOpts #else Log.info "Starting server with hs-grpc-server..." HsGrpc.runServer grpcOpts (HsGrpc.handlers sc) #endif -------------------------------------------------------------------------------- -- However, reconstruct hashRing every time can be expensive -- when we have a large number of nodes in the cluster. updateHashRing :: GossipContext -> TVar (Epoch, HashRing) -> IO () updateHashRing gc hashRing = loop 0 where loop epoch = loop =<< atomically ( do (epoch', list) <- getMemberListWithEpochSTM gc when (epoch == epoch') retry writeTVar hashRing (epoch', constructServerMap list) return epoch' )
null
https://raw.githubusercontent.com/hstreamdb/hstream/bf605e37f4bc847678cd9753a5dc77884acb97d4/hstream/app/server.hs
haskell
# LANGUAGE DataKinds # # LANGUAGE OverloadedStrings # # LANGUAGE PatternSynonyms # # LANGUAGE QuasiQuotes # # LANGUAGE RecordWildCards # ------------------------------------------------------------------------------ However, reconstruct hashRing every time can be expensive when we have a large number of nodes in the cluster.
# LANGUAGE CPP # # LANGUAGE GADTs # # LANGUAGE LambdaCase # # LANGUAGE ScopedTypeVariables # # LANGUAGE TypeApplications # import Control.Concurrent (MVar, forkIO, newMVar, readMVar, swapMVar) import qualified Control.Concurrent.Async as Async import Control.Concurrent.STM (TVar, atomically, retry, writeTVar) import Control.Exception (handle) import Control.Monad (forM_, join, void, when) import Data.ByteString (ByteString) import qualified Data.ByteString.Short as BS import qualified Data.Map as Map import qualified Data.Text as T import Data.Text.Encoding (encodeUtf8) import Data.Word (Word16) import qualified HsGrpc.Server as HsGrpc import qualified Network.GRPC.HighLevel as GRPC import qualified Network.GRPC.HighLevel.Client as GRPC import qualified Network.GRPC.HighLevel.Generated as GRPC import Network.HTTP.Client (defaultManagerSettings, newManager) import System.IO (hPutStrLn, stderr) import Text.RawString.QQ (r) import Z.Data.CBytes (CBytes) import ZooKeeper (withResource, zookeeperResInit) import ZooKeeper.Types (ZHandle, ZooEvent, ZooState, pattern ZooConnectedState, pattern ZooConnectingState, pattern ZooSessionEvent) import HStream.Common.ConsistentHashing (HashRing, constructServerMap) import HStream.Exception import HStream.Gossip (GossipContext (..), defaultGossipOpts, initGossipContext, startGossip, waitGossipBoot) import HStream.Gossip.Types (Epoch, InitType (Gossip)) import HStream.Gossip.Utils (getMemberListWithEpochSTM) import qualified HStream.Logger as Log import HStream.MetaStore.Types (MetaHandle (..), MetaStore (..), RHandle (..)) import HStream.Server.Config (AdvertisedListeners, ListenersSecurityProtocolMap, MetaStoreAddr (..), SecurityProtocolMap, ServerOpts (..), TlsConfig, advertisedListenersToPB, getConfig) import HStream.Server.Handler (handlers) import qualified HStream.Server.HsGrpcHandler as HsGrpc import HStream.Server.HStreamApi (NodeState (..), hstreamApiServer) import qualified HStream.Server.HStreamInternal as I import HStream.Server.Initialization (initializeServer, initializeTlsConfig, readTlsPemFile) import HStream.Server.MetaData (TaskAllocation, clusterStartTimeId, initializeAncestors, initializeFile, initializeTables) import HStream.Server.Types (ServerContext (..), ServerState) import qualified HStream.Store.Logger as Log import qualified HStream.ThirdParty.Protobuf as Proto import HStream.Utils (getProtoTimestamp, pattern EnumPB, setupSigsegvHandler) main :: IO () main = getConfig >>= app app :: ServerOpts -> IO () app config@ServerOpts{..} = do setupSigsegvHandler Log.setLogLevel _serverLogLevel _serverLogWithColor Log.setLogDeviceDbgLevel' _ldLogLevel case _metaStore of ZkAddr addr -> do let zkRes = zookeeperResInit addr Nothing 5000 Nothing 0 withResource zkRes $ \zk -> initializeAncestors zk >> action (ZkHandle zk) RqAddr addr -> do m <- newManager defaultManagerSettings let rq = RHandle m addr initializeTables rq action $ RLHandle rq FileAddr addr -> do initializeFile addr action $ FileHandle addr where action h = do let serverNode = I.ServerNode { serverNodeId = _serverID , serverNodePort = fromIntegral _serverPort , serverNodeAdvertisedAddress = encodeUtf8 . T.pack $ _serverAddress , serverNodeGossipPort = fromIntegral _serverInternalPort , serverNodeGossipAddress = encodeUtf8 . T.pack $ _serverGossipAddress , serverNodeAdvertisedListeners = advertisedListenersToPB _serverAdvertisedListeners } gossipContext <- initGossipContext defaultGossipOpts mempty serverNode _seedNodes serverContext <- initializeServer config gossipContext h void . forkIO $ updateHashRing gossipContext (loadBalanceHashRing serverContext) Async.withAsync (serve _serverHost _serverPort _securityProtocolMap serverContext _serverAdvertisedListeners _listenersSecurityProtocolMap) $ \a -> do a1 <- startGossip _serverHost gossipContext Async.link2Only (const True) a a1 waitGossipBoot gossipContext Async.wait a serve :: ByteString -> Word16 -> SecurityProtocolMap -> ServerContext -> AdvertisedListeners -> ListenersSecurityProtocolMap -> IO () serve host port securityMap sc@ServerContext{..} listeners listenerSecurityMap = do Log.i "************************" hPutStrLn stderr $ [r| _ _ __ _____ ___ ___ __ __ __ | || |/' _/_ _| _ \ __|/ \| V | | >< |`._`. | | | v / _|| /\ | \_/ | |_||_||___/ |_| |_|_\___|_||_|_| |_| |] Log.i "************************" let serverOnStarted = do Log.info $ "Server is started on port " <> Log.buildInt port <> ", waiting for cluster to get ready" void $ forkIO $ do void (readMVar (clusterReady gossipContext)) >> Log.i "Cluster is ready!" readMVar (clusterInited gossipContext) >>= \case Gossip -> return () _ -> do getProtoTimestamp >>= \x -> upsertMeta @Proto.Timestamp clusterStartTimeId x metaHandle handle (\(_ :: RQLiteRowNotFound) -> return ()) $ deleteAllMeta @TaskAllocation metaHandle #ifdef HStreamUseGrpcHaskell let sslOpts = initializeTlsConfig <$> join (Map.lookup "tls" securityMap) #else sslOpts <- mapM readTlsPemFile $ join (Map.lookup "tls" securityMap) #endif let grpcOpts = #ifdef HStreamUseGrpcHaskell GRPC.defaultServiceOptions { GRPC.serverHost = GRPC.Host host , GRPC.serverPort = GRPC.Port $ fromIntegral port , GRPC.serverOnStarted = Just serverOnStarted , GRPC.sslConfig = sslOpts } #else HsGrpc.ServerOptions { HsGrpc.serverHost = BS.toShort host , HsGrpc.serverPort = fromIntegral port , HsGrpc.serverParallelism = 0 , HsGrpc.serverSslOptions = sslOpts , HsGrpc.serverOnStarted = Just serverOnStarted } #endif forM_ (Map.toList listeners) $ \(key, vs) -> forM_ vs $ \I.Listener{..} -> do Log.debug $ "Starting advertised listener, " <> "key: " <> Log.buildText key <> ", " <> "address: " <> Log.buildText listenerAddress <> ", " <> "port: " <> Log.buildInt listenerPort forkIO $ do let listenerOnStarted = Log.info $ "Extra listener is started on port " <> Log.buildInt listenerPort let sc' = sc{scAdvertisedListenersKey = Just key} #ifdef HStreamUseGrpcHaskell let newSslOpts = initializeTlsConfig <$> join ((`Map.lookup` securityMap) =<< Map.lookup key listenerSecurityMap ) let grpcOpts' = grpcOpts { GRPC.serverPort = GRPC.Port $ fromIntegral listenerPort , GRPC.serverOnStarted = Just listenerOnStarted , GRPC.sslConfig = newSslOpts } api <- handlers sc' hstreamApiServer api grpcOpts' #else newSslOpts <- mapM readTlsPemFile $ join ((`Map.lookup` securityMap) =<< Map.lookup key listenerSecurityMap ) let grpcOpts' = grpcOpts { HsGrpc.serverPort = fromIntegral listenerPort , HsGrpc.serverOnStarted = Just listenerOnStarted , HsGrpc.serverSslOptions = newSslOpts } HsGrpc.runServer grpcOpts' (HsGrpc.handlers sc') #endif #ifdef HStreamUseGrpcHaskell Log.info "Starting server with grpc-haskell..." api <- handlers sc hstreamApiServer api grpcOpts #else Log.info "Starting server with hs-grpc-server..." HsGrpc.runServer grpcOpts (HsGrpc.handlers sc) #endif updateHashRing :: GossipContext -> TVar (Epoch, HashRing) -> IO () updateHashRing gc hashRing = loop 0 where loop epoch = loop =<< atomically ( do (epoch', list) <- getMemberListWithEpochSTM gc when (epoch == epoch') retry writeTVar hashRing (epoch', constructServerMap list) return epoch' )
a745d0c290d606e03055def7deaf4cb439eff2b71d2ea62692352df1652faec7
Helium4Haskell/helium
PatListResult.hs
module PatListResult where f :: Bool -> Int f [a] = 13
null
https://raw.githubusercontent.com/Helium4Haskell/helium/5928bff479e6f151b4ceb6c69bbc15d71e29eb47/test/typeerrors/Examples/PatListResult.hs
haskell
module PatListResult where f :: Bool -> Int f [a] = 13
1f30fb16de2198e01f9d8b53fae888b7dcfea0d1ff6f00c15483b648f6aa371a
qrilka/xlsx
CommonTests.hs
# LANGUAGE FlexibleInstances # # LANGUAGE MultiParamTypeClasses # # LANGUAGE ScopedTypeVariables # {-# LANGUAGE OverloadedStrings #-} # OPTIONS_GHC -fno - warn - orphans # module CommonTests ( tests ) where import Data.Fixed (Pico, Fixed(..), E12) import Data.Time.Calendar (fromGregorian) import Data.Time.Clock (UTCTime(..)) import Test.Tasty.SmallCheck (testProperty) import Test.SmallCheck.Series as Series ( Positive(..) , Serial(..) , newtypeCons , cons0 , (\/) ) import Test.Tasty (testGroup, TestTree) import Test.Tasty.HUnit (testCase, (@?=)) import Codec.Xlsx.Types.Common import qualified CommonTests.CellRefTests as CellRefTests tests :: TestTree tests = testGroup "Types.Common tests" [ testCase "date conversions" $ do dateFromNumber DateBase1900 (- 2338.0) @?= read "1893-08-06 00:00:00 UTC" dateFromNumber DateBase1900 2.0 @?= read "1900-01-02 00:00:00 UTC" dateFromNumber DateBase1900 3687.0 @?= read "1910-02-03 00:00:00 UTC" dateFromNumber DateBase1900 38749.0 @?= read "2006-02-01 00:00:00 UTC" dateFromNumber DateBase1900 2958465.0 @?= read "9999-12-31 00:00:00 UTC" dateFromNumber DateBase1900 59.0 @?= read "1900-02-28 00:00:00 UTC" dateFromNumber DateBase1900 59.5 @?= read "1900-02-28 12:00:00 UTC" dateFromNumber DateBase1900 60.0 @?= read "1900-03-01 00:00:00 UTC" dateFromNumber DateBase1900 60.5 @?= read "1900-03-01 00:00:00 UTC" dateFromNumber DateBase1900 61 @?= read "1900-03-01 00:00:00 UTC" dateFromNumber DateBase1900 61.5 @?= read "1900-03-01 12:00:00 UTC" dateFromNumber DateBase1900 62 @?= read "1900-03-02 00:00:00 UTC" dateFromNumber DateBase1904 (-3800.0) @?= read "1893-08-05 00:00:00 UTC" dateFromNumber DateBase1904 0.0 @?= read "1904-01-01 00:00:00 UTC" dateFromNumber DateBase1904 2225.0 @?= read "1910-02-03 00:00:00 UTC" dateFromNumber DateBase1904 37287.0 @?= read "2006-02-01 00:00:00 UTC" dateFromNumber DateBase1904 2957003.0 @?= read "9999-12-31 00:00:00 UTC" , testCase "Converting dates in the vicinity of 1900-03-01 to numbers" $ do Note how the fact that 1900 - 02 - 29 exists for Excel forces us to skip 60 dateToNumber DateBase1900 (UTCTime (fromGregorian 1900 2 28) 0) @?= (59 :: Double) dateToNumber DateBase1900 (UTCTime (fromGregorian 1900 3 1) 0) @?= (61 :: Double) , testProperty "dateToNumber . dateFromNumber == id" $ Because excel treats 1900 as a leap year , dateToNumber and dateFromNumber are n't inverses of each other in the range n E [ 60 , 61 [ for DateBase1900 \b (n :: Pico) -> (n >= 60 && n < 61 && b == DateBase1900) || n == dateToNumber b (dateFromNumber b $ n) , CellRefTests.tests ] instance Monad m => Serial m (Fixed E12) where series = newtypeCons MkFixed instance Monad m => Serial m DateBase where series = cons0 DateBase1900 \/ cons0 DateBase1904
null
https://raw.githubusercontent.com/qrilka/xlsx/c71992f20f78b444a5ff96254efc3a7bcf685abf/test/CommonTests.hs
haskell
# LANGUAGE OverloadedStrings #
# LANGUAGE FlexibleInstances # # LANGUAGE MultiParamTypeClasses # # LANGUAGE ScopedTypeVariables # # OPTIONS_GHC -fno - warn - orphans # module CommonTests ( tests ) where import Data.Fixed (Pico, Fixed(..), E12) import Data.Time.Calendar (fromGregorian) import Data.Time.Clock (UTCTime(..)) import Test.Tasty.SmallCheck (testProperty) import Test.SmallCheck.Series as Series ( Positive(..) , Serial(..) , newtypeCons , cons0 , (\/) ) import Test.Tasty (testGroup, TestTree) import Test.Tasty.HUnit (testCase, (@?=)) import Codec.Xlsx.Types.Common import qualified CommonTests.CellRefTests as CellRefTests tests :: TestTree tests = testGroup "Types.Common tests" [ testCase "date conversions" $ do dateFromNumber DateBase1900 (- 2338.0) @?= read "1893-08-06 00:00:00 UTC" dateFromNumber DateBase1900 2.0 @?= read "1900-01-02 00:00:00 UTC" dateFromNumber DateBase1900 3687.0 @?= read "1910-02-03 00:00:00 UTC" dateFromNumber DateBase1900 38749.0 @?= read "2006-02-01 00:00:00 UTC" dateFromNumber DateBase1900 2958465.0 @?= read "9999-12-31 00:00:00 UTC" dateFromNumber DateBase1900 59.0 @?= read "1900-02-28 00:00:00 UTC" dateFromNumber DateBase1900 59.5 @?= read "1900-02-28 12:00:00 UTC" dateFromNumber DateBase1900 60.0 @?= read "1900-03-01 00:00:00 UTC" dateFromNumber DateBase1900 60.5 @?= read "1900-03-01 00:00:00 UTC" dateFromNumber DateBase1900 61 @?= read "1900-03-01 00:00:00 UTC" dateFromNumber DateBase1900 61.5 @?= read "1900-03-01 12:00:00 UTC" dateFromNumber DateBase1900 62 @?= read "1900-03-02 00:00:00 UTC" dateFromNumber DateBase1904 (-3800.0) @?= read "1893-08-05 00:00:00 UTC" dateFromNumber DateBase1904 0.0 @?= read "1904-01-01 00:00:00 UTC" dateFromNumber DateBase1904 2225.0 @?= read "1910-02-03 00:00:00 UTC" dateFromNumber DateBase1904 37287.0 @?= read "2006-02-01 00:00:00 UTC" dateFromNumber DateBase1904 2957003.0 @?= read "9999-12-31 00:00:00 UTC" , testCase "Converting dates in the vicinity of 1900-03-01 to numbers" $ do Note how the fact that 1900 - 02 - 29 exists for Excel forces us to skip 60 dateToNumber DateBase1900 (UTCTime (fromGregorian 1900 2 28) 0) @?= (59 :: Double) dateToNumber DateBase1900 (UTCTime (fromGregorian 1900 3 1) 0) @?= (61 :: Double) , testProperty "dateToNumber . dateFromNumber == id" $ Because excel treats 1900 as a leap year , dateToNumber and dateFromNumber are n't inverses of each other in the range n E [ 60 , 61 [ for DateBase1900 \b (n :: Pico) -> (n >= 60 && n < 61 && b == DateBase1900) || n == dateToNumber b (dateFromNumber b $ n) , CellRefTests.tests ] instance Monad m => Serial m (Fixed E12) where series = newtypeCons MkFixed instance Monad m => Serial m DateBase where series = cons0 DateBase1900 \/ cons0 DateBase1904
5ab0970c824d8d604a2222e01bc4a95e3c21bdd1b2c4509c0efd104693d071f8
gjz010/slowql
Database.hs
# LANGUAGE DeriveGeneric # module SlowQL.Manage.Database where import qualified SlowQL.Manage.Table as T import qualified Data.ByteString as BS import qualified Data.ByteString.Lazy as BL import qualified SlowQL.Record.DataType as DT import qualified Data.ByteString.Char8 as BC import Data.Binary.Put import Data.Binary.Get import System.IO import System.Directory import SlowQL.Utils import Data.Conduit import Conduit import Data.IORef import qualified Data.Array.IArray as Arr import Data.Array.IArray ((!)) import qualified Data.Map.Strict as Map import qualified SlowQL.SQL.Parser as P import qualified SlowQL.Record.Relation as R import qualified Data.Vector.Mutable as V import qualified SlowQL.Manage.Index as I import Control.Monad import Control.Exception import Data.List import Control.DeepSeq import Data.Maybe type ByteString=BS.ByteString data DatabaseDef=DatabaseDef {name :: !ByteString, tables :: ![T.TableDef], indices :: ![I.IndexDef]} deriving (Show) data Database=Database {def :: !(IORef DatabaseDef), live_tables :: !(IORef (Map.Map ByteString T.Table)), live_indices :: !(IORef (Map.Map (ByteString, Int) I.Index))} tablePath :: String->String->String tablePath base name="slowql-data/"++base++"/"++name++".table" indexPath :: String->I.IndexDef->String indexPath base def="slowql-data/"++base++"/"++(BC.unpack $ I.name def)++(show $ I.target def)++".index" flushDatabaseDef :: Database->IO() flushDatabaseDef db=do def<-readIORef $ def db BL.writeFile ("slowql-data/"++(BC.unpack $ name def)++"/.slowql") $ runPut $ serialize def openTable :: ByteString->T.TableDef->IO (ByteString, T.Table) openTable base df=do let path=tablePath (BC.unpack base) (BC.unpack $ T.name df) t<-T.open path df return $ seq df (T.name df, t) showDatabase :: Database->IO() showDatabase db=do ddf<-readIORef (def db) print ddf lt<-readIORef (live_tables db) print lt li<-readIORef (live_indices db) print li openIndex :: Database->I.IndexDef->IO I.Index openIndex db df=do ddf<-readIORef (def db) let base=name ddf let path=indexPath (BC.unpack base) df [table]<-getTablesByName [BC.unpack $ I.name df] db i<-I.open path df (T.def table) modifyIORef' (live_indices db) (Map.insert (I.name df, I.target df) i) return i openAllIndices :: Database->IO () openAllIndices db=do ddf<-readIORef (def db) mapM_ (openIndex db) (indices ddf) openAllTables :: DatabaseDef->IO (Map.Map ByteString T.Table) openAllTables df=do l<-mapM (openTable $ name df) $ tables df return $ Map.fromList l showTables :: Database->IO () showTables db=do d<-readIORef $ def db print $ map T.name $ tables d createTable :: Database->String->[DT.TParam]->Maybe [String]->[(String, (String, String))]->IO () createTable db name orig_params primary fkey=do -- Pre-create check let bname=BC.pack name let params=map (\p->if isJust primary then if let Just [pk]=primary in BC.pack pk==(DT.name $ DT.general p) then p{DT.general=((DT.general p){DT.nullable=False})} else p else p) $ (DT.ridParam):orig_params tdef<-readIORef $ def db let primary_pred=case primary of Nothing->True (Just jp)-> (not $ hasDuplicates jp) && ( all (\p->any (\par->BC.pack p==(DT.name $ DT.general par) ) params) jp) checkWhen (all (\d->T.name d/=bname) $ tables tdef) "Duplicated table name!" $ checkWhen primary_pred "Bad primary key name!" $ checkWhen (all (\(p, _)->any (\par->BC.pack p==(DT.name $ DT.general par)) params) fkey) "Bad foreign key name!" $ do lts<-readIORef $ live_tables db let resolve_primary=case primary of Nothing -> 0 (Just [jp])-> forceJust "Bad primary key!" $ findIndex (\elm->(DT.name $ DT.general elm )== BC.pack jp) params let resolve_fkey (fld, (tbl,col))= (forceJust "Local column not found!" $ findIndex (\elm->(DT.name $ DT.general elm)==BC.pack fld) params, BC.pack tbl, forceJust "Foreign column not found!" $ findIndex (\elm->(DT.name $ DT.general elm)==BC.pack col) $ Arr.elems $ DT.domains $ T.domains $ T.def ((Map.!) lts (BC.pack tbl)) ) tbdef<-T.create (tablePath (BC.unpack $ SlowQL.Manage.Database.name tdef) name) name (DT.Domains $ DT.buildArray' params) resolve_primary (map resolve_fkey fkey) (pa,pb)<-openTable (SlowQL.Manage.Database.name tdef) tbdef modifyIORef' (live_tables db) (Map.insert pa pb) writeIORef (def db) (tdef {tables=tbdef:(tables tdef)}) when (resolve_primary > 0) $ createIndex' name (let Just [jp]=primary in jp) db putStrLn "CREATE TABLE" getAllRelatedIndices :: T.TableDef->Database->IO [I.Index] getAllRelatedIndices tdef db=do li<-readIORef $ live_indices db return $ snd $ unzip $ filter (\(k, a)->T.name tdef==fst k) $ Map.toList li type BinaryHook=(Int->ByteString->ByteString->IO ()) type UnitaryHook=((ByteString, Int)->IO ()) bindInsertHook :: [I.Index]->UnitaryHook bindInsertHook l u=mapM_ (\i->I.hookInsert i u) l bindUpdateHook :: [I.Index]->BinaryHook bindUpdateHook l a b c=mapM_ (\i->I.hookUpdate i a b c) l bindDeleteHook :: [I.Index]->UnitaryHook bindDeleteHook l u=mapM_ (\i->I.hookDelete i u) l insertHook :: T.Table->Database->UnitaryHook insertHook tbl db u=do l<-getAllRelatedIndices (T.def tbl) db bindInsertHook l u updateHook :: T.Table->Database->BinaryHook updateHook tbl db a b c=do l<-getAllRelatedIndices (T.def tbl) db bindUpdateHook l a b c deleteHook :: T.Table->Database->UnitaryHook deleteHook tbl db u=do l<-getAllRelatedIndices (T.def tbl) db bindDeleteHook l u createIndex :: String->String->Database->IO () createIndex tblname colname db=do createIndex' tblname colname db putStrLn "CREATE INDEX" createIndex' :: String->String->Database->IO() createIndex' tblname colname db=do [table]<-getTablesByName [tblname] db ddef<-readIORef $ def db let (_,column_id,_,_)= forceJust "Column missing!" $ translateColumn ([T.def table]) $ P.LocalCol colname let idef=I.IndexDef (BC.pack tblname) column_id checkWhen (not $ hasDuplicates $ idef:(indices ddef)) "Duplicated Index!" $ do I.create (indexPath (BC.unpack $ name ddef) idef) (T.def table) column_id writeIORef (def db) ddef{indices=idef:(indices ddef)} i<-openIndex db idef I.seed i table dropIndex :: String->String->Database->IO() dropIndex tblname colname db=do [table]<-getTablesByName [tblname] db let (_,column_id,_,_)= forceJust "Column missing!" $ translateColumn ([T.def table]) $ P.LocalCol colname dropIndex' (BC.pack tblname, column_id) db putStrLn "DROP INDEX" dropIndex' :: (ByteString, Int)->Database->IO() dropIndex' (tname, target) db=do li<-readIORef $ live_indices db let k=(tname, target) I.close ((Map.!) li k) print " Drop ! " modifyIORef' (live_indices db) (Map.delete k) ddef<-readIORef $ def db let new_indices=filter (/=(I.IndexDef tname target)) $ indices ddef removeFile $ indexPath (BC.unpack $ name ddef) (I.IndexDef tname target) writeIORef (def db) (ddef {indices=new_indices}) dropAllIndices :: ByteString->Database->IO () dropAllIndices tblname db=do ddef<-readIORef $ def db let indices_to_remove=filter (\(I.IndexDef t _)->t==tblname) $ indices ddef mapM_ (\(I.IndexDef a b)->dropIndex' (a,b) db) indices_to_remove serialize :: DatabaseDef->Put serialize def=do DT.writeString $ name def putWord32le $ fromIntegral $ length $ tables def mapM_ T.serializeTableDef $ tables def putWord32le $ fromIntegral $ length $ indices def mapM_ I.serializeIndexDef $ indices def deserialize :: Get DatabaseDef deserialize=do name<-DT.readString tables<-DT.getList T.deserializeTableDef indices<-DT.getList I.deserializeIndexDef return $ DatabaseDef name tables indices listDatabases :: IO [String] listDatabases=listDirectory "slowql-data" open :: String->IO (Either String Database) open name=do e<-doesDirectoryExist ("slowql-data/"++name) if e then do putStrLn "Opening database" str<-BS.readFile $ "slowql-data/"++name++"/.slowql" let df=runGet deserialize (BL.fromStrict str) lt<-openAllTables df r1<-newIORef df r2<-newIORef lt r3<-newIORef (Map.empty) let db=Database r1 r2 r3 openAllIndices db return $ Right db else return $ Left "Database does not exist." close :: Database->IO () close db=do lt<-readIORef $ live_tables db li<-readIORef $ live_indices db mapM_ T.close $ Map.elems lt mapM_ I.close $ Map.elems li d<-readIORef $ def db putStrLn "Closing database" BL.writeFile ("slowql-data/"++(BC.unpack $ name d)++"/.slowql") $runPut $ serialize d create :: String->IO (Maybe String) create db=do e<-doesDirectoryExist ("slowql-data/"++db) if e then return $ Just "Database already exists." else do createDirectory $ "slowql-data/"++db let def=DatabaseDef (BC.pack db) [] [] BL.writeFile ("slowql-data/"++db++"/.slowql") $runPut $ serialize def return Nothing ensureUnique :: String->[a]->a ensureUnique err (x:[])=x ensureUnique err _=error err ensureUniqueMaybe :: [a]->Maybe a ensureUniqueMaybe (x:[])=Just x ensureUniqueMaybe _=Nothing selectFrom :: P.SQLStatement->Database->IO () selectFrom stmt db=do (expr, related_tables, related_indices)<-compileSelect stmt db runConduit ((R.evaluate expr related_tables related_indices).|printC) drop :: String->IO(Maybe String) drop db=do e<-doesDirectoryExist ("slowql-data/"++db) if e then do removeDirectoryRecursive $ "slowql-data/"++db return Nothing else return $ Just "Database does not exist." dropTable :: String->Database->IO () dropTable tblname db=do [tbl]<-getTablesByName [tblname] db T.close tbl ddef<-readIORef $ def db let new_tables=filter (\d->(T.name d) /= (BC.pack tblname)) (tables ddef) writeIORef (def db) ddef{tables=new_tables} modifyIORef' (live_tables db) (Map.delete $ BC.pack tblname) removeFile $ tablePath (BC.unpack $ name ddef) (tblname) dropAllIndices (BC.pack tblname) db putStrLn "DROP TABLE" getTablesByName :: [String]->Database->IO [T.Table] getTablesByName l db=do mp<-readIORef $ live_tables db return $ map (((Map.!) mp). BC.pack) l TableIndex , ColumnIndex , TotalIndex , TParam translateColumn tdefs= let domains=map (DT.domains . T.domains) tdefs offsets=DT.buildArray' $ scanl (+) 0 (map (\arr->let (a,b)=Arr.bounds arr in b+1) domains) all_columns=map (\tabledef->let column_names=map (\p->(DT.name $ DT.general p, p)) $ Arr.elems tabledef in zip [0..] column_names) domains concat_columns=concat $ zipWith (\tindex list->map (\(cindex, (name,p))->(name, (tindex, cindex, (offsets!tindex)+cindex, p))) list)[0..] all_columns go (P.ForeignCol tblname colname)=do (tindex, tabledef)<-find (\(index, t)->BC.pack tblname==(T.name t)) (zip [0..] tdefs) let table_domains=DT.domains $ T.domains tabledef (cindex, p)<-find (\(_, d)->(BC.pack colname)==(DT.name $ DT.general d)) (zip [0..] $ Arr.elems table_domains) return (tindex, cindex, (offsets!tindex)+cindex, p) go (P.LocalCol colname)=do (_, t)<-ensureUniqueMaybe $ filter (\(bs, tuple)->BC.pack colname==bs) concat_columns return t in go forceJust :: String->Maybe a->a forceJust err Nothing=error err forceJust _ (Just x)=x applyOp :: P.Op->DT.TValue->DT.TValue->Bool applyOp P.OpEq=(==) applyOp P.OpNeq=(/=) applyOp P.OpLeq=(<=) applyOp P.OpGeq=(>=) applyOp P.OpLt=(<) applyOp P.OpGt=(>) tryIndex :: Database->T.Table->Int->IO (Maybe I.Index) tryIndex db table cid=do let tname=T.name $ T.def table li<-readIORef $ live_indices db return $ Map.lookup (tname, cid) li compileSelect :: P.SQLStatement->Database->IO (R.RelExpr, Arr.Array Int T.Table, Arr.Array Int I.Index) compileSelect stmt db=do df<-readIORef $ def db let get_tables (P.SelectStmt _ a b c)=(a,b,c) get_tables (P.SelectAllStmt a b c)=(a,b,c) let (used_tables, whereclause, suffices)=get_tables stmt used_tables_list<-getTablesByName used_tables db -- param 2 let array_tables=DT.buildArray' used_tables_list let all_table_defs=map T.def used_tables_list let translate=(forceJust "Column missing!" ). (translateColumn all_table_defs) --Expand where-clause into where segments let expand_where P.WhereAny=[] expand_where (P.WhereOp column op (P.ExprV val))=let (t,c,g, p)=translate column in if DT.compatiblePV p val then let functor=(\r->applyOp op ((DT.fields r) ! c) val) global_functor=(\r->applyOp op ((DT.fields r)!g) val) in case op of P.OpEq -> [R.OptimizableSingleTableWhereClause t c (Just (True, val)) (Just (True, val)) functor global_functor] P.OpLeq -> [R.OptimizableSingleTableWhereClause t c Nothing (Just (True, val)) functor global_functor] P.OpLt -> [R.OptimizableSingleTableWhereClause t c Nothing (Just (False, val)) functor global_functor] P.OpGeq -> [R.OptimizableSingleTableWhereClause t c (Just (True, val)) Nothing functor global_functor] P.OpGt -> [R.OptimizableSingleTableWhereClause t c (Just (False, val)) Nothing functor global_functor] _ -> [R.SingleTableWhereClause t functor global_functor] else [R.WhereNotCompatiblePV t c] expand_where (P.WhereOp c1 op (P.ExprC c2))= let (t1, ci1, i1, p1)=translate c1 (t2, ci2, i2, p2)=translate c2 in if DT.compatiblePP p1 p2 then if t1==t2 then [R.SingleTableWhereClause t1 (\r->applyOp op ((DT.fields r) ! ci1) ((DT.fields r) ! ci2)) (\r->applyOp op ((DT.fields r) ! i1) ((DT.fields r) ! i2))] else let functor=(\r->applyOp op ((DT.fields r) ! i1) ((DT.fields r) ! i2)) in if op==P.OpEq then [(if i1<i2 then R.ForeignReference t2 ci2 i1 functor else R.ForeignReference t1 ci1 i2 functor)] else [R.GeneralWhereClause functor] else [R.WhereNotCompatiblePP t1 ci1 t2 ci2] expand_where (P.WhereIsNull column isnull)=let (t,c,g, p)=translate column in let nullvalue=DT.nullValue p in expand_where (P.WhereOp column (if isnull then P.OpEq else P.OpNeq) (P.ExprV nullvalue)) expand_where (P.WhereAnd a b)=(expand_where a)++(expand_where b) let compiled_whereclause=force $ expand_where whereclause mapM_ R.assertCompileError compiled_whereclause print compiled_whereclause global_constraints<-newIORef $ map (\(R.GeneralWhereClause fallback)->fallback) $ filter R.isGeneralWC compiled_whereclause let addFB x=modifyIORef' global_constraints (\l->x:l) used_indices<-newIORef $ [] let addIdx x=do l<-readIORef used_indices let ll=length l modifyIORef' used_indices (\l->x:l) return ll let add_column acc tid=do if there is one and only one foreign reference , use the reference and use single table constraints as global constraints . --else the foreign reference becomes a global constraint that can be solved later let filter_foreign_reference (R.ForeignReference table_id column_id referto fallback)=table_id==tid filter_foreign_reference _ =False let f1_result=filter filter_foreign_reference compiled_whereclause let is_our_stc (R.SingleTableWhereClause table_id _ _)=table_id==tid is_our_stc (R.OptimizableSingleTableWhereClause table_id _ _ _ _ _)=table_id==tid is_our_stc _=False let optimize_singleclause=do --Get all available indices let table=(array_tables!tid) let tname=T.name $ T.def table li<-readIORef $ live_indices db let f3_result=filter is_our_stc compiled_whereclause let apply_filter expr (R.SingleTableWhereClause _ sf _)=R.RelFilter (R.RecordPred sf) expr apply_filter expr (R.OptimizableSingleTableWhereClause _ column_id l u sf _)= if (Map.member (tname ,column_id) li) then R.RelInterval (R.RecordPred sf) expr column_id (l, u) else R.RelFilter (R.RecordPred sf) expr let expr=foldl' apply_filter (R.RelEnumAll tid) f3_result cui<-readIORef used_indices let (used_index, merged_expr)=R.mergeEnumRange (length cui) expr when (isJust used_index) (let (Just juindex)=used_index (Just uindex)=Map.lookup (tname, juindex) li in do addIdx uindex return () ) return $ if R.isRelNothing acc then merged_expr else (R.RelCart acc merged_expr) if (length f1_result==1) then do let [(R.ForeignReference table_id column_id referto fallback)]=f1_result try_index<-tryIndex db (array_tables!table_id) column_id if (isJust try_index) then do let (Just index)=try_index placeholder<-addIdx index let expr=R.RelCartForeign acc placeholder referto let single_column_constraints x=is_our_stc x let f2_result=map R.fallback $ filter single_column_constraints compiled_whereclause mapM_ (addFB) f2_result return expr else do mapM_ (addFB) $ map R.fallback f1_result optimize_singleclause else do mapM_ (addFB) $ map R.fallback f1_result optimize_singleclause --if there are only optimizable clauses, try to optimize them --else combine all single-table clauses together. --cart this and that together. folded_expr<-foldM add_column R.RelNothing [0..(length used_tables_list-1)] gc_pred<-readIORef global_constraints let apply_multitable expr pred =R.RelFilter (R.RecordPred pred) expr let full_expr= foldl' apply_multitable folded_expr gc_pred let table_sources = DT.buildArray ' map [ 0 .. ((length used_tables_list)-1 ) ] ( length used_tables_list ) : : IO ( V.IOVector R.RelExpr ) mapM _ ( uncurry $ V.write table_vec ) $ zip [ 0 .. ] $ map [ 0 .. ((length used_tables_list)-1 ) ] --Maybe need reorder ? --Apply single - table filter let apply_singletable ( $ R.RecordPred pred ) tid : : IO ( ) apply_singletable _ = return ( ) mapM _ apply_singletable compiled_whereclause cart_items<-mapM ( V.read table_vec ) [ 0 .. ((length used_tables_list)-1 ) ] let folded_expr = foldr1 R.RelCart cart_items --Not considering index . let apply_multitable expr ( R.GeneralWhereClause pred ) = R.RelFilter ( R.RecordPred pred ) expr apply_multitable expr _ = expr let full_expr = foldl ' apply_multitable folded_expr compiled_whereclause table_vec<-V.new (length used_tables_list) :: IO (V.IOVector R.RelExpr) mapM_ (uncurry $ V.write table_vec ) $ zip [0..] $ map R.RelEnumAll [0..((length used_tables_list)-1)] --Maybe need reorder? --Apply single-table filter let apply_singletable (R.SingleTableWhereClause tid pred)=V.modify table_vec (R.RelFilter $ R.RecordPred pred) tid :: IO() apply_singletable _=return () mapM_ apply_singletable compiled_whereclause cart_items<-mapM (V.read table_vec) [0..((length used_tables_list)-1)] let folded_expr=foldr1 R.RelCart cart_items --Not considering index. let apply_multitable expr (R.GeneralWhereClause pred) =R.RelFilter (R.RecordPred pred) expr apply_multitable expr _=expr let full_expr=foldl' apply_multitable folded_expr compiled_whereclause -} --Expand projectors let names_of_all_columns=concat $ map (map (DT.name . DT.general) . Arr.elems . DT.domains . T.domains . T.def) used_tables_list let (removed_rids, _)=unzip $ filter (\(_, n)->n/=BC.pack "_rid") $ zip [0..] names_of_all_columns let add_projector (P.SelectAllStmt _ _ _) expr=R.RelProjection removed_rids expr add_projector (P.SelectStmt proj _ _ _) expr=R.RelProjection (map (\((_, _, c, _))->c) $ map translate proj) expr -- Add offset let apply_offset expr (P.COffset offset)=R.RelSkip offset expr apply_offset expr _=expr -- Add limit let apply_limit expr (P.CLimit limit)=R.RelTake limit expr apply_limit expr _=expr let query_plan=(flip (foldl' apply_limit) suffices) $ (flip (foldl' apply_offset) suffices)$ add_projector stmt full_expr evaluate $ force query_plan putStrLn ("Query plan: "++(show query_plan)) used_indices_list<-readIORef used_indices return (query_plan, DT.buildArray' used_tables_list, DT.buildArray' $ reverse used_indices_list) getIndex :: Database->(BS.ByteString, Int)->IO I.Index getIndex db p=do li<-readIORef $ live_indices db return $ (Map.!) li p doInsert :: String->[[DT.TValue]]->Database->IO () doInsert tblname orig_tvalues db=do [tbl]<-getTablesByName [tblname] db --do pre-flight check uuids<-generateBulkUUID (length orig_tvalues) let tvalues=zipWith (:) (map (DT.ValChar . Just ) uuids) orig_tvalues let op_insert recd=do when ((T.primary $ T.def tbl )/=0) $ do let notnull_test=not $ DT.isNull $ head $ (Data.List.drop (T.primary $ T.def tbl) recd) assertIO notnull_test "Primary key not null violation!" primary_index<-getIndex db (T.name $ T.def tbl, T.primary $ T.def tbl) unique_test<-I.checkUnique primary_index $ head $ Data.List.drop (T.primary $ T.def tbl) recd assertIO unique_test "Primary key unique violation!" let record=DT.Record $ DT.buildArray' recd T.insert tbl record (insertHook tbl db) let insert_into_index index = I.insert index record lt_index --li<-readIORef $ live_indices db mapM _ insert_into_index $ Map.elems li mapM_ op_insert tvalues putStrLn ("INSERT "++(show $ length tvalues)) doUpdate :: String->[(String, DT.TValue)]->P.WhereClause->Database->IO() doUpdate tblname tvalues wc db=do [tbl]<-getTablesByName [tblname] db let translate=(forceJust "Column missing!") .(translateColumn [T.def tbl] ) let (column_names, values)=unzip tvalues let columns= map (translate . P.LocalCol) column_names --Check compatible let check_compatible=and $ zipWith (\v (_,_,_,p)->DT.compatiblePV p v) values columns assertIO check_compatible "Some column and value not compatible!" let expand_where P.WhereAny=[] expand_where (P.WhereOp column op (P.ExprV val))=let (t,c,_, p)=translate column in if DT.compatiblePV p val then [R.GeneralWhereClause (\r->applyOp op ((DT.fields r) ! c) val)] else [R.WhereNotCompatiblePV t c] expand_where (P.WhereOp c1 op (P.ExprC c2))= let (t1, ci1, i1, p1)=translate c1 (t2, ci2, i2, p2)=translate c2 in if DT.compatiblePP p1 p2 then if t1==t2 then [R.GeneralWhereClause (\r->applyOp op ((DT.fields r) ! ci1) ((DT.fields r) ! ci2))] else [R.GeneralWhereClause (\r->applyOp op ((DT.fields r) ! i1) ((DT.fields r) ! i2))] else [R.WhereNotCompatiblePP t1 ci1 t2 ci2] expand_where (P.WhereIsNull column isnull)=let (t, c, _, _)=translate column in [R.GeneralWhereClause (\r->(DT.isNull ((DT.fields r)!c))==isnull)] expand_where (P.WhereAnd a b)=(expand_where a)++(expand_where b) let compiled_where=expand_where wc mapM_ R.assertCompileError compiled_where let eval_where rc (R.GeneralWhereClause pred)=pred rc --Do the real update work let replacement_tree=zipWith (\v (_, i, _, _)->(i, v)) values columns let checker rc=let pass w=eval_where rc w in foldr (&&) True (map pass compiled_where) let updator rc=if checker rc then Just $ DT.Record $ Arr.accum (\o n->n) (DT.fields rc) replacement_tree else Nothing updated<-T.update tbl updator (updateHook tbl db) putStrLn ("UPDATE "++(show updated)) doDelete :: String->P.WhereClause->Database->IO () doDelete tblname wc db=do [tbl]<-getTablesByName [tblname] db let translate=(forceJust "Column missing!") .(translateColumn [T.def tbl] ) let expand_where P.WhereAny=[] expand_where (P.WhereOp column op (P.ExprV val))=let (t,c,_, p)=translate column in if DT.compatiblePV p val then [R.GeneralWhereClause (\r->applyOp op ((DT.fields r) ! c) val)] else [R.WhereNotCompatiblePV t c] expand_where (P.WhereOp c1 op (P.ExprC c2))= let (t1, ci1, i1, p1)=translate c1 (t2, ci2, i2, p2)=translate c2 in if DT.compatiblePP p1 p2 then if t1==t2 then [R.GeneralWhereClause (\r->applyOp op ((DT.fields r) ! ci1) ((DT.fields r) ! ci2))] else [R.GeneralWhereClause (\r->applyOp op ((DT.fields r) ! i1) ((DT.fields r) ! i2))] else [R.WhereNotCompatiblePP t1 ci1 t2 ci2] expand_where (P.WhereIsNull column isnull)=let (t, c, _, _)=translate column in [R.GeneralWhereClause (\r->(DT.isNull ((DT.fields r)!c))==isnull)] expand_where (P.WhereAnd a b)=(expand_where a)++(expand_where b) let compiled_where=expand_where wc mapM_ R.assertCompileError compiled_where let eval_where rc (R.GeneralWhereClause pred)=pred rc -- Do the real delete work let deleter rc=let pass w=eval_where rc w in foldr (&&) True (map pass compiled_where) deleted<-T.delete tbl deleter (deleteHook tbl db) putStrLn ("DELETE "++(show deleted)) describeTable :: String->Database->IO() describeTable tblname db=do [tbl]<-getTablesByName [tblname] db print $ T.def tbl compileUpdate stmt db = return ( ) compileDelete stmt db = return ( ) data Database = Database { file : : Han } createDatabase : : ( ) --createDatabase=do
null
https://raw.githubusercontent.com/gjz010/slowql/5e8c698eeb10222082f5fb5bf5dabd4105819c77/src/SlowQL/Manage/Database.hs
haskell
Pre-create check param 2 Expand where-clause into where segments else the foreign reference becomes a global constraint that can be solved later Get all available indices if there are only optimizable clauses, try to optimize them else combine all single-table clauses together. cart this and that together. Maybe need reorder ? Apply single - table filter Not considering index . Maybe need reorder? Apply single-table filter Not considering index. Expand projectors Add offset Add limit do pre-flight check li<-readIORef $ live_indices db Check compatible Do the real update work Do the real delete work createDatabase=do
# LANGUAGE DeriveGeneric # module SlowQL.Manage.Database where import qualified SlowQL.Manage.Table as T import qualified Data.ByteString as BS import qualified Data.ByteString.Lazy as BL import qualified SlowQL.Record.DataType as DT import qualified Data.ByteString.Char8 as BC import Data.Binary.Put import Data.Binary.Get import System.IO import System.Directory import SlowQL.Utils import Data.Conduit import Conduit import Data.IORef import qualified Data.Array.IArray as Arr import Data.Array.IArray ((!)) import qualified Data.Map.Strict as Map import qualified SlowQL.SQL.Parser as P import qualified SlowQL.Record.Relation as R import qualified Data.Vector.Mutable as V import qualified SlowQL.Manage.Index as I import Control.Monad import Control.Exception import Data.List import Control.DeepSeq import Data.Maybe type ByteString=BS.ByteString data DatabaseDef=DatabaseDef {name :: !ByteString, tables :: ![T.TableDef], indices :: ![I.IndexDef]} deriving (Show) data Database=Database {def :: !(IORef DatabaseDef), live_tables :: !(IORef (Map.Map ByteString T.Table)), live_indices :: !(IORef (Map.Map (ByteString, Int) I.Index))} tablePath :: String->String->String tablePath base name="slowql-data/"++base++"/"++name++".table" indexPath :: String->I.IndexDef->String indexPath base def="slowql-data/"++base++"/"++(BC.unpack $ I.name def)++(show $ I.target def)++".index" flushDatabaseDef :: Database->IO() flushDatabaseDef db=do def<-readIORef $ def db BL.writeFile ("slowql-data/"++(BC.unpack $ name def)++"/.slowql") $ runPut $ serialize def openTable :: ByteString->T.TableDef->IO (ByteString, T.Table) openTable base df=do let path=tablePath (BC.unpack base) (BC.unpack $ T.name df) t<-T.open path df return $ seq df (T.name df, t) showDatabase :: Database->IO() showDatabase db=do ddf<-readIORef (def db) print ddf lt<-readIORef (live_tables db) print lt li<-readIORef (live_indices db) print li openIndex :: Database->I.IndexDef->IO I.Index openIndex db df=do ddf<-readIORef (def db) let base=name ddf let path=indexPath (BC.unpack base) df [table]<-getTablesByName [BC.unpack $ I.name df] db i<-I.open path df (T.def table) modifyIORef' (live_indices db) (Map.insert (I.name df, I.target df) i) return i openAllIndices :: Database->IO () openAllIndices db=do ddf<-readIORef (def db) mapM_ (openIndex db) (indices ddf) openAllTables :: DatabaseDef->IO (Map.Map ByteString T.Table) openAllTables df=do l<-mapM (openTable $ name df) $ tables df return $ Map.fromList l showTables :: Database->IO () showTables db=do d<-readIORef $ def db print $ map T.name $ tables d createTable :: Database->String->[DT.TParam]->Maybe [String]->[(String, (String, String))]->IO () createTable db name orig_params primary fkey=do let bname=BC.pack name let params=map (\p->if isJust primary then if let Just [pk]=primary in BC.pack pk==(DT.name $ DT.general p) then p{DT.general=((DT.general p){DT.nullable=False})} else p else p) $ (DT.ridParam):orig_params tdef<-readIORef $ def db let primary_pred=case primary of Nothing->True (Just jp)-> (not $ hasDuplicates jp) && ( all (\p->any (\par->BC.pack p==(DT.name $ DT.general par) ) params) jp) checkWhen (all (\d->T.name d/=bname) $ tables tdef) "Duplicated table name!" $ checkWhen primary_pred "Bad primary key name!" $ checkWhen (all (\(p, _)->any (\par->BC.pack p==(DT.name $ DT.general par)) params) fkey) "Bad foreign key name!" $ do lts<-readIORef $ live_tables db let resolve_primary=case primary of Nothing -> 0 (Just [jp])-> forceJust "Bad primary key!" $ findIndex (\elm->(DT.name $ DT.general elm )== BC.pack jp) params let resolve_fkey (fld, (tbl,col))= (forceJust "Local column not found!" $ findIndex (\elm->(DT.name $ DT.general elm)==BC.pack fld) params, BC.pack tbl, forceJust "Foreign column not found!" $ findIndex (\elm->(DT.name $ DT.general elm)==BC.pack col) $ Arr.elems $ DT.domains $ T.domains $ T.def ((Map.!) lts (BC.pack tbl)) ) tbdef<-T.create (tablePath (BC.unpack $ SlowQL.Manage.Database.name tdef) name) name (DT.Domains $ DT.buildArray' params) resolve_primary (map resolve_fkey fkey) (pa,pb)<-openTable (SlowQL.Manage.Database.name tdef) tbdef modifyIORef' (live_tables db) (Map.insert pa pb) writeIORef (def db) (tdef {tables=tbdef:(tables tdef)}) when (resolve_primary > 0) $ createIndex' name (let Just [jp]=primary in jp) db putStrLn "CREATE TABLE" getAllRelatedIndices :: T.TableDef->Database->IO [I.Index] getAllRelatedIndices tdef db=do li<-readIORef $ live_indices db return $ snd $ unzip $ filter (\(k, a)->T.name tdef==fst k) $ Map.toList li type BinaryHook=(Int->ByteString->ByteString->IO ()) type UnitaryHook=((ByteString, Int)->IO ()) bindInsertHook :: [I.Index]->UnitaryHook bindInsertHook l u=mapM_ (\i->I.hookInsert i u) l bindUpdateHook :: [I.Index]->BinaryHook bindUpdateHook l a b c=mapM_ (\i->I.hookUpdate i a b c) l bindDeleteHook :: [I.Index]->UnitaryHook bindDeleteHook l u=mapM_ (\i->I.hookDelete i u) l insertHook :: T.Table->Database->UnitaryHook insertHook tbl db u=do l<-getAllRelatedIndices (T.def tbl) db bindInsertHook l u updateHook :: T.Table->Database->BinaryHook updateHook tbl db a b c=do l<-getAllRelatedIndices (T.def tbl) db bindUpdateHook l a b c deleteHook :: T.Table->Database->UnitaryHook deleteHook tbl db u=do l<-getAllRelatedIndices (T.def tbl) db bindDeleteHook l u createIndex :: String->String->Database->IO () createIndex tblname colname db=do createIndex' tblname colname db putStrLn "CREATE INDEX" createIndex' :: String->String->Database->IO() createIndex' tblname colname db=do [table]<-getTablesByName [tblname] db ddef<-readIORef $ def db let (_,column_id,_,_)= forceJust "Column missing!" $ translateColumn ([T.def table]) $ P.LocalCol colname let idef=I.IndexDef (BC.pack tblname) column_id checkWhen (not $ hasDuplicates $ idef:(indices ddef)) "Duplicated Index!" $ do I.create (indexPath (BC.unpack $ name ddef) idef) (T.def table) column_id writeIORef (def db) ddef{indices=idef:(indices ddef)} i<-openIndex db idef I.seed i table dropIndex :: String->String->Database->IO() dropIndex tblname colname db=do [table]<-getTablesByName [tblname] db let (_,column_id,_,_)= forceJust "Column missing!" $ translateColumn ([T.def table]) $ P.LocalCol colname dropIndex' (BC.pack tblname, column_id) db putStrLn "DROP INDEX" dropIndex' :: (ByteString, Int)->Database->IO() dropIndex' (tname, target) db=do li<-readIORef $ live_indices db let k=(tname, target) I.close ((Map.!) li k) print " Drop ! " modifyIORef' (live_indices db) (Map.delete k) ddef<-readIORef $ def db let new_indices=filter (/=(I.IndexDef tname target)) $ indices ddef removeFile $ indexPath (BC.unpack $ name ddef) (I.IndexDef tname target) writeIORef (def db) (ddef {indices=new_indices}) dropAllIndices :: ByteString->Database->IO () dropAllIndices tblname db=do ddef<-readIORef $ def db let indices_to_remove=filter (\(I.IndexDef t _)->t==tblname) $ indices ddef mapM_ (\(I.IndexDef a b)->dropIndex' (a,b) db) indices_to_remove serialize :: DatabaseDef->Put serialize def=do DT.writeString $ name def putWord32le $ fromIntegral $ length $ tables def mapM_ T.serializeTableDef $ tables def putWord32le $ fromIntegral $ length $ indices def mapM_ I.serializeIndexDef $ indices def deserialize :: Get DatabaseDef deserialize=do name<-DT.readString tables<-DT.getList T.deserializeTableDef indices<-DT.getList I.deserializeIndexDef return $ DatabaseDef name tables indices listDatabases :: IO [String] listDatabases=listDirectory "slowql-data" open :: String->IO (Either String Database) open name=do e<-doesDirectoryExist ("slowql-data/"++name) if e then do putStrLn "Opening database" str<-BS.readFile $ "slowql-data/"++name++"/.slowql" let df=runGet deserialize (BL.fromStrict str) lt<-openAllTables df r1<-newIORef df r2<-newIORef lt r3<-newIORef (Map.empty) let db=Database r1 r2 r3 openAllIndices db return $ Right db else return $ Left "Database does not exist." close :: Database->IO () close db=do lt<-readIORef $ live_tables db li<-readIORef $ live_indices db mapM_ T.close $ Map.elems lt mapM_ I.close $ Map.elems li d<-readIORef $ def db putStrLn "Closing database" BL.writeFile ("slowql-data/"++(BC.unpack $ name d)++"/.slowql") $runPut $ serialize d create :: String->IO (Maybe String) create db=do e<-doesDirectoryExist ("slowql-data/"++db) if e then return $ Just "Database already exists." else do createDirectory $ "slowql-data/"++db let def=DatabaseDef (BC.pack db) [] [] BL.writeFile ("slowql-data/"++db++"/.slowql") $runPut $ serialize def return Nothing ensureUnique :: String->[a]->a ensureUnique err (x:[])=x ensureUnique err _=error err ensureUniqueMaybe :: [a]->Maybe a ensureUniqueMaybe (x:[])=Just x ensureUniqueMaybe _=Nothing selectFrom :: P.SQLStatement->Database->IO () selectFrom stmt db=do (expr, related_tables, related_indices)<-compileSelect stmt db runConduit ((R.evaluate expr related_tables related_indices).|printC) drop :: String->IO(Maybe String) drop db=do e<-doesDirectoryExist ("slowql-data/"++db) if e then do removeDirectoryRecursive $ "slowql-data/"++db return Nothing else return $ Just "Database does not exist." dropTable :: String->Database->IO () dropTable tblname db=do [tbl]<-getTablesByName [tblname] db T.close tbl ddef<-readIORef $ def db let new_tables=filter (\d->(T.name d) /= (BC.pack tblname)) (tables ddef) writeIORef (def db) ddef{tables=new_tables} modifyIORef' (live_tables db) (Map.delete $ BC.pack tblname) removeFile $ tablePath (BC.unpack $ name ddef) (tblname) dropAllIndices (BC.pack tblname) db putStrLn "DROP TABLE" getTablesByName :: [String]->Database->IO [T.Table] getTablesByName l db=do mp<-readIORef $ live_tables db return $ map (((Map.!) mp). BC.pack) l TableIndex , ColumnIndex , TotalIndex , TParam translateColumn tdefs= let domains=map (DT.domains . T.domains) tdefs offsets=DT.buildArray' $ scanl (+) 0 (map (\arr->let (a,b)=Arr.bounds arr in b+1) domains) all_columns=map (\tabledef->let column_names=map (\p->(DT.name $ DT.general p, p)) $ Arr.elems tabledef in zip [0..] column_names) domains concat_columns=concat $ zipWith (\tindex list->map (\(cindex, (name,p))->(name, (tindex, cindex, (offsets!tindex)+cindex, p))) list)[0..] all_columns go (P.ForeignCol tblname colname)=do (tindex, tabledef)<-find (\(index, t)->BC.pack tblname==(T.name t)) (zip [0..] tdefs) let table_domains=DT.domains $ T.domains tabledef (cindex, p)<-find (\(_, d)->(BC.pack colname)==(DT.name $ DT.general d)) (zip [0..] $ Arr.elems table_domains) return (tindex, cindex, (offsets!tindex)+cindex, p) go (P.LocalCol colname)=do (_, t)<-ensureUniqueMaybe $ filter (\(bs, tuple)->BC.pack colname==bs) concat_columns return t in go forceJust :: String->Maybe a->a forceJust err Nothing=error err forceJust _ (Just x)=x applyOp :: P.Op->DT.TValue->DT.TValue->Bool applyOp P.OpEq=(==) applyOp P.OpNeq=(/=) applyOp P.OpLeq=(<=) applyOp P.OpGeq=(>=) applyOp P.OpLt=(<) applyOp P.OpGt=(>) tryIndex :: Database->T.Table->Int->IO (Maybe I.Index) tryIndex db table cid=do let tname=T.name $ T.def table li<-readIORef $ live_indices db return $ Map.lookup (tname, cid) li compileSelect :: P.SQLStatement->Database->IO (R.RelExpr, Arr.Array Int T.Table, Arr.Array Int I.Index) compileSelect stmt db=do df<-readIORef $ def db let get_tables (P.SelectStmt _ a b c)=(a,b,c) get_tables (P.SelectAllStmt a b c)=(a,b,c) let (used_tables, whereclause, suffices)=get_tables stmt let array_tables=DT.buildArray' used_tables_list let all_table_defs=map T.def used_tables_list let translate=(forceJust "Column missing!" ). (translateColumn all_table_defs) let expand_where P.WhereAny=[] expand_where (P.WhereOp column op (P.ExprV val))=let (t,c,g, p)=translate column in if DT.compatiblePV p val then let functor=(\r->applyOp op ((DT.fields r) ! c) val) global_functor=(\r->applyOp op ((DT.fields r)!g) val) in case op of P.OpEq -> [R.OptimizableSingleTableWhereClause t c (Just (True, val)) (Just (True, val)) functor global_functor] P.OpLeq -> [R.OptimizableSingleTableWhereClause t c Nothing (Just (True, val)) functor global_functor] P.OpLt -> [R.OptimizableSingleTableWhereClause t c Nothing (Just (False, val)) functor global_functor] P.OpGeq -> [R.OptimizableSingleTableWhereClause t c (Just (True, val)) Nothing functor global_functor] P.OpGt -> [R.OptimizableSingleTableWhereClause t c (Just (False, val)) Nothing functor global_functor] _ -> [R.SingleTableWhereClause t functor global_functor] else [R.WhereNotCompatiblePV t c] expand_where (P.WhereOp c1 op (P.ExprC c2))= let (t1, ci1, i1, p1)=translate c1 (t2, ci2, i2, p2)=translate c2 in if DT.compatiblePP p1 p2 then if t1==t2 then [R.SingleTableWhereClause t1 (\r->applyOp op ((DT.fields r) ! ci1) ((DT.fields r) ! ci2)) (\r->applyOp op ((DT.fields r) ! i1) ((DT.fields r) ! i2))] else let functor=(\r->applyOp op ((DT.fields r) ! i1) ((DT.fields r) ! i2)) in if op==P.OpEq then [(if i1<i2 then R.ForeignReference t2 ci2 i1 functor else R.ForeignReference t1 ci1 i2 functor)] else [R.GeneralWhereClause functor] else [R.WhereNotCompatiblePP t1 ci1 t2 ci2] expand_where (P.WhereIsNull column isnull)=let (t,c,g, p)=translate column in let nullvalue=DT.nullValue p in expand_where (P.WhereOp column (if isnull then P.OpEq else P.OpNeq) (P.ExprV nullvalue)) expand_where (P.WhereAnd a b)=(expand_where a)++(expand_where b) let compiled_whereclause=force $ expand_where whereclause mapM_ R.assertCompileError compiled_whereclause print compiled_whereclause global_constraints<-newIORef $ map (\(R.GeneralWhereClause fallback)->fallback) $ filter R.isGeneralWC compiled_whereclause let addFB x=modifyIORef' global_constraints (\l->x:l) used_indices<-newIORef $ [] let addIdx x=do l<-readIORef used_indices let ll=length l modifyIORef' used_indices (\l->x:l) return ll let add_column acc tid=do if there is one and only one foreign reference , use the reference and use single table constraints as global constraints . let filter_foreign_reference (R.ForeignReference table_id column_id referto fallback)=table_id==tid filter_foreign_reference _ =False let f1_result=filter filter_foreign_reference compiled_whereclause let is_our_stc (R.SingleTableWhereClause table_id _ _)=table_id==tid is_our_stc (R.OptimizableSingleTableWhereClause table_id _ _ _ _ _)=table_id==tid is_our_stc _=False let optimize_singleclause=do let table=(array_tables!tid) let tname=T.name $ T.def table li<-readIORef $ live_indices db let f3_result=filter is_our_stc compiled_whereclause let apply_filter expr (R.SingleTableWhereClause _ sf _)=R.RelFilter (R.RecordPred sf) expr apply_filter expr (R.OptimizableSingleTableWhereClause _ column_id l u sf _)= if (Map.member (tname ,column_id) li) then R.RelInterval (R.RecordPred sf) expr column_id (l, u) else R.RelFilter (R.RecordPred sf) expr let expr=foldl' apply_filter (R.RelEnumAll tid) f3_result cui<-readIORef used_indices let (used_index, merged_expr)=R.mergeEnumRange (length cui) expr when (isJust used_index) (let (Just juindex)=used_index (Just uindex)=Map.lookup (tname, juindex) li in do addIdx uindex return () ) return $ if R.isRelNothing acc then merged_expr else (R.RelCart acc merged_expr) if (length f1_result==1) then do let [(R.ForeignReference table_id column_id referto fallback)]=f1_result try_index<-tryIndex db (array_tables!table_id) column_id if (isJust try_index) then do let (Just index)=try_index placeholder<-addIdx index let expr=R.RelCartForeign acc placeholder referto let single_column_constraints x=is_our_stc x let f2_result=map R.fallback $ filter single_column_constraints compiled_whereclause mapM_ (addFB) f2_result return expr else do mapM_ (addFB) $ map R.fallback f1_result optimize_singleclause else do mapM_ (addFB) $ map R.fallback f1_result optimize_singleclause folded_expr<-foldM add_column R.RelNothing [0..(length used_tables_list-1)] gc_pred<-readIORef global_constraints let apply_multitable expr pred =R.RelFilter (R.RecordPred pred) expr let full_expr= foldl' apply_multitable folded_expr gc_pred let table_sources = DT.buildArray ' map [ 0 .. ((length used_tables_list)-1 ) ] ( length used_tables_list ) : : IO ( V.IOVector R.RelExpr ) mapM _ ( uncurry $ V.write table_vec ) $ zip [ 0 .. ] $ map [ 0 .. ((length used_tables_list)-1 ) ] let apply_singletable ( $ R.RecordPred pred ) tid : : IO ( ) apply_singletable _ = return ( ) mapM _ apply_singletable compiled_whereclause cart_items<-mapM ( V.read table_vec ) [ 0 .. ((length used_tables_list)-1 ) ] let apply_multitable expr ( R.GeneralWhereClause pred ) = R.RelFilter ( R.RecordPred pred ) expr apply_multitable expr _ = expr let full_expr = foldl ' apply_multitable folded_expr compiled_whereclause table_vec<-V.new (length used_tables_list) :: IO (V.IOVector R.RelExpr) mapM_ (uncurry $ V.write table_vec ) $ zip [0..] $ map R.RelEnumAll [0..((length used_tables_list)-1)] let apply_singletable (R.SingleTableWhereClause tid pred)=V.modify table_vec (R.RelFilter $ R.RecordPred pred) tid :: IO() apply_singletable _=return () mapM_ apply_singletable compiled_whereclause cart_items<-mapM (V.read table_vec) [0..((length used_tables_list)-1)] let apply_multitable expr (R.GeneralWhereClause pred) =R.RelFilter (R.RecordPred pred) expr apply_multitable expr _=expr let full_expr=foldl' apply_multitable folded_expr compiled_whereclause -} let names_of_all_columns=concat $ map (map (DT.name . DT.general) . Arr.elems . DT.domains . T.domains . T.def) used_tables_list let (removed_rids, _)=unzip $ filter (\(_, n)->n/=BC.pack "_rid") $ zip [0..] names_of_all_columns let add_projector (P.SelectAllStmt _ _ _) expr=R.RelProjection removed_rids expr add_projector (P.SelectStmt proj _ _ _) expr=R.RelProjection (map (\((_, _, c, _))->c) $ map translate proj) expr let apply_offset expr (P.COffset offset)=R.RelSkip offset expr apply_offset expr _=expr let apply_limit expr (P.CLimit limit)=R.RelTake limit expr apply_limit expr _=expr let query_plan=(flip (foldl' apply_limit) suffices) $ (flip (foldl' apply_offset) suffices)$ add_projector stmt full_expr evaluate $ force query_plan putStrLn ("Query plan: "++(show query_plan)) used_indices_list<-readIORef used_indices return (query_plan, DT.buildArray' used_tables_list, DT.buildArray' $ reverse used_indices_list) getIndex :: Database->(BS.ByteString, Int)->IO I.Index getIndex db p=do li<-readIORef $ live_indices db return $ (Map.!) li p doInsert :: String->[[DT.TValue]]->Database->IO () doInsert tblname orig_tvalues db=do [tbl]<-getTablesByName [tblname] db uuids<-generateBulkUUID (length orig_tvalues) let tvalues=zipWith (:) (map (DT.ValChar . Just ) uuids) orig_tvalues let op_insert recd=do when ((T.primary $ T.def tbl )/=0) $ do let notnull_test=not $ DT.isNull $ head $ (Data.List.drop (T.primary $ T.def tbl) recd) assertIO notnull_test "Primary key not null violation!" primary_index<-getIndex db (T.name $ T.def tbl, T.primary $ T.def tbl) unique_test<-I.checkUnique primary_index $ head $ Data.List.drop (T.primary $ T.def tbl) recd assertIO unique_test "Primary key unique violation!" let record=DT.Record $ DT.buildArray' recd T.insert tbl record (insertHook tbl db) let insert_into_index index = I.insert index record lt_index mapM _ insert_into_index $ Map.elems li mapM_ op_insert tvalues putStrLn ("INSERT "++(show $ length tvalues)) doUpdate :: String->[(String, DT.TValue)]->P.WhereClause->Database->IO() doUpdate tblname tvalues wc db=do [tbl]<-getTablesByName [tblname] db let translate=(forceJust "Column missing!") .(translateColumn [T.def tbl] ) let (column_names, values)=unzip tvalues let columns= map (translate . P.LocalCol) column_names let check_compatible=and $ zipWith (\v (_,_,_,p)->DT.compatiblePV p v) values columns assertIO check_compatible "Some column and value not compatible!" let expand_where P.WhereAny=[] expand_where (P.WhereOp column op (P.ExprV val))=let (t,c,_, p)=translate column in if DT.compatiblePV p val then [R.GeneralWhereClause (\r->applyOp op ((DT.fields r) ! c) val)] else [R.WhereNotCompatiblePV t c] expand_where (P.WhereOp c1 op (P.ExprC c2))= let (t1, ci1, i1, p1)=translate c1 (t2, ci2, i2, p2)=translate c2 in if DT.compatiblePP p1 p2 then if t1==t2 then [R.GeneralWhereClause (\r->applyOp op ((DT.fields r) ! ci1) ((DT.fields r) ! ci2))] else [R.GeneralWhereClause (\r->applyOp op ((DT.fields r) ! i1) ((DT.fields r) ! i2))] else [R.WhereNotCompatiblePP t1 ci1 t2 ci2] expand_where (P.WhereIsNull column isnull)=let (t, c, _, _)=translate column in [R.GeneralWhereClause (\r->(DT.isNull ((DT.fields r)!c))==isnull)] expand_where (P.WhereAnd a b)=(expand_where a)++(expand_where b) let compiled_where=expand_where wc mapM_ R.assertCompileError compiled_where let eval_where rc (R.GeneralWhereClause pred)=pred rc let replacement_tree=zipWith (\v (_, i, _, _)->(i, v)) values columns let checker rc=let pass w=eval_where rc w in foldr (&&) True (map pass compiled_where) let updator rc=if checker rc then Just $ DT.Record $ Arr.accum (\o n->n) (DT.fields rc) replacement_tree else Nothing updated<-T.update tbl updator (updateHook tbl db) putStrLn ("UPDATE "++(show updated)) doDelete :: String->P.WhereClause->Database->IO () doDelete tblname wc db=do [tbl]<-getTablesByName [tblname] db let translate=(forceJust "Column missing!") .(translateColumn [T.def tbl] ) let expand_where P.WhereAny=[] expand_where (P.WhereOp column op (P.ExprV val))=let (t,c,_, p)=translate column in if DT.compatiblePV p val then [R.GeneralWhereClause (\r->applyOp op ((DT.fields r) ! c) val)] else [R.WhereNotCompatiblePV t c] expand_where (P.WhereOp c1 op (P.ExprC c2))= let (t1, ci1, i1, p1)=translate c1 (t2, ci2, i2, p2)=translate c2 in if DT.compatiblePP p1 p2 then if t1==t2 then [R.GeneralWhereClause (\r->applyOp op ((DT.fields r) ! ci1) ((DT.fields r) ! ci2))] else [R.GeneralWhereClause (\r->applyOp op ((DT.fields r) ! i1) ((DT.fields r) ! i2))] else [R.WhereNotCompatiblePP t1 ci1 t2 ci2] expand_where (P.WhereIsNull column isnull)=let (t, c, _, _)=translate column in [R.GeneralWhereClause (\r->(DT.isNull ((DT.fields r)!c))==isnull)] expand_where (P.WhereAnd a b)=(expand_where a)++(expand_where b) let compiled_where=expand_where wc mapM_ R.assertCompileError compiled_where let eval_where rc (R.GeneralWhereClause pred)=pred rc let deleter rc=let pass w=eval_where rc w in foldr (&&) True (map pass compiled_where) deleted<-T.delete tbl deleter (deleteHook tbl db) putStrLn ("DELETE "++(show deleted)) describeTable :: String->Database->IO() describeTable tblname db=do [tbl]<-getTablesByName [tblname] db print $ T.def tbl compileUpdate stmt db = return ( ) compileDelete stmt db = return ( ) data Database = Database { file : : Han } createDatabase : : ( )
1f4405c990e150a0200a27f697c9c017e8ac5a5a6c033bf31f799cb830b065fd
pirapira/coq2rust
redops.ml
(************************************************************************) v * The Coq Proof Assistant / The Coq Development Team < O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2012 \VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * (* // * This file is distributed under the terms of the *) (* * GNU Lesser General Public License Version 2.1 *) (************************************************************************) open Genredexpr FIXME let make_red_flag l = let rec add_flag red = function | [] -> red | FBeta :: lf -> add_flag { red with rBeta = true } lf | FIota :: lf -> add_flag { red with rIota = true } lf | FZeta :: lf -> add_flag { red with rZeta = true } lf | FConst l :: lf -> if red.rDelta then Errors.error "Cannot set both constants to unfold and constants not to unfold"; add_flag { red with rConst = union_consts red.rConst l } lf | FDeltaBut l :: lf -> if red.rConst <> [] && not red.rDelta then Errors.error "Cannot set both constants to unfold and constants not to unfold"; add_flag { red with rConst = union_consts red.rConst l; rDelta = true } lf in add_flag {rBeta = false; rIota = false; rZeta = false; rDelta = false; rConst = []} l let all_flags = {rBeta = true; rIota = true; rZeta = true; rDelta = true; rConst = []}
null
https://raw.githubusercontent.com/pirapira/coq2rust/22e8aaefc723bfb324ca2001b2b8e51fcc923543/pretyping/redops.ml
ocaml
********************************************************************** // * This file is distributed under the terms of the * GNU Lesser General Public License Version 2.1 **********************************************************************
v * The Coq Proof Assistant / The Coq Development Team < O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2012 \VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * open Genredexpr FIXME let make_red_flag l = let rec add_flag red = function | [] -> red | FBeta :: lf -> add_flag { red with rBeta = true } lf | FIota :: lf -> add_flag { red with rIota = true } lf | FZeta :: lf -> add_flag { red with rZeta = true } lf | FConst l :: lf -> if red.rDelta then Errors.error "Cannot set both constants to unfold and constants not to unfold"; add_flag { red with rConst = union_consts red.rConst l } lf | FDeltaBut l :: lf -> if red.rConst <> [] && not red.rDelta then Errors.error "Cannot set both constants to unfold and constants not to unfold"; add_flag { red with rConst = union_consts red.rConst l; rDelta = true } lf in add_flag {rBeta = false; rIota = false; rZeta = false; rDelta = false; rConst = []} l let all_flags = {rBeta = true; rIota = true; rZeta = true; rDelta = true; rConst = []}
bf64163be547a99f04abb87f58221f74a5dd954d503786a8a4836deea8032ac3
samrushing/irken-compiler
t37.scm
(define (+ a b) (%%cexp (int int -> int) "%0+%1" a b)) (define (thing r) (let ((x r.x) (z r.z) ) (+ x z))) (thing {x=1 z=3})
null
https://raw.githubusercontent.com/samrushing/irken-compiler/690da48852d55497f873738df54f14e8e135d006/tests/t37.scm
scheme
(define (+ a b) (%%cexp (int int -> int) "%0+%1" a b)) (define (thing r) (let ((x r.x) (z r.z) ) (+ x z))) (thing {x=1 z=3})
348ad0635dfd2d191a571bbf5f633b55b3b4c5f3eb2ad0b318ff8cf91ad41ca6
upenn-cis1xx/camelot
equality.ml
open Canonical open Utils open Astutils open Check (** ------------------ Checks rules: if (_ = [literals] | [literals] = _) ----------------------- *) module EqList : EXPRCHECK = struct type ctxt = Parsetree.expression_desc Pctxt.pctxt let fix = "using a pattern match to check whether a list has a certain value" let violation = "using `=` with lists as a condition in an if statement" let check st (E {location; source; pattern}: ctxt) = begin match pattern with | Pexp_ifthenelse (cond, _, _) -> begin match cond.pexp_desc with | Pexp_apply (application, [(_,lop); (_,rop)]) -> if application =~ "=" && (is_list_lit lop || is_list_lit rop) then st := Hint.mk_hint location source fix violation :: !st | _ -> () end | _ -> () end let name = "EqList", check end (** ------------------ Checks rules: _ = [None] | [None] = _ ------------- *) module EqOption : EXPRCHECK = struct type ctxt = Parsetree.expression_desc Pctxt.pctxt let fix = "using a pattern match to check the presence of an option" let violation = "using `=` with options" let check st (E {location; source; pattern}: ctxt) = begin match pattern with | Pexp_apply (application, [(_, lop); (_, rop)]) -> if application =~ "=" && (is_some_lit lop || is_some_lit rop) then st := Hint.mk_hint location source fix violation :: !st | _ -> () end let name = "EqOption", check end (** ------------------ Checks rules: (_ = :bool | :bool = _) ----------------------- *) module EqBool : EXPRCHECK = struct type ctxt = Parsetree.expression_desc Pctxt.pctxt let fix = "using the variable itself to represent the value" let violation = "using `=` with a boolean literal" let check st (E {location; source; pattern}: ctxt) = begin match pattern with | Pexp_apply (application, [(_,lop); (_,rop)]) -> if application =~ "=" && (is_bool_lit lop || is_bool_lit rop) then st := Hint.mk_hint location source fix violation :: !st | _ -> () end let name = "EqBool", check end
null
https://raw.githubusercontent.com/upenn-cis1xx/camelot/2d7e8db8abb8c1ad8187bfeb94499fe1746bb664/lib/style/equality.ml
ocaml
* ------------------ Checks rules: if (_ = [literals] | [literals] = _) ----------------------- * ------------------ Checks rules: _ = [None] | [None] = _ ------------- * ------------------ Checks rules: (_ = :bool | :bool = _) -----------------------
open Canonical open Utils open Astutils open Check module EqList : EXPRCHECK = struct type ctxt = Parsetree.expression_desc Pctxt.pctxt let fix = "using a pattern match to check whether a list has a certain value" let violation = "using `=` with lists as a condition in an if statement" let check st (E {location; source; pattern}: ctxt) = begin match pattern with | Pexp_ifthenelse (cond, _, _) -> begin match cond.pexp_desc with | Pexp_apply (application, [(_,lop); (_,rop)]) -> if application =~ "=" && (is_list_lit lop || is_list_lit rop) then st := Hint.mk_hint location source fix violation :: !st | _ -> () end | _ -> () end let name = "EqList", check end module EqOption : EXPRCHECK = struct type ctxt = Parsetree.expression_desc Pctxt.pctxt let fix = "using a pattern match to check the presence of an option" let violation = "using `=` with options" let check st (E {location; source; pattern}: ctxt) = begin match pattern with | Pexp_apply (application, [(_, lop); (_, rop)]) -> if application =~ "=" && (is_some_lit lop || is_some_lit rop) then st := Hint.mk_hint location source fix violation :: !st | _ -> () end let name = "EqOption", check end module EqBool : EXPRCHECK = struct type ctxt = Parsetree.expression_desc Pctxt.pctxt let fix = "using the variable itself to represent the value" let violation = "using `=` with a boolean literal" let check st (E {location; source; pattern}: ctxt) = begin match pattern with | Pexp_apply (application, [(_,lop); (_,rop)]) -> if application =~ "=" && (is_bool_lit lop || is_bool_lit rop) then st := Hint.mk_hint location source fix violation :: !st | _ -> () end let name = "EqBool", check end
16a44cc45a3122f7e771f83b0147fcb6651e87ebcd357dbe44d9922aebc7c5ad
clojure-interop/google-cloud-clients
LogEntry.clj
(ns com.google.cloud.logging.LogEntry "A Stackdriver Logging log entry. All log entries are represented via objects of this class. Log entries can have different type of payloads: an UTF-8 string (see Payload.StringPayload), a JSON object (see Payload.JsonPayload, or a protobuf object (see Payload.ProtoPayload). Entries can also store additional information about the operation or the HTTP request that generated the log (see getOperation() and getHttpRequest(), respectively)." (:refer-clojure :only [require comment defn ->]) (:import [com.google.cloud.logging LogEntry])) (defn *new-builder "Returns a builder for LogEntry objects given the entry payload. payload - `com.google.cloud.logging.Payload` returns: `com.google.cloud.logging.LogEntry$Builder`" (^com.google.cloud.logging.LogEntry$Builder [^com.google.cloud.logging.Payload payload] (LogEntry/newBuilder payload))) (defn *of "Creates a LogEntry object given the log name, the monitored resource and the entry payload. log-name - `java.lang.String` resource - `com.google.cloud.MonitoredResource` payload - `com.google.cloud.logging.Payload` returns: `com.google.cloud.logging.LogEntry`" (^com.google.cloud.logging.LogEntry [^java.lang.String log-name ^com.google.cloud.MonitoredResource resource ^com.google.cloud.logging.Payload payload] (LogEntry/of log-name resource payload)) (^com.google.cloud.logging.LogEntry [^com.google.cloud.logging.Payload payload] (LogEntry/of payload))) (defn get-trace "Returns the resource name of the trace associated with the log entry, if any. If it contains a relative resource name, the name is assumed to be relative to `//tracing.googleapis.com`. returns: `java.lang.String`" (^java.lang.String [^LogEntry this] (-> this (.getTrace)))) (defn get-resource "Returns the monitored resource associated with this log entry. Example: a log entry that reports a database error would be associated with the monitored resource designating the particular database that reported the error. returns: `com.google.cloud.MonitoredResource`" (^com.google.cloud.MonitoredResource [^LogEntry this] (-> this (.getResource)))) (defn get-severity "Returns the severity of the log entry. If not set, Severity.DEFAULT is used. returns: `com.google.cloud.logging.Severity`" (^com.google.cloud.logging.Severity [^LogEntry this] (-> this (.getSeverity)))) (defn get-timestamp "Returns the time at which the event described by the log entry occurred, in milliseconds. If omitted, the Logging service will use the time at which the log entry is received. returns: `java.lang.Long`" (^java.lang.Long [^LogEntry this] (-> this (.getTimestamp)))) (defn to-string "returns: `java.lang.String`" (^java.lang.String [^LogEntry this] (-> this (.toString)))) (defn get-payload "Returns the payload for this log entry. The log entry payload can be an UTF-8 string (see Payload.StringPayload), a JSON object (see Payload.JsonPayload, or a protobuf object (see Payload.ProtoPayload). returns: `<T extends com.google.cloud.logging.Payload> T`" ([^LogEntry this] (-> this (.getPayload)))) (defn get-trace-sampled? "Returns the sampling decision of the trace span associated with the log entry, or false if there is no trace span. returns: `boolean`" (^Boolean [^LogEntry this] (-> this (.getTraceSampled)))) (defn get-span-id "Returns the ID of the trace span associated with the log entry, if any. returns: `java.lang.String`" (^java.lang.String [^LogEntry this] (-> this (.getSpanId)))) (defn get-labels "Returns an optional set of user-defined (key, value) data that provides additional information about the log entry. returns: `java.util.Map<java.lang.String,java.lang.String>`" (^java.util.Map [^LogEntry this] (-> this (.getLabels)))) (defn get-receive-timestamp "Returns the time the log entry was received by Stackdriver Logging. returns: `java.lang.Long`" (^java.lang.Long [^LogEntry this] (-> this (.getReceiveTimestamp)))) (defn get-http-request "Returns information about the HTTP request associated with this log entry, if applicable. returns: `com.google.cloud.logging.HttpRequest`" (^com.google.cloud.logging.HttpRequest [^LogEntry this] (-> this (.getHttpRequest)))) (defn hash-code "returns: `int`" (^Integer [^LogEntry this] (-> this (.hashCode)))) (defn get-operation "Returns information about an operation associated with the log entry, if applicable. returns: `com.google.cloud.logging.Operation`" (^com.google.cloud.logging.Operation [^LogEntry this] (-> this (.getOperation)))) (defn get-log-name "Returns the name of the log to which this log entry belongs. The log name must be less than 512 characters long and can only include the following characters: upper and lower case alphanumeric characters: [A-Za-z0-9]; and punctuation characters: _-./. The forward-slash (/) characters in the log name must be URL-encoded. Examples: syslog, library.googleapis.com%2Fbook_log. returns: `java.lang.String`" (^java.lang.String [^LogEntry this] (-> this (.getLogName)))) (defn equals "obj - `java.lang.Object` returns: `boolean`" (^Boolean [^LogEntry this ^java.lang.Object obj] (-> this (.equals obj)))) (defn get-insert-id "Returns a unique ID for the log entry. The Logging service considers other log entries in the same log with the same ID as duplicates which can be removed. returns: `java.lang.String`" (^java.lang.String [^LogEntry this] (-> this (.getInsertId)))) (defn to-builder "Returns a Builder for this log entry. returns: `com.google.cloud.logging.LogEntry$Builder`" (^com.google.cloud.logging.LogEntry$Builder [^LogEntry this] (-> this (.toBuilder)))) (defn get-source-location "Returns the source code location information associated with the log entry, if any. returns: `com.google.cloud.logging.SourceLocation`" (^com.google.cloud.logging.SourceLocation [^LogEntry this] (-> this (.getSourceLocation))))
null
https://raw.githubusercontent.com/clojure-interop/google-cloud-clients/80852d0496057c22f9cdc86d6f9ffc0fa3cd7904/com.google.cloud.logging/src/com/google/cloud/logging/LogEntry.clj
clojure
and punctuation characters: _-./. The
(ns com.google.cloud.logging.LogEntry "A Stackdriver Logging log entry. All log entries are represented via objects of this class. Log entries can have different type of payloads: an UTF-8 string (see Payload.StringPayload), a JSON object (see Payload.JsonPayload, or a protobuf object (see Payload.ProtoPayload). Entries can also store additional information about the operation or the HTTP request that generated the log (see getOperation() and getHttpRequest(), respectively)." (:refer-clojure :only [require comment defn ->]) (:import [com.google.cloud.logging LogEntry])) (defn *new-builder "Returns a builder for LogEntry objects given the entry payload. payload - `com.google.cloud.logging.Payload` returns: `com.google.cloud.logging.LogEntry$Builder`" (^com.google.cloud.logging.LogEntry$Builder [^com.google.cloud.logging.Payload payload] (LogEntry/newBuilder payload))) (defn *of "Creates a LogEntry object given the log name, the monitored resource and the entry payload. log-name - `java.lang.String` resource - `com.google.cloud.MonitoredResource` payload - `com.google.cloud.logging.Payload` returns: `com.google.cloud.logging.LogEntry`" (^com.google.cloud.logging.LogEntry [^java.lang.String log-name ^com.google.cloud.MonitoredResource resource ^com.google.cloud.logging.Payload payload] (LogEntry/of log-name resource payload)) (^com.google.cloud.logging.LogEntry [^com.google.cloud.logging.Payload payload] (LogEntry/of payload))) (defn get-trace "Returns the resource name of the trace associated with the log entry, if any. If it contains a relative resource name, the name is assumed to be relative to `//tracing.googleapis.com`. returns: `java.lang.String`" (^java.lang.String [^LogEntry this] (-> this (.getTrace)))) (defn get-resource "Returns the monitored resource associated with this log entry. Example: a log entry that reports a database error would be associated with the monitored resource designating the particular database that reported the error. returns: `com.google.cloud.MonitoredResource`" (^com.google.cloud.MonitoredResource [^LogEntry this] (-> this (.getResource)))) (defn get-severity "Returns the severity of the log entry. If not set, Severity.DEFAULT is used. returns: `com.google.cloud.logging.Severity`" (^com.google.cloud.logging.Severity [^LogEntry this] (-> this (.getSeverity)))) (defn get-timestamp "Returns the time at which the event described by the log entry occurred, in milliseconds. If omitted, the Logging service will use the time at which the log entry is received. returns: `java.lang.Long`" (^java.lang.Long [^LogEntry this] (-> this (.getTimestamp)))) (defn to-string "returns: `java.lang.String`" (^java.lang.String [^LogEntry this] (-> this (.toString)))) (defn get-payload "Returns the payload for this log entry. The log entry payload can be an UTF-8 string (see Payload.StringPayload), a JSON object (see Payload.JsonPayload, or a protobuf object (see Payload.ProtoPayload). returns: `<T extends com.google.cloud.logging.Payload> T`" ([^LogEntry this] (-> this (.getPayload)))) (defn get-trace-sampled? "Returns the sampling decision of the trace span associated with the log entry, or false if there is no trace span. returns: `boolean`" (^Boolean [^LogEntry this] (-> this (.getTraceSampled)))) (defn get-span-id "Returns the ID of the trace span associated with the log entry, if any. returns: `java.lang.String`" (^java.lang.String [^LogEntry this] (-> this (.getSpanId)))) (defn get-labels "Returns an optional set of user-defined (key, value) data that provides additional information about the log entry. returns: `java.util.Map<java.lang.String,java.lang.String>`" (^java.util.Map [^LogEntry this] (-> this (.getLabels)))) (defn get-receive-timestamp "Returns the time the log entry was received by Stackdriver Logging. returns: `java.lang.Long`" (^java.lang.Long [^LogEntry this] (-> this (.getReceiveTimestamp)))) (defn get-http-request "Returns information about the HTTP request associated with this log entry, if applicable. returns: `com.google.cloud.logging.HttpRequest`" (^com.google.cloud.logging.HttpRequest [^LogEntry this] (-> this (.getHttpRequest)))) (defn hash-code "returns: `int`" (^Integer [^LogEntry this] (-> this (.hashCode)))) (defn get-operation "Returns information about an operation associated with the log entry, if applicable. returns: `com.google.cloud.logging.Operation`" (^com.google.cloud.logging.Operation [^LogEntry this] (-> this (.getOperation)))) (defn get-log-name "Returns the name of the log to which this log entry belongs. The log name must be less than 512 characters long and can only include the following characters: upper and lower case forward-slash (/) characters in the log name must be URL-encoded. Examples: syslog, library.googleapis.com%2Fbook_log. returns: `java.lang.String`" (^java.lang.String [^LogEntry this] (-> this (.getLogName)))) (defn equals "obj - `java.lang.Object` returns: `boolean`" (^Boolean [^LogEntry this ^java.lang.Object obj] (-> this (.equals obj)))) (defn get-insert-id "Returns a unique ID for the log entry. The Logging service considers other log entries in the same log with the same ID as duplicates which can be removed. returns: `java.lang.String`" (^java.lang.String [^LogEntry this] (-> this (.getInsertId)))) (defn to-builder "Returns a Builder for this log entry. returns: `com.google.cloud.logging.LogEntry$Builder`" (^com.google.cloud.logging.LogEntry$Builder [^LogEntry this] (-> this (.toBuilder)))) (defn get-source-location "Returns the source code location information associated with the log entry, if any. returns: `com.google.cloud.logging.SourceLocation`" (^com.google.cloud.logging.SourceLocation [^LogEntry this] (-> this (.getSourceLocation))))
74bf9e1874a2b9945491e9e4a83b7e7a2da1ee8ac4b76b3f8b1be396f53fe56b
chpatrick/codec
Codec.hs
module Data.Binary.Codec ( -- * Binary codecs BinaryCodec , byteString , word8 , word16be, word16le, word16host , word32be, word32le, word32host , word64be, word64le, word64host , wordhost , int8 , int16be, int16le, int16host , int32be, int32le, int32host , int64be, int64le, int64host , inthost ) where import Control.Monad.Codec import qualified Data.ByteString as BS import Data.Binary.Get import Data.Binary.Put import Data.Int import Data.Word type BinaryCodec a = Codec Get PutM a -- | Get/put an n-byte field. byteString :: Int -> BinaryCodec BS.ByteString byteString n = Codec { codecIn = getByteString n , codecOut = \bs -> if BS.length bs == n then bs <$ putByteString bs else fail $ "Expected a ByteString of size " ++ show n } word8 :: BinaryCodec Word8 word8 = Codec getWord8 (fmapArg putWord8) word16be :: BinaryCodec Word16 word16be = Codec getWord16be (fmapArg putWord16be) word16le :: BinaryCodec Word16 word16le = Codec getWord16le (fmapArg putWord16le) word16host :: BinaryCodec Word16 word16host = Codec getWord16host (fmapArg putWord16host) word32be :: BinaryCodec Word32 word32be = Codec getWord32be (fmapArg putWord32be) word32le :: BinaryCodec Word32 word32le = Codec getWord32le (fmapArg putWord32le) word32host :: BinaryCodec Word32 word32host = Codec getWord32host (fmapArg putWord32host) word64be :: BinaryCodec Word64 word64be = Codec getWord64be (fmapArg putWord64be) word64le :: BinaryCodec Word64 word64le = Codec getWord64le (fmapArg putWord64le) word64host :: BinaryCodec Word64 word64host = Codec getWord64host (fmapArg putWord64host) wordhost :: BinaryCodec Word wordhost = Codec getWordhost (fmapArg putWordhost) int8 :: BinaryCodec Int8 int8 = Codec getInt8 (fmapArg putInt8) int16be :: BinaryCodec Int16 int16be = Codec getInt16be (fmapArg putInt16be) int16le :: BinaryCodec Int16 int16le = Codec getInt16le (fmapArg putInt16le) int16host :: BinaryCodec Int16 int16host = Codec getInt16host (fmapArg putInt16host) int32be :: BinaryCodec Int32 int32be = Codec getInt32be (fmapArg putInt32be) int32le :: BinaryCodec Int32 int32le = Codec getInt32le (fmapArg putInt32le) int32host :: BinaryCodec Int32 int32host = Codec getInt32host (fmapArg putInt32host) int64be :: BinaryCodec Int64 int64be = Codec getInt64be (fmapArg putInt64be) int64le :: BinaryCodec Int64 int64le = Codec getInt64le (fmapArg putInt64le) int64host :: BinaryCodec Int64 int64host = Codec getInt64host (fmapArg putInt64host) inthost :: BinaryCodec Int inthost = Codec getInthost (fmapArg putInthost)
null
https://raw.githubusercontent.com/chpatrick/codec/0faf37a1cefb21dc46cc2857e538dd983bb28652/src/Data/Binary/Codec.hs
haskell
* Binary codecs | Get/put an n-byte field.
module Data.Binary.Codec ( BinaryCodec , byteString , word8 , word16be, word16le, word16host , word32be, word32le, word32host , word64be, word64le, word64host , wordhost , int8 , int16be, int16le, int16host , int32be, int32le, int32host , int64be, int64le, int64host , inthost ) where import Control.Monad.Codec import qualified Data.ByteString as BS import Data.Binary.Get import Data.Binary.Put import Data.Int import Data.Word type BinaryCodec a = Codec Get PutM a byteString :: Int -> BinaryCodec BS.ByteString byteString n = Codec { codecIn = getByteString n , codecOut = \bs -> if BS.length bs == n then bs <$ putByteString bs else fail $ "Expected a ByteString of size " ++ show n } word8 :: BinaryCodec Word8 word8 = Codec getWord8 (fmapArg putWord8) word16be :: BinaryCodec Word16 word16be = Codec getWord16be (fmapArg putWord16be) word16le :: BinaryCodec Word16 word16le = Codec getWord16le (fmapArg putWord16le) word16host :: BinaryCodec Word16 word16host = Codec getWord16host (fmapArg putWord16host) word32be :: BinaryCodec Word32 word32be = Codec getWord32be (fmapArg putWord32be) word32le :: BinaryCodec Word32 word32le = Codec getWord32le (fmapArg putWord32le) word32host :: BinaryCodec Word32 word32host = Codec getWord32host (fmapArg putWord32host) word64be :: BinaryCodec Word64 word64be = Codec getWord64be (fmapArg putWord64be) word64le :: BinaryCodec Word64 word64le = Codec getWord64le (fmapArg putWord64le) word64host :: BinaryCodec Word64 word64host = Codec getWord64host (fmapArg putWord64host) wordhost :: BinaryCodec Word wordhost = Codec getWordhost (fmapArg putWordhost) int8 :: BinaryCodec Int8 int8 = Codec getInt8 (fmapArg putInt8) int16be :: BinaryCodec Int16 int16be = Codec getInt16be (fmapArg putInt16be) int16le :: BinaryCodec Int16 int16le = Codec getInt16le (fmapArg putInt16le) int16host :: BinaryCodec Int16 int16host = Codec getInt16host (fmapArg putInt16host) int32be :: BinaryCodec Int32 int32be = Codec getInt32be (fmapArg putInt32be) int32le :: BinaryCodec Int32 int32le = Codec getInt32le (fmapArg putInt32le) int32host :: BinaryCodec Int32 int32host = Codec getInt32host (fmapArg putInt32host) int64be :: BinaryCodec Int64 int64be = Codec getInt64be (fmapArg putInt64be) int64le :: BinaryCodec Int64 int64le = Codec getInt64le (fmapArg putInt64le) int64host :: BinaryCodec Int64 int64host = Codec getInt64host (fmapArg putInt64host) inthost :: BinaryCodec Int inthost = Codec getInthost (fmapArg putInthost)
e1cc66f75970a320ea32987829a86cfc5c4fef9d8671e13efe8ede19d2854557
johnyob/dromedary
test_pr7381.ml
open! Import open Util let%expect_test "" = let str = {| type ('a, 'b) eq = | Refl constraint 'a = 'b ;; external hole : 'a. 'a = "%hole";; let (type 't) f = fun (t1 : (int, 't) eq) (t2 : (string, 't) eq) -> match (t1, t2) with ( (Refl, Refl) -> hole ) ;; |} in print_infer_result str; [%expect {| "Inconsistent equations added by local branches" |}] let%expect_test "" = let str = {| type ('a, 'b) eq = | Refl constraint 'a = 'b ;; external hole : 'a. 'a = "%hole";; type 'a option = | None | Some of 'a ;; let (type 't) f = fun (t : ((int, 't) eq * (string, 't) eq) option) -> match t with ( None -> () ) ;; |} in print_infer_result str; [%expect {| Structure: └──Structure: └──Structure item: Type └──Type declaration: └──Type name: eq └──Type declaration kind: Variant └──Constructor declaration: └──Constructor name: Refl └──Constructor alphas: 53 54 └──Constructor type: └──Type expr: Constructor: eq └──Type expr: Variable: 53 └──Type expr: Variable: 54 └──Constraint: └──Type expr: Variable: 53 └──Type expr: Variable: 54 └──Structure item: Primitive └──Value description: └──Name: hole └──Scheme: └──Variables: 0 └──Type expr: Variable: 0 └──Primitive name: %hole └──Structure item: Type └──Type declaration: └──Type name: option └──Type declaration kind: Variant └──Constructor declaration: └──Constructor name: None └──Constructor alphas: 56 └──Constructor type: └──Type expr: Constructor: option └──Type expr: Variable: 56 └──Constructor declaration: └──Constructor name: Some └──Constructor alphas: 56 └──Constructor type: └──Type expr: Constructor: option └──Type expr: Variable: 56 └──Constructor argument: └──Constructor betas: └──Type expr: Variable: 56 └──Structure item: Let └──Value bindings: └──Value binding: └──Pattern: └──Type expr: Arrow └──Type expr: Constructor: option └──Type expr: Tuple └──Type expr: Constructor: eq └──Type expr: Constructor: int └──Type expr: Variable: 31 └──Type expr: Constructor: eq └──Type expr: Constructor: string └──Type expr: Variable: 31 └──Type expr: Constructor: unit └──Desc: Variable: f └──Abstraction: └──Variables: 31 └──Expression: └──Type expr: Arrow └──Type expr: Constructor: option └──Type expr: Tuple └──Type expr: Constructor: eq └──Type expr: Constructor: int └──Type expr: Variable: 31 └──Type expr: Constructor: eq └──Type expr: Constructor: string └──Type expr: Variable: 31 └──Type expr: Constructor: unit └──Desc: Function └──Pattern: └──Type expr: Constructor: option └──Type expr: Tuple └──Type expr: Constructor: eq └──Type expr: Constructor: int └──Type expr: Variable: 31 └──Type expr: Constructor: eq └──Type expr: Constructor: string └──Type expr: Variable: 31 └──Desc: Variable: t └──Expression: └──Type expr: Constructor: unit └──Desc: Match └──Expression: └──Type expr: Constructor: option └──Type expr: Tuple └──Type expr: Constructor: eq └──Type expr: Constructor: int └──Type expr: Variable: 31 └──Type expr: Constructor: eq └──Type expr: Constructor: string └──Type expr: Variable: 31 └──Desc: Variable └──Variable: t └──Type expr: Constructor: option └──Type expr: Tuple └──Type expr: Constructor: eq └──Type expr: Constructor: int └──Type expr: Variable: 31 └──Type expr: Constructor: eq └──Type expr: Constructor: string └──Type expr: Variable: 31 └──Cases: └──Case: └──Pattern: └──Type expr: Constructor: option └──Type expr: Tuple └──Type expr: Constructor: eq └──Type expr: Constructor: int └──Type expr: Variable: 31 └──Type expr: Constructor: eq └──Type expr: Constructor: string └──Type expr: Variable: 31 └──Desc: Construct └──Constructor description: └──Name: None └──Constructor type: └──Type expr: Constructor: option └──Type expr: Tuple └──Type expr: Constructor: eq └──Type expr: Constructor: int └──Type expr: Variable: 31 └──Type expr: Constructor: eq └──Type expr: Constructor: string └──Type expr: Variable: 31 └──Expression: └──Type expr: Constructor: unit └──Desc: Constant: () |}]
null
https://raw.githubusercontent.com/johnyob/dromedary/a9359321492ff5c38c143385513e673d8d1f05a4/test/typing/gadts/test_pr7381.ml
ocaml
open! Import open Util let%expect_test "" = let str = {| type ('a, 'b) eq = | Refl constraint 'a = 'b ;; external hole : 'a. 'a = "%hole";; let (type 't) f = fun (t1 : (int, 't) eq) (t2 : (string, 't) eq) -> match (t1, t2) with ( (Refl, Refl) -> hole ) ;; |} in print_infer_result str; [%expect {| "Inconsistent equations added by local branches" |}] let%expect_test "" = let str = {| type ('a, 'b) eq = | Refl constraint 'a = 'b ;; external hole : 'a. 'a = "%hole";; type 'a option = | None | Some of 'a ;; let (type 't) f = fun (t : ((int, 't) eq * (string, 't) eq) option) -> match t with ( None -> () ) ;; |} in print_infer_result str; [%expect {| Structure: └──Structure: └──Structure item: Type └──Type declaration: └──Type name: eq └──Type declaration kind: Variant └──Constructor declaration: └──Constructor name: Refl └──Constructor alphas: 53 54 └──Constructor type: └──Type expr: Constructor: eq └──Type expr: Variable: 53 └──Type expr: Variable: 54 └──Constraint: └──Type expr: Variable: 53 └──Type expr: Variable: 54 └──Structure item: Primitive └──Value description: └──Name: hole └──Scheme: └──Variables: 0 └──Type expr: Variable: 0 └──Primitive name: %hole └──Structure item: Type └──Type declaration: └──Type name: option └──Type declaration kind: Variant └──Constructor declaration: └──Constructor name: None └──Constructor alphas: 56 └──Constructor type: └──Type expr: Constructor: option └──Type expr: Variable: 56 └──Constructor declaration: └──Constructor name: Some └──Constructor alphas: 56 └──Constructor type: └──Type expr: Constructor: option └──Type expr: Variable: 56 └──Constructor argument: └──Constructor betas: └──Type expr: Variable: 56 └──Structure item: Let └──Value bindings: └──Value binding: └──Pattern: └──Type expr: Arrow └──Type expr: Constructor: option └──Type expr: Tuple └──Type expr: Constructor: eq └──Type expr: Constructor: int └──Type expr: Variable: 31 └──Type expr: Constructor: eq └──Type expr: Constructor: string └──Type expr: Variable: 31 └──Type expr: Constructor: unit └──Desc: Variable: f └──Abstraction: └──Variables: 31 └──Expression: └──Type expr: Arrow └──Type expr: Constructor: option └──Type expr: Tuple └──Type expr: Constructor: eq └──Type expr: Constructor: int └──Type expr: Variable: 31 └──Type expr: Constructor: eq └──Type expr: Constructor: string └──Type expr: Variable: 31 └──Type expr: Constructor: unit └──Desc: Function └──Pattern: └──Type expr: Constructor: option └──Type expr: Tuple └──Type expr: Constructor: eq └──Type expr: Constructor: int └──Type expr: Variable: 31 └──Type expr: Constructor: eq └──Type expr: Constructor: string └──Type expr: Variable: 31 └──Desc: Variable: t └──Expression: └──Type expr: Constructor: unit └──Desc: Match └──Expression: └──Type expr: Constructor: option └──Type expr: Tuple └──Type expr: Constructor: eq └──Type expr: Constructor: int └──Type expr: Variable: 31 └──Type expr: Constructor: eq └──Type expr: Constructor: string └──Type expr: Variable: 31 └──Desc: Variable └──Variable: t └──Type expr: Constructor: option └──Type expr: Tuple └──Type expr: Constructor: eq └──Type expr: Constructor: int └──Type expr: Variable: 31 └──Type expr: Constructor: eq └──Type expr: Constructor: string └──Type expr: Variable: 31 └──Cases: └──Case: └──Pattern: └──Type expr: Constructor: option └──Type expr: Tuple └──Type expr: Constructor: eq └──Type expr: Constructor: int └──Type expr: Variable: 31 └──Type expr: Constructor: eq └──Type expr: Constructor: string └──Type expr: Variable: 31 └──Desc: Construct └──Constructor description: └──Name: None └──Constructor type: └──Type expr: Constructor: option └──Type expr: Tuple └──Type expr: Constructor: eq └──Type expr: Constructor: int └──Type expr: Variable: 31 └──Type expr: Constructor: eq └──Type expr: Constructor: string └──Type expr: Variable: 31 └──Expression: └──Type expr: Constructor: unit └──Desc: Constant: () |}]
f14251585a59c1ba6cf0ff5f5f2937e2f34b9eaf034cfb64156f6422745b9d4e
AndrasKovacs/setoidtt
Unlifted.hs
module Data.Unlifted where | Class for types that can be represented as elements of TYPE ' UnliftedRep . NOTE : this module is unsound to use in FFI : Do not pass any data to FFI which contains some unlifted value coerced to a different unlifted type ! NOTE: this module is unsound to use in FFI: Do not pass any data to FFI which contains some unlifted value coerced to a different unlifted type! -} import GHC.Prim import GHC.Types writeUnlifted# :: forall (a :: TYPE 'UnliftedRep) s. MutableArrayArray# s -> Int# -> a -> State# s -> State# s writeUnlifted# marr i a s = writeArrayArrayArray# marr i (unsafeCoerce# a) s # inline writeUnlifted # # readUnlifted# :: forall (a :: TYPE 'UnliftedRep) s. MutableArrayArray# s -> Int# -> State# s -> (# State# s, a #) readUnlifted# marr i s = unsafeCoerce# (readArrayArrayArray# marr i s) # inline readUnlifted # # indexUnlifted# :: forall (a :: TYPE 'UnliftedRep). ArrayArray# -> Int# -> a indexUnlifted# arr i = unsafeCoerce# (indexArrayArrayArray# arr i) {-# inline indexUnlifted# #-} setUnlifted# :: forall (a :: TYPE 'UnliftedRep) s. MutableArrayArray# s -> a -> State# s -> State# s setUnlifted# marr a s = let go :: MutableArrayArray# s -> a -> State# s -> Int# -> Int# -> State# s go marr a s l i = case i ==# l of 1# -> s _ -> case writeUnlifted# marr i a s of s -> go marr a s l (i +# 1#) in go marr a s (sizeofMutableArrayArray# marr) 0# # inline setUnlifted # # newUnlifted# :: forall (a :: TYPE 'UnliftedRep) s. Int# -> a -> State# s -> (# State# s, MutableArrayArray# s #) newUnlifted# i a s = case newArrayArray# i s of (# s, marr #) -> case setUnlifted# marr a s of s -> (# s, marr #) # inline newUnlifted # # class Unlifted (a :: *) where type Rep a :: TYPE 'UnliftedRep to# :: a -> Rep a from# :: Rep a -> a defaultElem :: a
null
https://raw.githubusercontent.com/AndrasKovacs/setoidtt/621aef2c4ae5a6acb418fa1153575b21e2dc48d2/setoidtt/primdata/Data/Unlifted.hs
haskell
# inline indexUnlifted# #
module Data.Unlifted where | Class for types that can be represented as elements of TYPE ' UnliftedRep . NOTE : this module is unsound to use in FFI : Do not pass any data to FFI which contains some unlifted value coerced to a different unlifted type ! NOTE: this module is unsound to use in FFI: Do not pass any data to FFI which contains some unlifted value coerced to a different unlifted type! -} import GHC.Prim import GHC.Types writeUnlifted# :: forall (a :: TYPE 'UnliftedRep) s. MutableArrayArray# s -> Int# -> a -> State# s -> State# s writeUnlifted# marr i a s = writeArrayArrayArray# marr i (unsafeCoerce# a) s # inline writeUnlifted # # readUnlifted# :: forall (a :: TYPE 'UnliftedRep) s. MutableArrayArray# s -> Int# -> State# s -> (# State# s, a #) readUnlifted# marr i s = unsafeCoerce# (readArrayArrayArray# marr i s) # inline readUnlifted # # indexUnlifted# :: forall (a :: TYPE 'UnliftedRep). ArrayArray# -> Int# -> a indexUnlifted# arr i = unsafeCoerce# (indexArrayArrayArray# arr i) setUnlifted# :: forall (a :: TYPE 'UnliftedRep) s. MutableArrayArray# s -> a -> State# s -> State# s setUnlifted# marr a s = let go :: MutableArrayArray# s -> a -> State# s -> Int# -> Int# -> State# s go marr a s l i = case i ==# l of 1# -> s _ -> case writeUnlifted# marr i a s of s -> go marr a s l (i +# 1#) in go marr a s (sizeofMutableArrayArray# marr) 0# # inline setUnlifted # # newUnlifted# :: forall (a :: TYPE 'UnliftedRep) s. Int# -> a -> State# s -> (# State# s, MutableArrayArray# s #) newUnlifted# i a s = case newArrayArray# i s of (# s, marr #) -> case setUnlifted# marr a s of s -> (# s, marr #) # inline newUnlifted # # class Unlifted (a :: *) where type Rep a :: TYPE 'UnliftedRep to# :: a -> Rep a from# :: Rep a -> a defaultElem :: a