_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
62eb513bfd208bd0bd1acb61b8e2d8ac6be51a74ffbfe0bf6b2f5a7d173f7768
turquoise-hexagon/euler
solution.scm
(import (chicken fixnum) (euler) (srfi 69)) (define (order n) (let loop ((i 1)) (let ((_ (fx* i 10))) (if (fx> _ n) i (loop _))))) (define (make-circular-prime? primes) (let ((acc (make-hash-table))) (for-each (lambda (_) (hash-table-set! acc _ #t)) primes) (define (circular-prime? n) (let ((_ (order n))) (let loop ((i n) (n n)) (if (fx= i 0) #t (if (hash-table-exists? acc n) (loop (fx/ i 10) (fx+ (fx* (fxmod n _) 10) (fx/ n _))) #f))))) circular-prime?)) (define (solve n) (let* ((primes (primes n)) (circular-prime? (make-circular-prime? primes))) (foldl (lambda (acc i) (if (circular-prime? i) (fx+ acc 1) acc)) 0 primes))) (let ((_ (solve #e1e6))) (print _) (assert (= _ 55)))
null
https://raw.githubusercontent.com/turquoise-hexagon/euler/346c4bc2e0cfe0afff41df9b040af77cdae91a74/src/035/solution.scm
scheme
(import (chicken fixnum) (euler) (srfi 69)) (define (order n) (let loop ((i 1)) (let ((_ (fx* i 10))) (if (fx> _ n) i (loop _))))) (define (make-circular-prime? primes) (let ((acc (make-hash-table))) (for-each (lambda (_) (hash-table-set! acc _ #t)) primes) (define (circular-prime? n) (let ((_ (order n))) (let loop ((i n) (n n)) (if (fx= i 0) #t (if (hash-table-exists? acc n) (loop (fx/ i 10) (fx+ (fx* (fxmod n _) 10) (fx/ n _))) #f))))) circular-prime?)) (define (solve n) (let* ((primes (primes n)) (circular-prime? (make-circular-prime? primes))) (foldl (lambda (acc i) (if (circular-prime? i) (fx+ acc 1) acc)) 0 primes))) (let ((_ (solve #e1e6))) (print _) (assert (= _ 55)))
35209b41d5b058cc92e52641829cd636bf876b7d9c2f0babf890684ff9ef26f1
juspay/euler-hs
DB.hs
{-# LANGUAGE DerivingStrategies #-} {-# LANGUAGE DeriveAnyClass #-} # LANGUAGE FunctionalDependencies # # LANGUAGE RecordWildCards # | Module : EulerHS.Core . Types . DB Copyright : ( C ) Juspay Technologies Pvt Ltd 2019 - 2022 License : Apache 2.0 ( see the file LICENSE ) Maintainer : Stability : experimental Portability : non - portable This module contains general DB - related types and helper functions . This module is internal and should not imported in the projects . Import ' EulerHS.Types ' instead . Types and helpers for specific databases can be found in separate modules : ' EulerHS.Core . Types . MySQL ' ' EulerHS.Core . Types . Postgres ' Module : EulerHS.Core.Types.DB Copyright : (C) Juspay Technologies Pvt Ltd 2019-2022 License : Apache 2.0 (see the file LICENSE) Maintainer : Stability : experimental Portability : non-portable This module contains general DB-related types and helper functions. This module is internal and should not imported in the projects. Import 'EulerHS.Types' instead. Types and helpers for specific databases can be found in separate modules: 'EulerHS.Core.Types.MySQL' 'EulerHS.Core.Types.Postgres' -} module EulerHS.Core.Types.DB ( -- * Core DB -- ** Types BeamRuntime(..) , deleteReturningListPG , updateReturningListPG , BeamRunner(..) , NativeSqlPool(..) , NativeSqlConn(..) , ConnTag , SQliteDBname , SqlConn(..) , DBConfig , PoolConfig(..) , DBErrorType(..) , DBError(..) , DBResult -- ** Methods , bemToNative , nativeToBem , mkSqlConn , mkSQLiteConfig , mkSQLitePoolConfig , mkPostgresConfig , mkPostgresPoolConfig , mkMySQLConfig , mkMySQLPoolConfig , getDBName -- ** Helpers , withTransaction , mysqlErrorToDbError , sqliteErrorToDbError , postgresErrorToDbError , PostgresSqlError(..) , PostgresExecStatus(..) , MysqlSqlError(..) , SqliteSqlError(..) , SqliteError(..) , SQLError(..) ) where import EulerHS.Prelude import qualified Data.Pool as DP import Data.Time.Clock (NominalDiffTime) import qualified Database.Beam as B import qualified Database.Beam.Backend.SQL as B import qualified Database.Beam.Backend.SQL.BeamExtensions as B import qualified Database.Beam.MySQL as BM import qualified Database.Beam.Postgres as BP import qualified Database.Beam.Sqlite as BS import qualified Database.Beam.Sqlite.Connection as SQLite import qualified Database.MySQL.Base as MySQL import qualified Database.PostgreSQL.Simple as PGS import qualified Database.SQLite.Simple as SQLite import EulerHS.Core.Types.MySQL (MySQLConfig(..), createMySQLConn) import EulerHS.Core.Types.Postgres (PostgresConfig(..), createPostgresConn) class (B.BeamSqlBackend be, B.MonadBeam be beM) => BeamRuntime be beM | be -> beM, beM -> be where rtSelectReturningList :: B.FromBackendRow be a => B.SqlSelect be a -> beM [a] rtSelectReturningOne :: B.FromBackendRow be a => B.SqlSelect be a -> beM (Maybe a) rtInsert :: B.SqlInsert be table -> beM () rtInsertReturningList :: forall table . (B.Beamable table, B.FromBackendRow be (table Identity)) => B.SqlInsert be table -> beM [table Identity] rtUpdate :: B.SqlUpdate be table -> beM () rtUpdateReturningList :: forall table. (B.Beamable table, B.FromBackendRow be (table Identity)) => B.SqlUpdate be table -> beM [table Identity] rtDelete :: B.SqlDelete be table -> beM () -- TODO: move somewhere (it's implementation) instance BeamRuntime BS.Sqlite BS.SqliteM where rtSelectReturningList = B.runSelectReturningList rtSelectReturningOne = B.runSelectReturningOne rtInsert = B.runInsert rtInsertReturningList = B.runInsertReturningList rtUpdate = B.runUpdate rtUpdateReturningList = error "Not implemented" rtDelete = B.runDelete -- TODO: move somewhere (it's implementation) instance BeamRuntime BP.Postgres BP.Pg where rtSelectReturningList = B.runSelectReturningList rtSelectReturningOne = B.runSelectReturningOne rtInsert = B.runInsert rtInsertReturningList = B.runInsertReturningList rtUpdate = B.runUpdate rtUpdateReturningList = updateReturningListPG rtDelete = B.runDelete deleteReturningListPG :: (B.Beamable table, B.FromBackendRow BP.Postgres (table Identity)) => B.SqlDelete BP.Postgres table -> BP.Pg [table Identity] deleteReturningListPG = B.runDeleteReturningList updateReturningListPG :: (B.Beamable table, B.FromBackendRow BP.Postgres (table Identity)) => B.SqlUpdate BP.Postgres table -> BP.Pg [table Identity] updateReturningListPG = B.runUpdateReturningList instance BeamRuntime BM.MySQL BM.MySQLM where rtSelectReturningList = B.runSelectReturningList rtSelectReturningOne = B.runSelectReturningOne rtInsert = B.runInsert rtInsertReturningList = error "Not implemented" rtUpdate = B.runUpdate rtUpdateReturningList = error "Not implemented" rtDelete = B.runDelete class BeamRunner beM where getBeamDebugRunner :: NativeSqlConn -> beM a -> ((Text -> IO ()) -> IO a) instance BeamRunner BS.SqliteM where getBeamDebugRunner (NativeSQLiteConn conn) beM = \logger -> SQLite.runBeamSqliteDebug logger conn beM getBeamDebugRunner _ _ = \_ -> error "Not a SQLite connection" instance BeamRunner BP.Pg where getBeamDebugRunner (NativePGConn conn) beM = \logger -> BP.runBeamPostgresDebug logger conn beM getBeamDebugRunner _ _ = \_ -> error "Not a Postgres connection" instance BeamRunner BM.MySQLM where getBeamDebugRunner (NativeMySQLConn conn) beM = \logger -> BM.runBeamMySQLDebug logger conn beM getBeamDebugRunner _ _ = \_ -> error "Not a MySQL connection" withTransaction :: forall beM a . SqlConn beM -> (NativeSqlConn -> IO a) -> IO (Either SomeException a) withTransaction conn f = tryAny $ case conn of MockedPool _ -> error "Mocked pool connections are not supported." PostgresPool _ pool -> DP.withResource pool (go PGS.withTransaction NativePGConn) MySQLPool _ pool -> DP.withResource pool (go MySQL.withTransaction NativeMySQLConn) SQLitePool _ pool -> DP.withResource pool (go SQLite.withTransaction NativeSQLiteConn) where go :: forall b . (b -> IO a -> IO a) -> (b -> NativeSqlConn) -> b -> IO a go hof wrap conn' = hof conn' (f . wrap $ conn') | Representation of native DB pools that we store in FlowRuntime data NativeSqlPool = NativePGPool (DP.Pool BP.Connection) -- ^ 'Pool' with Postgres connections | NativeMySQLPool (DP.Pool MySQL.MySQLConn) -- ^ 'Pool' with MySQL connections ^ ' Pool ' with SQLite connections | NativeMockedPool deriving Show -- | Representation of native DB connections that we use in implementation. data NativeSqlConn = NativePGConn BP.Connection | NativeMySQLConn MySQL.MySQLConn | NativeSQLiteConn SQLite.Connection -- | Transform 'SqlConn' to 'NativeSqlPool' bemToNative :: SqlConn beM -> NativeSqlPool bemToNative (MockedPool _) = NativeMockedPool bemToNative (PostgresPool _ pool) = NativePGPool pool bemToNative (MySQLPool _ pool) = NativeMySQLPool pool bemToNative (SQLitePool _ pool) = NativeSQLitePool pool -- | Create 'SqlConn' from 'DBConfig' mkSqlConn :: DBConfig beM -> IO (SqlConn beM) mkSqlConn (PostgresPoolConf connTag cfg PoolConfig {..}) = PostgresPool connTag <$> DP.createPool (createPostgresConn cfg) BP.close stripes keepAlive resourcesPerStripe mkSqlConn (MySQLPoolConf connTag cfg PoolConfig {..}) = MySQLPool connTag <$> DP.createPool (createMySQLConn cfg) MySQL.close stripes keepAlive resourcesPerStripe mkSqlConn (SQLitePoolConf connTag dbname PoolConfig {..}) = SQLitePool connTag <$> DP.createPool (SQLite.open dbname) SQLite.close stripes keepAlive resourcesPerStripe mkSqlConn (MockConfig connTag) = pure $ MockedPool connTag -- | Tag for SQL connections type ConnTag = Text | Represents path to the SQLite DB type SQliteDBname = String -- | Represents SQL connection that we use in flow. Parametrised by BEAM monad corresponding to the certain DB ( MySQL , Postgres , SQLite ) data SqlConn (beM :: Type -> Type) = MockedPool ConnTag | PostgresPool ConnTag (DP.Pool BP.Connection) -- ^ 'Pool' with Postgres connections | MySQLPool ConnTag (DP.Pool MySQL.MySQLConn) -- ^ 'Pool' with MySQL connections | SQLitePool ConnTag (DP.Pool SQLite.Connection) ^ ' Pool ' with SQLite connections deriving (Generic) -- | Represents DB configurations data DBConfig (beM :: Type -> Type) = MockConfig ConnTag | PostgresPoolConf ConnTag PostgresConfig PoolConfig -- ^ config for 'Pool' with Postgres connections | MySQLPoolConf ConnTag MySQLConfig PoolConfig -- ^ config for 'Pool' with MySQL connections | SQLitePoolConf ConnTag SQliteDBname PoolConfig ^ config for ' Pool ' with SQlite connections deriving (Show, Eq, Ord, Generic, ToJSON, FromJSON) -- | Represents 'Pool' parameters data PoolConfig = PoolConfig { stripes :: Int -- ^ a number of sub-pools , keepAlive :: NominalDiffTime -- ^ the amount of time the connection will be stored , resourcesPerStripe :: Int -- ^ maximum number of connections to be stored in each sub-pool } deriving (Show, Eq, Ord, Generic, ToJSON, FromJSON) defaultPoolConfig :: PoolConfig defaultPoolConfig = PoolConfig { stripes = 1 , keepAlive = 100 , resourcesPerStripe = 1 } -- | Create SQLite 'DBConfig' mkSQLiteConfig :: ConnTag -> SQliteDBname -> DBConfig BS.SqliteM mkSQLiteConfig connTag dbName = SQLitePoolConf connTag dbName defaultPoolConfig -- | Create SQLite 'Pool' 'DBConfig' mkSQLitePoolConfig :: ConnTag -> SQliteDBname -> PoolConfig -> DBConfig BS.SqliteM mkSQLitePoolConfig = SQLitePoolConf -- | Create Postgres 'DBConfig' mkPostgresConfig :: ConnTag -> PostgresConfig -> DBConfig BP.Pg mkPostgresConfig connTag dbName = PostgresPoolConf connTag dbName defaultPoolConfig -- | Create Postgres 'Pool' 'DBConfig' mkPostgresPoolConfig :: ConnTag -> PostgresConfig -> PoolConfig -> DBConfig BP.Pg mkPostgresPoolConfig = PostgresPoolConf -- | Create MySQL 'DBConfig' mkMySQLConfig :: ConnTag -> MySQLConfig -> DBConfig BM.MySQLM mkMySQLConfig connTag dbName = MySQLPoolConf connTag dbName defaultPoolConfig -- | Create MySQL 'Pool' 'DBConfig' mkMySQLPoolConfig :: ConnTag -> MySQLConfig -> PoolConfig -> DBConfig BM.MySQLM mkMySQLPoolConfig = MySQLPoolConf getDBName :: DBConfig beM -> String getDBName (PostgresPoolConf _ (PostgresConfig{..}) _) = connectDatabase getDBName (MySQLPoolConf _ (MySQLConfig{..}) _) = connectDatabase getDBName (SQLitePoolConf _ dbName _) = dbName getDBName (MockConfig _) = error "Can't get DB name of MockConfig" ---------------------------------------------------------------------- data SqliteError = SqliteErrorOK | SqliteErrorError | SqliteErrorInternal | SqliteErrorPermission | SqliteErrorAbort | SqliteErrorBusy | SqliteErrorLocked | SqliteErrorNoMemory | SqliteErrorReadOnly | SqliteErrorInterrupt | SqliteErrorIO | SqliteErrorCorrupt | SqliteErrorNotFound | SqliteErrorFull | SqliteErrorCantOpen | SqliteErrorProtocol | SqliteErrorEmpty | SqliteErrorSchema | SqliteErrorTooBig | SqliteErrorConstraint | SqliteErrorMismatch | SqliteErrorMisuse | SqliteErrorNoLargeFileSupport | SqliteErrorAuthorization | SqliteErrorFormat | SqliteErrorRange | SqliteErrorNotADatabase | SqliteErrorNotice | SqliteErrorWarning | SqliteErrorRow | SqliteErrorDone deriving (Show, Eq, Ord, Generic, ToJSON, FromJSON) toSqliteError :: SQLite.Error -> SqliteError toSqliteError SQLite.ErrorOK = SqliteErrorOK toSqliteError SQLite.ErrorError = SqliteErrorError toSqliteError SQLite.ErrorInternal = SqliteErrorInternal toSqliteError SQLite.ErrorPermission = SqliteErrorPermission toSqliteError SQLite.ErrorAbort = SqliteErrorAbort toSqliteError SQLite.ErrorBusy = SqliteErrorBusy toSqliteError SQLite.ErrorLocked = SqliteErrorLocked toSqliteError SQLite.ErrorNoMemory = SqliteErrorNoMemory toSqliteError SQLite.ErrorReadOnly = SqliteErrorReadOnly toSqliteError SQLite.ErrorInterrupt = SqliteErrorInterrupt toSqliteError SQLite.ErrorIO = SqliteErrorIO toSqliteError SQLite.ErrorCorrupt = SqliteErrorCorrupt toSqliteError SQLite.ErrorNotFound = SqliteErrorNotFound toSqliteError SQLite.ErrorFull = SqliteErrorFull toSqliteError SQLite.ErrorCan'tOpen = SqliteErrorCantOpen toSqliteError SQLite.ErrorProtocol = SqliteErrorProtocol toSqliteError SQLite.ErrorEmpty = SqliteErrorEmpty toSqliteError SQLite.ErrorSchema = SqliteErrorSchema toSqliteError SQLite.ErrorTooBig = SqliteErrorTooBig toSqliteError SQLite.ErrorConstraint = SqliteErrorConstraint toSqliteError SQLite.ErrorMismatch = SqliteErrorMismatch toSqliteError SQLite.ErrorMisuse = SqliteErrorMisuse toSqliteError SQLite.ErrorNoLargeFileSupport = SqliteErrorNoLargeFileSupport toSqliteError SQLite.ErrorAuthorization = SqliteErrorAuthorization toSqliteError SQLite.ErrorFormat = SqliteErrorFormat toSqliteError SQLite.ErrorRange = SqliteErrorRange toSqliteError SQLite.ErrorNotADatabase = SqliteErrorNotADatabase toSqliteError SQLite.ErrorNotice = SqliteErrorNotice toSqliteError SQLite.ErrorWarning = SqliteErrorWarning toSqliteError SQLite.ErrorRow = SqliteErrorRow toSqliteError SQLite.ErrorDone = SqliteErrorDone data SqliteSqlError = SqliteSqlError { sqlError :: !SqliteError , sqlErrorDetails :: Text , sqlErrorContext :: Text } deriving (Show, Eq, Ord, Generic, ToJSON, FromJSON) toSqliteSqlError :: SQLite.SQLError -> SqliteSqlError toSqliteSqlError sqlErr = SqliteSqlError { sqlError = toSqliteError $ SQLite.sqlError sqlErr , sqlErrorDetails = SQLite.sqlErrorDetails sqlErr , sqlErrorContext = SQLite.sqlErrorContext sqlErr } sqliteErrorToDbError :: Text -> SQLite.SQLError -> DBError sqliteErrorToDbError descr e = DBError (SQLError $ SqliteError $ toSqliteSqlError e) descr data SQLError = PostgresError PostgresSqlError | MysqlError MysqlSqlError | SqliteError SqliteSqlError deriving (Show, Eq, Ord, Generic, ToJSON, FromJSON) ---------------------------------------------------------------------- data MysqlSqlError = MysqlSqlError { errCode :: {-# UNPACK #-} !Word16, errMsg :: {-# UNPACK #-} !Text } deriving stock (Show, Eq, Ord, Generic) deriving anyclass (ToJSON, FromJSON) toMysqlSqlError :: MySQL.ERR -> MysqlSqlError toMysqlSqlError err = MysqlSqlError { errCode = MySQL.errCode err, errMsg = decodeUtf8 . MySQL.errMsg $ err } mysqlErrorToDbError :: Text -> MySQL.ERRException -> DBError mysqlErrorToDbError desc (MySQL.ERRException e) = DBError (SQLError . MysqlError . toMysqlSqlError $ e) desc ---------------------------------------------------------------------- data PostgresExecStatus = PostgresEmptyQuery | PostgresCommandOk | PostgresTuplesOk | PostgresCopyOut | PostgresCopyIn | PostgresCopyBoth | PostgresBadResponse | PostgresNonfatalError | PostgresFatalError | PostgresSingleTuple deriving (Show, Eq, Ord, Generic, ToJSON, FromJSON) toPostgresExecStatus :: PGS.ExecStatus -> PostgresExecStatus toPostgresExecStatus PGS.EmptyQuery = PostgresEmptyQuery toPostgresExecStatus PGS.CommandOk = PostgresCommandOk toPostgresExecStatus PGS.TuplesOk = PostgresTuplesOk toPostgresExecStatus PGS.CopyOut = PostgresCopyOut toPostgresExecStatus PGS.CopyIn = PostgresCopyIn toPostgresExecStatus PGS.CopyBoth = PostgresCopyBoth toPostgresExecStatus PGS.BadResponse = PostgresBadResponse toPostgresExecStatus PGS.NonfatalError = PostgresNonfatalError toPostgresExecStatus PGS.FatalError = PostgresFatalError toPostgresExecStatus PGS.SingleTuple = PostgresSingleTuple data PostgresSqlError = PostgresSqlError { sqlState :: Text , sqlExecStatus :: PostgresExecStatus , sqlErrorMsg :: Text , sqlErrorDetail :: Text , sqlErrorHint :: Text } deriving (Show, Eq, Ord, Generic, ToJSON, FromJSON) toPostgresSqlError :: PGS.SqlError -> PostgresSqlError toPostgresSqlError e = PostgresSqlError { sqlState = decodeUtf8 $ PGS.sqlState e , sqlExecStatus = toPostgresExecStatus $ PGS.sqlExecStatus e , sqlErrorMsg = decodeUtf8 $ PGS.sqlErrorMsg e , sqlErrorDetail = decodeUtf8 $ PGS.sqlErrorDetail e , sqlErrorHint = decodeUtf8 $ PGS.sqlErrorHint e } postgresErrorToDbError :: Text -> PGS.SqlError -> DBError postgresErrorToDbError descr e = DBError (SQLError $ PostgresError $ toPostgresSqlError e) descr ---------------------------------------------------------------------- -- TODO: more informative typed error. -- | Represents failures that may occur while working with the database data DBErrorType = ConnectionFailed | ConnectionAlreadyExists | ConnectionDoesNotExist | TransactionRollbacked | SQLError SQLError | UnexpectedResult | UnrecognizedError deriving (Show, Eq, Ord, Generic, ToJSON, FromJSON) -- | Represents DB error data DBError = DBError DBErrorType Text deriving (Show, Eq, Ord, Generic, ToJSON, FromJSON) -- | Represents resulting type for DB actions type DBResult a = Either DBError a | Transforms ' NativeSqlPool ' to ' SqlConn ' nativeToBem :: ConnTag -> NativeSqlPool -> SqlConn beM nativeToBem connTag NativeMockedPool = MockedPool connTag nativeToBem connTag (NativePGPool conn) = PostgresPool connTag conn nativeToBem connTag (NativeMySQLPool conn) = MySQLPool connTag conn nativeToBem connTag (NativeSQLitePool conn) = SQLitePool connTag conn
null
https://raw.githubusercontent.com/juspay/euler-hs/0fdda6ef43c1a6c9c7221d7c194c278e375b9936/src/EulerHS/Core/Types/DB.hs
haskell
# LANGUAGE DerivingStrategies # # LANGUAGE DeriveAnyClass # * Core DB ** Types ** Methods ** Helpers TODO: move somewhere (it's implementation) TODO: move somewhere (it's implementation) ^ 'Pool' with Postgres connections ^ 'Pool' with MySQL connections | Representation of native DB connections that we use in implementation. | Transform 'SqlConn' to 'NativeSqlPool' | Create 'SqlConn' from 'DBConfig' | Tag for SQL connections | Represents SQL connection that we use in flow. ^ 'Pool' with Postgres connections ^ 'Pool' with MySQL connections | Represents DB configurations ^ config for 'Pool' with Postgres connections ^ config for 'Pool' with MySQL connections | Represents 'Pool' parameters ^ a number of sub-pools ^ the amount of time the connection will be stored ^ maximum number of connections to be stored in each sub-pool | Create SQLite 'DBConfig' | Create SQLite 'Pool' 'DBConfig' | Create Postgres 'DBConfig' | Create Postgres 'Pool' 'DBConfig' | Create MySQL 'DBConfig' | Create MySQL 'Pool' 'DBConfig' -------------------------------------------------------------------- -------------------------------------------------------------------- # UNPACK # # UNPACK # -------------------------------------------------------------------- -------------------------------------------------------------------- TODO: more informative typed error. | Represents failures that may occur while working with the database | Represents DB error | Represents resulting type for DB actions
# LANGUAGE FunctionalDependencies # # LANGUAGE RecordWildCards # | Module : EulerHS.Core . Types . DB Copyright : ( C ) Juspay Technologies Pvt Ltd 2019 - 2022 License : Apache 2.0 ( see the file LICENSE ) Maintainer : Stability : experimental Portability : non - portable This module contains general DB - related types and helper functions . This module is internal and should not imported in the projects . Import ' EulerHS.Types ' instead . Types and helpers for specific databases can be found in separate modules : ' EulerHS.Core . Types . MySQL ' ' EulerHS.Core . Types . Postgres ' Module : EulerHS.Core.Types.DB Copyright : (C) Juspay Technologies Pvt Ltd 2019-2022 License : Apache 2.0 (see the file LICENSE) Maintainer : Stability : experimental Portability : non-portable This module contains general DB-related types and helper functions. This module is internal and should not imported in the projects. Import 'EulerHS.Types' instead. Types and helpers for specific databases can be found in separate modules: 'EulerHS.Core.Types.MySQL' 'EulerHS.Core.Types.Postgres' -} module EulerHS.Core.Types.DB ( BeamRuntime(..) , deleteReturningListPG , updateReturningListPG , BeamRunner(..) , NativeSqlPool(..) , NativeSqlConn(..) , ConnTag , SQliteDBname , SqlConn(..) , DBConfig , PoolConfig(..) , DBErrorType(..) , DBError(..) , DBResult , bemToNative , nativeToBem , mkSqlConn , mkSQLiteConfig , mkSQLitePoolConfig , mkPostgresConfig , mkPostgresPoolConfig , mkMySQLConfig , mkMySQLPoolConfig , getDBName , withTransaction , mysqlErrorToDbError , sqliteErrorToDbError , postgresErrorToDbError , PostgresSqlError(..) , PostgresExecStatus(..) , MysqlSqlError(..) , SqliteSqlError(..) , SqliteError(..) , SQLError(..) ) where import EulerHS.Prelude import qualified Data.Pool as DP import Data.Time.Clock (NominalDiffTime) import qualified Database.Beam as B import qualified Database.Beam.Backend.SQL as B import qualified Database.Beam.Backend.SQL.BeamExtensions as B import qualified Database.Beam.MySQL as BM import qualified Database.Beam.Postgres as BP import qualified Database.Beam.Sqlite as BS import qualified Database.Beam.Sqlite.Connection as SQLite import qualified Database.MySQL.Base as MySQL import qualified Database.PostgreSQL.Simple as PGS import qualified Database.SQLite.Simple as SQLite import EulerHS.Core.Types.MySQL (MySQLConfig(..), createMySQLConn) import EulerHS.Core.Types.Postgres (PostgresConfig(..), createPostgresConn) class (B.BeamSqlBackend be, B.MonadBeam be beM) => BeamRuntime be beM | be -> beM, beM -> be where rtSelectReturningList :: B.FromBackendRow be a => B.SqlSelect be a -> beM [a] rtSelectReturningOne :: B.FromBackendRow be a => B.SqlSelect be a -> beM (Maybe a) rtInsert :: B.SqlInsert be table -> beM () rtInsertReturningList :: forall table . (B.Beamable table, B.FromBackendRow be (table Identity)) => B.SqlInsert be table -> beM [table Identity] rtUpdate :: B.SqlUpdate be table -> beM () rtUpdateReturningList :: forall table. (B.Beamable table, B.FromBackendRow be (table Identity)) => B.SqlUpdate be table -> beM [table Identity] rtDelete :: B.SqlDelete be table -> beM () instance BeamRuntime BS.Sqlite BS.SqliteM where rtSelectReturningList = B.runSelectReturningList rtSelectReturningOne = B.runSelectReturningOne rtInsert = B.runInsert rtInsertReturningList = B.runInsertReturningList rtUpdate = B.runUpdate rtUpdateReturningList = error "Not implemented" rtDelete = B.runDelete instance BeamRuntime BP.Postgres BP.Pg where rtSelectReturningList = B.runSelectReturningList rtSelectReturningOne = B.runSelectReturningOne rtInsert = B.runInsert rtInsertReturningList = B.runInsertReturningList rtUpdate = B.runUpdate rtUpdateReturningList = updateReturningListPG rtDelete = B.runDelete deleteReturningListPG :: (B.Beamable table, B.FromBackendRow BP.Postgres (table Identity)) => B.SqlDelete BP.Postgres table -> BP.Pg [table Identity] deleteReturningListPG = B.runDeleteReturningList updateReturningListPG :: (B.Beamable table, B.FromBackendRow BP.Postgres (table Identity)) => B.SqlUpdate BP.Postgres table -> BP.Pg [table Identity] updateReturningListPG = B.runUpdateReturningList instance BeamRuntime BM.MySQL BM.MySQLM where rtSelectReturningList = B.runSelectReturningList rtSelectReturningOne = B.runSelectReturningOne rtInsert = B.runInsert rtInsertReturningList = error "Not implemented" rtUpdate = B.runUpdate rtUpdateReturningList = error "Not implemented" rtDelete = B.runDelete class BeamRunner beM where getBeamDebugRunner :: NativeSqlConn -> beM a -> ((Text -> IO ()) -> IO a) instance BeamRunner BS.SqliteM where getBeamDebugRunner (NativeSQLiteConn conn) beM = \logger -> SQLite.runBeamSqliteDebug logger conn beM getBeamDebugRunner _ _ = \_ -> error "Not a SQLite connection" instance BeamRunner BP.Pg where getBeamDebugRunner (NativePGConn conn) beM = \logger -> BP.runBeamPostgresDebug logger conn beM getBeamDebugRunner _ _ = \_ -> error "Not a Postgres connection" instance BeamRunner BM.MySQLM where getBeamDebugRunner (NativeMySQLConn conn) beM = \logger -> BM.runBeamMySQLDebug logger conn beM getBeamDebugRunner _ _ = \_ -> error "Not a MySQL connection" withTransaction :: forall beM a . SqlConn beM -> (NativeSqlConn -> IO a) -> IO (Either SomeException a) withTransaction conn f = tryAny $ case conn of MockedPool _ -> error "Mocked pool connections are not supported." PostgresPool _ pool -> DP.withResource pool (go PGS.withTransaction NativePGConn) MySQLPool _ pool -> DP.withResource pool (go MySQL.withTransaction NativeMySQLConn) SQLitePool _ pool -> DP.withResource pool (go SQLite.withTransaction NativeSQLiteConn) where go :: forall b . (b -> IO a -> IO a) -> (b -> NativeSqlConn) -> b -> IO a go hof wrap conn' = hof conn' (f . wrap $ conn') | Representation of native DB pools that we store in FlowRuntime data NativeSqlPool ^ ' Pool ' with SQLite connections | NativeMockedPool deriving Show data NativeSqlConn = NativePGConn BP.Connection | NativeMySQLConn MySQL.MySQLConn | NativeSQLiteConn SQLite.Connection bemToNative :: SqlConn beM -> NativeSqlPool bemToNative (MockedPool _) = NativeMockedPool bemToNative (PostgresPool _ pool) = NativePGPool pool bemToNative (MySQLPool _ pool) = NativeMySQLPool pool bemToNative (SQLitePool _ pool) = NativeSQLitePool pool mkSqlConn :: DBConfig beM -> IO (SqlConn beM) mkSqlConn (PostgresPoolConf connTag cfg PoolConfig {..}) = PostgresPool connTag <$> DP.createPool (createPostgresConn cfg) BP.close stripes keepAlive resourcesPerStripe mkSqlConn (MySQLPoolConf connTag cfg PoolConfig {..}) = MySQLPool connTag <$> DP.createPool (createMySQLConn cfg) MySQL.close stripes keepAlive resourcesPerStripe mkSqlConn (SQLitePoolConf connTag dbname PoolConfig {..}) = SQLitePool connTag <$> DP.createPool (SQLite.open dbname) SQLite.close stripes keepAlive resourcesPerStripe mkSqlConn (MockConfig connTag) = pure $ MockedPool connTag type ConnTag = Text | Represents path to the SQLite DB type SQliteDBname = String Parametrised by BEAM monad corresponding to the certain DB ( MySQL , Postgres , SQLite ) data SqlConn (beM :: Type -> Type) = MockedPool ConnTag | PostgresPool ConnTag (DP.Pool BP.Connection) | MySQLPool ConnTag (DP.Pool MySQL.MySQLConn) | SQLitePool ConnTag (DP.Pool SQLite.Connection) ^ ' Pool ' with SQLite connections deriving (Generic) data DBConfig (beM :: Type -> Type) = MockConfig ConnTag | PostgresPoolConf ConnTag PostgresConfig PoolConfig | MySQLPoolConf ConnTag MySQLConfig PoolConfig | SQLitePoolConf ConnTag SQliteDBname PoolConfig ^ config for ' Pool ' with SQlite connections deriving (Show, Eq, Ord, Generic, ToJSON, FromJSON) data PoolConfig = PoolConfig { stripes :: Int , keepAlive :: NominalDiffTime , resourcesPerStripe :: Int } deriving (Show, Eq, Ord, Generic, ToJSON, FromJSON) defaultPoolConfig :: PoolConfig defaultPoolConfig = PoolConfig { stripes = 1 , keepAlive = 100 , resourcesPerStripe = 1 } mkSQLiteConfig :: ConnTag -> SQliteDBname -> DBConfig BS.SqliteM mkSQLiteConfig connTag dbName = SQLitePoolConf connTag dbName defaultPoolConfig mkSQLitePoolConfig :: ConnTag -> SQliteDBname -> PoolConfig -> DBConfig BS.SqliteM mkSQLitePoolConfig = SQLitePoolConf mkPostgresConfig :: ConnTag -> PostgresConfig -> DBConfig BP.Pg mkPostgresConfig connTag dbName = PostgresPoolConf connTag dbName defaultPoolConfig mkPostgresPoolConfig :: ConnTag -> PostgresConfig -> PoolConfig -> DBConfig BP.Pg mkPostgresPoolConfig = PostgresPoolConf mkMySQLConfig :: ConnTag -> MySQLConfig -> DBConfig BM.MySQLM mkMySQLConfig connTag dbName = MySQLPoolConf connTag dbName defaultPoolConfig mkMySQLPoolConfig :: ConnTag -> MySQLConfig -> PoolConfig -> DBConfig BM.MySQLM mkMySQLPoolConfig = MySQLPoolConf getDBName :: DBConfig beM -> String getDBName (PostgresPoolConf _ (PostgresConfig{..}) _) = connectDatabase getDBName (MySQLPoolConf _ (MySQLConfig{..}) _) = connectDatabase getDBName (SQLitePoolConf _ dbName _) = dbName getDBName (MockConfig _) = error "Can't get DB name of MockConfig" data SqliteError = SqliteErrorOK | SqliteErrorError | SqliteErrorInternal | SqliteErrorPermission | SqliteErrorAbort | SqliteErrorBusy | SqliteErrorLocked | SqliteErrorNoMemory | SqliteErrorReadOnly | SqliteErrorInterrupt | SqliteErrorIO | SqliteErrorCorrupt | SqliteErrorNotFound | SqliteErrorFull | SqliteErrorCantOpen | SqliteErrorProtocol | SqliteErrorEmpty | SqliteErrorSchema | SqliteErrorTooBig | SqliteErrorConstraint | SqliteErrorMismatch | SqliteErrorMisuse | SqliteErrorNoLargeFileSupport | SqliteErrorAuthorization | SqliteErrorFormat | SqliteErrorRange | SqliteErrorNotADatabase | SqliteErrorNotice | SqliteErrorWarning | SqliteErrorRow | SqliteErrorDone deriving (Show, Eq, Ord, Generic, ToJSON, FromJSON) toSqliteError :: SQLite.Error -> SqliteError toSqliteError SQLite.ErrorOK = SqliteErrorOK toSqliteError SQLite.ErrorError = SqliteErrorError toSqliteError SQLite.ErrorInternal = SqliteErrorInternal toSqliteError SQLite.ErrorPermission = SqliteErrorPermission toSqliteError SQLite.ErrorAbort = SqliteErrorAbort toSqliteError SQLite.ErrorBusy = SqliteErrorBusy toSqliteError SQLite.ErrorLocked = SqliteErrorLocked toSqliteError SQLite.ErrorNoMemory = SqliteErrorNoMemory toSqliteError SQLite.ErrorReadOnly = SqliteErrorReadOnly toSqliteError SQLite.ErrorInterrupt = SqliteErrorInterrupt toSqliteError SQLite.ErrorIO = SqliteErrorIO toSqliteError SQLite.ErrorCorrupt = SqliteErrorCorrupt toSqliteError SQLite.ErrorNotFound = SqliteErrorNotFound toSqliteError SQLite.ErrorFull = SqliteErrorFull toSqliteError SQLite.ErrorCan'tOpen = SqliteErrorCantOpen toSqliteError SQLite.ErrorProtocol = SqliteErrorProtocol toSqliteError SQLite.ErrorEmpty = SqliteErrorEmpty toSqliteError SQLite.ErrorSchema = SqliteErrorSchema toSqliteError SQLite.ErrorTooBig = SqliteErrorTooBig toSqliteError SQLite.ErrorConstraint = SqliteErrorConstraint toSqliteError SQLite.ErrorMismatch = SqliteErrorMismatch toSqliteError SQLite.ErrorMisuse = SqliteErrorMisuse toSqliteError SQLite.ErrorNoLargeFileSupport = SqliteErrorNoLargeFileSupport toSqliteError SQLite.ErrorAuthorization = SqliteErrorAuthorization toSqliteError SQLite.ErrorFormat = SqliteErrorFormat toSqliteError SQLite.ErrorRange = SqliteErrorRange toSqliteError SQLite.ErrorNotADatabase = SqliteErrorNotADatabase toSqliteError SQLite.ErrorNotice = SqliteErrorNotice toSqliteError SQLite.ErrorWarning = SqliteErrorWarning toSqliteError SQLite.ErrorRow = SqliteErrorRow toSqliteError SQLite.ErrorDone = SqliteErrorDone data SqliteSqlError = SqliteSqlError { sqlError :: !SqliteError , sqlErrorDetails :: Text , sqlErrorContext :: Text } deriving (Show, Eq, Ord, Generic, ToJSON, FromJSON) toSqliteSqlError :: SQLite.SQLError -> SqliteSqlError toSqliteSqlError sqlErr = SqliteSqlError { sqlError = toSqliteError $ SQLite.sqlError sqlErr , sqlErrorDetails = SQLite.sqlErrorDetails sqlErr , sqlErrorContext = SQLite.sqlErrorContext sqlErr } sqliteErrorToDbError :: Text -> SQLite.SQLError -> DBError sqliteErrorToDbError descr e = DBError (SQLError $ SqliteError $ toSqliteSqlError e) descr data SQLError = PostgresError PostgresSqlError | MysqlError MysqlSqlError | SqliteError SqliteSqlError deriving (Show, Eq, Ord, Generic, ToJSON, FromJSON) data MysqlSqlError = MysqlSqlError } deriving stock (Show, Eq, Ord, Generic) deriving anyclass (ToJSON, FromJSON) toMysqlSqlError :: MySQL.ERR -> MysqlSqlError toMysqlSqlError err = MysqlSqlError { errCode = MySQL.errCode err, errMsg = decodeUtf8 . MySQL.errMsg $ err } mysqlErrorToDbError :: Text -> MySQL.ERRException -> DBError mysqlErrorToDbError desc (MySQL.ERRException e) = DBError (SQLError . MysqlError . toMysqlSqlError $ e) desc data PostgresExecStatus = PostgresEmptyQuery | PostgresCommandOk | PostgresTuplesOk | PostgresCopyOut | PostgresCopyIn | PostgresCopyBoth | PostgresBadResponse | PostgresNonfatalError | PostgresFatalError | PostgresSingleTuple deriving (Show, Eq, Ord, Generic, ToJSON, FromJSON) toPostgresExecStatus :: PGS.ExecStatus -> PostgresExecStatus toPostgresExecStatus PGS.EmptyQuery = PostgresEmptyQuery toPostgresExecStatus PGS.CommandOk = PostgresCommandOk toPostgresExecStatus PGS.TuplesOk = PostgresTuplesOk toPostgresExecStatus PGS.CopyOut = PostgresCopyOut toPostgresExecStatus PGS.CopyIn = PostgresCopyIn toPostgresExecStatus PGS.CopyBoth = PostgresCopyBoth toPostgresExecStatus PGS.BadResponse = PostgresBadResponse toPostgresExecStatus PGS.NonfatalError = PostgresNonfatalError toPostgresExecStatus PGS.FatalError = PostgresFatalError toPostgresExecStatus PGS.SingleTuple = PostgresSingleTuple data PostgresSqlError = PostgresSqlError { sqlState :: Text , sqlExecStatus :: PostgresExecStatus , sqlErrorMsg :: Text , sqlErrorDetail :: Text , sqlErrorHint :: Text } deriving (Show, Eq, Ord, Generic, ToJSON, FromJSON) toPostgresSqlError :: PGS.SqlError -> PostgresSqlError toPostgresSqlError e = PostgresSqlError { sqlState = decodeUtf8 $ PGS.sqlState e , sqlExecStatus = toPostgresExecStatus $ PGS.sqlExecStatus e , sqlErrorMsg = decodeUtf8 $ PGS.sqlErrorMsg e , sqlErrorDetail = decodeUtf8 $ PGS.sqlErrorDetail e , sqlErrorHint = decodeUtf8 $ PGS.sqlErrorHint e } postgresErrorToDbError :: Text -> PGS.SqlError -> DBError postgresErrorToDbError descr e = DBError (SQLError $ PostgresError $ toPostgresSqlError e) descr data DBErrorType = ConnectionFailed | ConnectionAlreadyExists | ConnectionDoesNotExist | TransactionRollbacked | SQLError SQLError | UnexpectedResult | UnrecognizedError deriving (Show, Eq, Ord, Generic, ToJSON, FromJSON) data DBError = DBError DBErrorType Text deriving (Show, Eq, Ord, Generic, ToJSON, FromJSON) type DBResult a = Either DBError a | Transforms ' NativeSqlPool ' to ' SqlConn ' nativeToBem :: ConnTag -> NativeSqlPool -> SqlConn beM nativeToBem connTag NativeMockedPool = MockedPool connTag nativeToBem connTag (NativePGPool conn) = PostgresPool connTag conn nativeToBem connTag (NativeMySQLPool conn) = MySQLPool connTag conn nativeToBem connTag (NativeSQLitePool conn) = SQLitePool connTag conn
3a8a9d7b6b44125129696f4a0be587440bcf69bfd1db4f9526bd6ae6bb6bd852
Mayvenn/storefront
footer_minimal.cljc
(ns storefront.components.footer-minimal (:require [storefront.accessors.experiments :as experiments] [storefront.component :as component :refer [defcomponent]] [storefront.components.footer-links :as footer-links] [storefront.components.ui :as ui] [storefront.config :as config] [storefront.events :as events])) (defcomponent component [{:keys [call-number] :as query} owner opts] [:div.bg-cool-gray [:div.hide-on-mb.p8 ;; Desktop & Tablet [:div.flex.justify-between [:div.flex.items-start [:div.title-2.proxima.shout "Need Help?"] [:div.flex.flex-column.items-start.ml8.ptp3.content-2 [:div call-number " | 8am-5pm PST M-F"] [:div.left.mt3 (component/build footer-links/component {:minimal? true} nil)]]]]] [:div.hide-on-tb-dt.py2.px3.flex.flex-column ;; mobile [:div.title-2.proxima.shout.mx-auto.mb1 "Need Help?"] [:div.content-3.proxima.mx-auto (ui/link :link/phone :a.inherit-color {} call-number) " | 8am-5pm PST M-F"] [:div.left (component/build footer-links/component {:minimal? true} nil)]] [:div {:style {:padding-bottom "100px"}}]]) (defn query [data] (merge {:call-number config/support-phone-number})) (defn built-component [data opts] (component/build component (query data) nil))
null
https://raw.githubusercontent.com/Mayvenn/storefront/c7f73e173246f123cfc8197ffe651b1d20792f75/src-cljc/storefront/components/footer_minimal.cljc
clojure
Desktop & Tablet mobile
(ns storefront.components.footer-minimal (:require [storefront.accessors.experiments :as experiments] [storefront.component :as component :refer [defcomponent]] [storefront.components.footer-links :as footer-links] [storefront.components.ui :as ui] [storefront.config :as config] [storefront.events :as events])) (defcomponent component [{:keys [call-number] :as query} owner opts] [:div.bg-cool-gray [:div.flex.justify-between [:div.flex.items-start [:div.title-2.proxima.shout "Need Help?"] [:div.flex.flex-column.items-start.ml8.ptp3.content-2 [:div call-number " | 8am-5pm PST M-F"] [:div.left.mt3 (component/build footer-links/component {:minimal? true} nil)]]]]] [:div.title-2.proxima.shout.mx-auto.mb1 "Need Help?"] [:div.content-3.proxima.mx-auto (ui/link :link/phone :a.inherit-color {} call-number) " | 8am-5pm PST M-F"] [:div.left (component/build footer-links/component {:minimal? true} nil)]] [:div {:style {:padding-bottom "100px"}}]]) (defn query [data] (merge {:call-number config/support-phone-number})) (defn built-component [data opts] (component/build component (query data) nil))
0c803ad2ac83e3e5c376cd40e440033360f59141aa058dc0b0b5bcead75edf7e
AshleyYakeley/Truth
Env.hs
module Pinafore.Language.Library.Env ( envLibSection ) where import Changes.Core import Pinafore.Base import Pinafore.Context import Pinafore.Language.Library.Convert () import Pinafore.Language.Library.Defs import Pinafore.Language.Library.Storage () import Pinafore.Language.Library.Stream import Shapes getVar :: (?qcontext :: InvocationInfo) => Text -> Maybe Text getVar n = fmap pack $ lookup (unpack n) $ iiEnvironment ?qcontext langStdIn :: (?qcontext :: InvocationInfo) => LangSource Text langStdIn = MkLangSource $ hoistSource liftIO $ iiStdIn ?qcontext langStdOut :: (?qcontext :: InvocationInfo) => LangSink Text langStdOut = MkLangSink $ hoistSink liftIO $ iiStdOut ?qcontext langStdErr :: (?qcontext :: InvocationInfo) => LangSink Text langStdErr = MkLangSink $ hoistSink liftIO $ iiStdErr ?qcontext openDefaultStore :: (?qcontext :: InvocationInfo) => View QStore openDefaultStore = do model <- iiDefaultStorageModel ?qcontext liftIO $ mkQStore model envLibSection :: BindDocTree InvocationInfo envLibSection = headingBDT "Env" "The environment in which the script was invoked." $ pure $ namespaceBDT "Env" "" [ valBDT "scriptName" "The name of the script." (pack $ iiScriptName ?qcontext :: Text) , valBDT "arguments" "Arguments passed to the script." (fmap pack $ iiScriptArguments ?qcontext :: [Text]) , valBDT "variables" "Environment variables." (fmap (\(n, v) -> (pack n, pack v)) $ iiEnvironment ?qcontext :: [(Text, Text)]) , valBDT "getVar" "Get environment variable." getVar , valBDT "stdin" "Standard input source." langStdIn , valBDT "stdout" "Standard output sink." langStdOut , valBDT "stderr" "Standard error/diagnostics sink." langStdErr , valBDT "outputLn" "Output text and a newline to standard output. Same as `writeLn stdout`." $ langSinkWriteLn langStdOut , valBDT "openDefaultStore" "Open the default `Store`. Will be closed at the end of the lifecycle." openDefaultStore ]
null
https://raw.githubusercontent.com/AshleyYakeley/Truth/f567d19253bb471cbd8c39095fb414229b27706a/Pinafore/pinafore-language/lib/Pinafore/Language/Library/Env.hs
haskell
module Pinafore.Language.Library.Env ( envLibSection ) where import Changes.Core import Pinafore.Base import Pinafore.Context import Pinafore.Language.Library.Convert () import Pinafore.Language.Library.Defs import Pinafore.Language.Library.Storage () import Pinafore.Language.Library.Stream import Shapes getVar :: (?qcontext :: InvocationInfo) => Text -> Maybe Text getVar n = fmap pack $ lookup (unpack n) $ iiEnvironment ?qcontext langStdIn :: (?qcontext :: InvocationInfo) => LangSource Text langStdIn = MkLangSource $ hoistSource liftIO $ iiStdIn ?qcontext langStdOut :: (?qcontext :: InvocationInfo) => LangSink Text langStdOut = MkLangSink $ hoistSink liftIO $ iiStdOut ?qcontext langStdErr :: (?qcontext :: InvocationInfo) => LangSink Text langStdErr = MkLangSink $ hoistSink liftIO $ iiStdErr ?qcontext openDefaultStore :: (?qcontext :: InvocationInfo) => View QStore openDefaultStore = do model <- iiDefaultStorageModel ?qcontext liftIO $ mkQStore model envLibSection :: BindDocTree InvocationInfo envLibSection = headingBDT "Env" "The environment in which the script was invoked." $ pure $ namespaceBDT "Env" "" [ valBDT "scriptName" "The name of the script." (pack $ iiScriptName ?qcontext :: Text) , valBDT "arguments" "Arguments passed to the script." (fmap pack $ iiScriptArguments ?qcontext :: [Text]) , valBDT "variables" "Environment variables." (fmap (\(n, v) -> (pack n, pack v)) $ iiEnvironment ?qcontext :: [(Text, Text)]) , valBDT "getVar" "Get environment variable." getVar , valBDT "stdin" "Standard input source." langStdIn , valBDT "stdout" "Standard output sink." langStdOut , valBDT "stderr" "Standard error/diagnostics sink." langStdErr , valBDT "outputLn" "Output text and a newline to standard output. Same as `writeLn stdout`." $ langSinkWriteLn langStdOut , valBDT "openDefaultStore" "Open the default `Store`. Will be closed at the end of the lifecycle." openDefaultStore ]
c4b64c720cd6b441d8cb8bd6201cd6a486c5dd96827a66970834af07f43eb3a9
narkisr-deprecated/core
common.clj
(ns openstack.common "common openstack api access" (:require [re-core.model :refer (hypervisor)] ) (:import org.openstack4j.openstack.OSFactory ) ) (defn openstack [tenant] (let [{:keys [username password endpoint]} (hypervisor :openstack)] (-> (OSFactory/builder) (.endpoint endpoint) (.credentials username password) (.tenantName tenant) (.authenticate)))) (defn compute [tenant] (let [{:keys [username password endpoint]} (hypervisor :openstack)] (.compute (openstack tenant)))) (defn servers [tenant] (-> (compute tenant) (.servers))) (defn block-storage [tenant] (-> (openstack tenant) (.blockStorage)))
null
https://raw.githubusercontent.com/narkisr-deprecated/core/85b4a768ef4b3a4eae86695bce36d270dd51dbae/src/openstack/common.clj
clojure
(ns openstack.common "common openstack api access" (:require [re-core.model :refer (hypervisor)] ) (:import org.openstack4j.openstack.OSFactory ) ) (defn openstack [tenant] (let [{:keys [username password endpoint]} (hypervisor :openstack)] (-> (OSFactory/builder) (.endpoint endpoint) (.credentials username password) (.tenantName tenant) (.authenticate)))) (defn compute [tenant] (let [{:keys [username password endpoint]} (hypervisor :openstack)] (.compute (openstack tenant)))) (defn servers [tenant] (-> (compute tenant) (.servers))) (defn block-storage [tenant] (-> (openstack tenant) (.blockStorage)))
bc1846aaa2a037c31d200b5dea26d13be4cef22315fd07f03a8dacd2c3c109a1
zalando-stups/kio
sql.clj
; Copyright 2015 Zalando SE ; 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. (ns org.zalando.stups.kio.sql (:require [environ.core :as env] [yesql.core :refer [defqueries]] [org.zalando.stups.friboo.system.db :refer [def-db-component generate-hystrix-commands]])) USE env variable AUTO_MIGRATION to configure auto - migration ? (def-db-component DB :auto-migration? (Boolean/parseBoolean (env/env :auto-migration))) (def default-db-configuration {:db-classname "org.postgresql.Driver" :db-subprotocol "postgresql" :db-subname "//localhost:5432/kio" :db-user "postgres" :db-password "postgres" :db-init-sql "SET search_path TO zk_data, public"}) (defqueries "db/applications.sql") (generate-hystrix-commands)
null
https://raw.githubusercontent.com/zalando-stups/kio/d84dd2e27d155340c4d2ae45908a11d637563493/src/org/zalando/stups/kio/sql.clj
clojure
Copyright 2015 Zalando SE 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.
Licensed under the Apache License , Version 2.0 ( the " License " ) distributed under the License is distributed on an " AS IS " BASIS , (ns org.zalando.stups.kio.sql (:require [environ.core :as env] [yesql.core :refer [defqueries]] [org.zalando.stups.friboo.system.db :refer [def-db-component generate-hystrix-commands]])) USE env variable AUTO_MIGRATION to configure auto - migration ? (def-db-component DB :auto-migration? (Boolean/parseBoolean (env/env :auto-migration))) (def default-db-configuration {:db-classname "org.postgresql.Driver" :db-subprotocol "postgresql" :db-subname "//localhost:5432/kio" :db-user "postgres" :db-password "postgres" :db-init-sql "SET search_path TO zk_data, public"}) (defqueries "db/applications.sql") (generate-hystrix-commands)
1be57fe9e63bb75bcd3309ed8bae467fdcb222e66839c0b6eda9596000423427
aphyr/tesser
bench_test.clj
(ns tesser.bench-test (:require [clojure.test :refer :all] [clojure.test.check :as tc] [clojure.test.check [clojure-test :refer :all] [generators :as gen] [properties :as prop]] [multiset.core :refer [multiset]] [criterium.core :refer [with-progress-reporting quick-bench bench]] [tesser.core :as t] [tesser.simple :as s] [tesser.utils :refer :all] [clojure.core.reducers :as r] [clojure.set :as set])) (def n 1000000) (defn long-ary [] (->> #(rand-int n) repeatedly (take n) long-array)) (defn long-vec [] (->> #(rand-int n) repeatedly (take n) vec)) (defn sep ([& args] (prn) (prn) (apply println args) (prn))) (deftest ^:bench sum (sep "###### Simple sum ########") (dorun (for [collf [#'long-ary #'long-vec] reducef [#'reduce #'r/fold #'s/fold]] (let [coll (@collf) reducef @reducef] (sep collf reducef) (quick-bench (reducef + coll)))))) (deftest ^:bench map-filter-sum (sep "####### map/filter/sum #######") (dorun (for [collf [#'long-ary #'long-vec]] (let [coll (@collf)] (sep collf "seq/reduce") (quick-bench (->> coll (map inc) (filter even?) (reduce +))) (sep collf "reducers fold") (quick-bench (->> coll (r/map inc) (r/filter even?) (r/fold +))) (sep collf "tesser") (quick-bench (->> (t/map inc) (t/filter even?) (t/fold +) (t/tesser (t/chunk 16384 coll)))))))) (deftest ^:bench fuse (sep "##### Fuse #####") (let [coll (long-ary)] (time (->> (t/fuse {:sum (t/fold +) :evens (->> (t/filter even?) (t/count)) :odds (->> (t/filter odd?) (t/count))}) (t/tesser (t/chunk 16384 coll)))))) ; For profiling (deftest ^:stress stress (let [a (long-vec)] (dotimes [i 10000000] (->> (t/map inc) (t/filter even?) (t/fold +) (t/tesser (t/chunk 1024 a))))))
null
https://raw.githubusercontent.com/aphyr/tesser/2e6fedebbdb127850bd48f255c5793b858eee445/core/test/tesser/bench_test.clj
clojure
For profiling
(ns tesser.bench-test (:require [clojure.test :refer :all] [clojure.test.check :as tc] [clojure.test.check [clojure-test :refer :all] [generators :as gen] [properties :as prop]] [multiset.core :refer [multiset]] [criterium.core :refer [with-progress-reporting quick-bench bench]] [tesser.core :as t] [tesser.simple :as s] [tesser.utils :refer :all] [clojure.core.reducers :as r] [clojure.set :as set])) (def n 1000000) (defn long-ary [] (->> #(rand-int n) repeatedly (take n) long-array)) (defn long-vec [] (->> #(rand-int n) repeatedly (take n) vec)) (defn sep ([& args] (prn) (prn) (apply println args) (prn))) (deftest ^:bench sum (sep "###### Simple sum ########") (dorun (for [collf [#'long-ary #'long-vec] reducef [#'reduce #'r/fold #'s/fold]] (let [coll (@collf) reducef @reducef] (sep collf reducef) (quick-bench (reducef + coll)))))) (deftest ^:bench map-filter-sum (sep "####### map/filter/sum #######") (dorun (for [collf [#'long-ary #'long-vec]] (let [coll (@collf)] (sep collf "seq/reduce") (quick-bench (->> coll (map inc) (filter even?) (reduce +))) (sep collf "reducers fold") (quick-bench (->> coll (r/map inc) (r/filter even?) (r/fold +))) (sep collf "tesser") (quick-bench (->> (t/map inc) (t/filter even?) (t/fold +) (t/tesser (t/chunk 16384 coll)))))))) (deftest ^:bench fuse (sep "##### Fuse #####") (let [coll (long-ary)] (time (->> (t/fuse {:sum (t/fold +) :evens (->> (t/filter even?) (t/count)) :odds (->> (t/filter odd?) (t/count))}) (t/tesser (t/chunk 16384 coll)))))) (deftest ^:stress stress (let [a (long-vec)] (dotimes [i 10000000] (->> (t/map inc) (t/filter even?) (t/fold +) (t/tesser (t/chunk 1024 a))))))
4f5eb04b990d1899add937fee1237dfed617c3344462e38aab449648ae99044b
rorokimdim/stash
TestUtility.hs
module TestUtility ( randomPlainNode , randomPlainNodes , randomLine , randomTitle , randomText , randomBody ) where import Control.Monad (replicateM) import Data.Time (getCurrentTime) import System.Random (randomRIO) import qualified Data.Text as T import qualified Test.RandomStrings as RS import qualified Cipher import Types |Gets a random PlainNode with given parent - id and node - id . randomPlainNode :: ParentId -> NodeId -> IO PlainNode randomPlainNode pid nid = do keySize <- randomRIO (1, 31) key <- T.take keySize <$> randomLine value <- randomBody version <- randomRIO (1, 100) let hkey = Cipher.hash "salt" key let hvalue = Cipher.hash "salt" value created <- getCurrentTime modified <- getCurrentTime return PlainNode { __id = nid , __parent = pid , __hkey = hkey , __hvalue = hvalue , __key = key , __value = value , __version = version , __created = created , __modified = modified } -- |Gets a tree of plain-nodes with provided depth and order. -- -- order is the number of children per node -- number of nodes at each level = order ^ level total number of nodes = order ^ ( depth + 1 ) - 1 randomPlainNodes :: Int -> Int -> IO [PlainNode] randomPlainNodes order depth = do let pids :: [ParentId] pids = concatMap (replicate order) [0 ..] let fns :: [NodeId -> IO PlainNode] fns = map randomPlainNode pids sequence [ fn (toInteger nid) | (fn, nid) <- zip fns [1 .. order ^ (depth + 1) - 1] ] -- |Gets random text for given format. randomText :: TextFormat -> Int -> Int -> Int -> Int -> IO [T.Text] randomText _ 0 _ _ _ = return [] randomText format numTitles depth minDepth maxDepth | depth > maxDepth = return [] randomText format numTitles depth minDepth maxDepth = do title <- randomTitle format depth body <- randomBody numSubTitles <- randomRIO (minDepth, maxDepth) children <- randomText format numSubTitles (depth + 1) minDepth maxDepth others <- randomText format (numTitles - 1) depth minDepth maxDepth return $ title : body : (children ++ others) -- |Gets random title for given format. randomTitle :: TextFormat -> Int -> IO T.Text randomTitle format depth = do rtext <- randomLine let fc = case format of OrgText -> '*' MarkdownText -> '#' if depth == 0 then return rtext else return $ T.pack (replicate depth fc) <> " " <> rtext -- |Gets random body of text randomBody :: IO T.Text randomBody = do n <- randomRIO (minLinesPerBody, maxLinesPerBody) lines <- replicateM n randomLine return $ T.intercalate "\n" lines -- |Gets a random line of text randomLine :: IO T.Text randomLine = do n <- randomRIO (minWordsPerLine, maxWordsPerLine) xs <- RS.randomStringsLen (RS.randomWord RS.randomASCII) (minWordSize, maxWordSize) n return $ T.intercalate " " [ T.pack x | x <- xs ] minWordSize :: Int minWordSize = 1 maxWordSize :: Int maxWordSize = 20 minWordsPerLine :: Int minWordsPerLine = 1 maxWordsPerLine :: Int maxWordsPerLine = 20 minLinesPerBody :: Int minLinesPerBody = 0 maxLinesPerBody :: Int maxLinesPerBody = 10
null
https://raw.githubusercontent.com/rorokimdim/stash/18bdb25b9d1cb0386daf7a2c93bcb4ef654729d9/src/TestUtility.hs
haskell
|Gets a tree of plain-nodes with provided depth and order. order is the number of children per node number of nodes at each level = order ^ level |Gets random text for given format. |Gets random title for given format. |Gets random body of text |Gets a random line of text
module TestUtility ( randomPlainNode , randomPlainNodes , randomLine , randomTitle , randomText , randomBody ) where import Control.Monad (replicateM) import Data.Time (getCurrentTime) import System.Random (randomRIO) import qualified Data.Text as T import qualified Test.RandomStrings as RS import qualified Cipher import Types |Gets a random PlainNode with given parent - id and node - id . randomPlainNode :: ParentId -> NodeId -> IO PlainNode randomPlainNode pid nid = do keySize <- randomRIO (1, 31) key <- T.take keySize <$> randomLine value <- randomBody version <- randomRIO (1, 100) let hkey = Cipher.hash "salt" key let hvalue = Cipher.hash "salt" value created <- getCurrentTime modified <- getCurrentTime return PlainNode { __id = nid , __parent = pid , __hkey = hkey , __hvalue = hvalue , __key = key , __value = value , __version = version , __created = created , __modified = modified } total number of nodes = order ^ ( depth + 1 ) - 1 randomPlainNodes :: Int -> Int -> IO [PlainNode] randomPlainNodes order depth = do let pids :: [ParentId] pids = concatMap (replicate order) [0 ..] let fns :: [NodeId -> IO PlainNode] fns = map randomPlainNode pids sequence [ fn (toInteger nid) | (fn, nid) <- zip fns [1 .. order ^ (depth + 1) - 1] ] randomText :: TextFormat -> Int -> Int -> Int -> Int -> IO [T.Text] randomText _ 0 _ _ _ = return [] randomText format numTitles depth minDepth maxDepth | depth > maxDepth = return [] randomText format numTitles depth minDepth maxDepth = do title <- randomTitle format depth body <- randomBody numSubTitles <- randomRIO (minDepth, maxDepth) children <- randomText format numSubTitles (depth + 1) minDepth maxDepth others <- randomText format (numTitles - 1) depth minDepth maxDepth return $ title : body : (children ++ others) randomTitle :: TextFormat -> Int -> IO T.Text randomTitle format depth = do rtext <- randomLine let fc = case format of OrgText -> '*' MarkdownText -> '#' if depth == 0 then return rtext else return $ T.pack (replicate depth fc) <> " " <> rtext randomBody :: IO T.Text randomBody = do n <- randomRIO (minLinesPerBody, maxLinesPerBody) lines <- replicateM n randomLine return $ T.intercalate "\n" lines randomLine :: IO T.Text randomLine = do n <- randomRIO (minWordsPerLine, maxWordsPerLine) xs <- RS.randomStringsLen (RS.randomWord RS.randomASCII) (minWordSize, maxWordSize) n return $ T.intercalate " " [ T.pack x | x <- xs ] minWordSize :: Int minWordSize = 1 maxWordSize :: Int maxWordSize = 20 minWordsPerLine :: Int minWordsPerLine = 1 maxWordsPerLine :: Int maxWordsPerLine = 20 minLinesPerBody :: Int minLinesPerBody = 0 maxLinesPerBody :: Int maxLinesPerBody = 10
9ee3b97ec51f38ca240dfef3740b242635baa2c8af72439534ff089a271a36c8
achirkin/vulkan
Enum.hs
# LANGUAGE DuplicateRecordFields # # LANGUAGE OverloadedStrings # {-# LANGUAGE QuasiQuotes #-} # LANGUAGE RecordWildCards # {-# LANGUAGE Strict #-} -- Generate enums and bitmasks module Write.Types.Enum ( genEnum , genAlias , genApiConstants , enumPattern , genBitmaskPair ) where import Control.Lens import Control.Monad import Control.Monad.Reader.Class import Data.Maybe import qualified Control . Monad . Trans . RWS.Strict as RWS import qualified Data.Map.Strict as Map import Data.Semigroup import Data.Text (Text) import qualified Data.Text as T import Language.Haskell.Exts.SimpleComments import Language.Haskell.Exts.Syntax import NeatInterpolation import VkXml.CommonTypes import VkXml.Sections import VkXml.Sections.Enums import VkXml.Sections.Types import Write.ModuleWriter import Write.Util.DeclaredNames genBitmaskPair :: Monad m => VkType -- ^ type category bitmask -> VkType -- ^ corresponding bits -> ModuleWriter m () genBitmaskPair tbm te = ask >>= \vk -> case Map.lookup (Just bitsName) (globEnums vk) of Nothing -> error $ "genBitmaskPair: Could not find a corresponding enum for bits type " ++ show te Just VkEnums {..} -> do writePragma "DataKinds" writePragma "KindSignatures" writePragma "StandaloneDeriving" writePragma "TypeSynonymInstances" writePragma "PatternSynonyms" writePragma "FlexibleInstances" writePragma "GeneralizedNewtypeDeriving" writeOptionsPragma (Just HADDOCK) "ignore-exports" writeImport $ DIThing "Storable" DITEmpty writeImport $ DIThing "Bits" DITEmpty writeImport $ DIThing "FiniteBits" DITEmpty writeImport $ DIThing "VkFlags" DITAll writeImport $ DIThing "FlagType" DITEmpty writeImport $ DIThing "FlagMask" DITNo writeImport $ DIThing "FlagBit" DITNo let allPNs = map (unVkEnumName . _vkEnumName) . items $ _vkEnumsMembers mapM_ writeDecl $ parseDecls [text| newtype $baseNameTxt (a :: FlagType) = $baseNameTxt VkFlags deriving ( Eq, Ord, Storable) type $flagNameTxt = $baseNameTxt FlagMask type $bitsNameTxt = $baseNameTxt FlagBit pattern $bitsNameTxt :: VkFlags -> $baseNameTxt FlagBit pattern $bitsNameTxt n = $baseNameTxt n pattern $flagNameTxt :: VkFlags -> $baseNameTxt FlagMask pattern $flagNameTxt n = $baseNameTxt n deriving instance Bits ($baseNameTxt FlagMask) deriving instance FiniteBits ($baseNameTxt FlagMask) |] genEnumShow (VkTypeName $ "(" <> baseNameTxt <> " a)") baseNameTxt allPNs genEnumRead (VkTypeName $ "(" <> baseNameTxt <> " a)") baseNameTxt allPNs pats <- mapM ( bitmaskPattern (baseNameTxt <> " a") baseNameTxt ) $ items _vkEnumsMembers let patCNames = map (ConName () . Ident () . T.unpack) $ baseNameTxt : flagNameTxt : bitsNameTxt : pats ilist = IThingAll () (Ident () (T.unpack baseNameTxt)) elist = EThingWith () (NoWildcard ()) (UnQual () (Ident () $ T.unpack baseNameTxt)) patCNames writeExportExplicit (DIThing baseNameTxt DITNo) [diToImportSpec $ DIThing baseNameTxt DITNo] [] writeExportExplicit (DIThing baseNameTxt DITEmpty) [diToImportSpec $ DIThing baseNameTxt DITEmpty] [] writeExportExplicit (DIThing baseNameTxt DITAll) [ilist] [elist] writeExportExplicit (DIThing flagNameTxt DITNo) [diToImportSpec $ DIThing flagNameTxt DITNo] [diToExportSpec $ DIThing flagNameTxt DITNo] writeExportExplicit (DIThing flagNameTxt DITEmpty) [diToImportSpec $ DIThing flagNameTxt DITEmpty] [] writeExportExplicit (DIThing bitsNameTxt DITNo) [diToImportSpec $ DIThing bitsNameTxt DITNo] [diToExportSpec $ DIThing bitsNameTxt DITNo] writeExportExplicit (DIThing bitsNameTxt DITEmpty) [diToImportSpec $ DIThing bitsNameTxt DITEmpty] [] writeExportExplicit (DIThing flagNameTxt DITAll) [ ilist , diToImportSpec $ DIThing flagNameTxt DITNo] [ ] writeExportExplicit (DIThing bitsNameTxt DITAll) [ ilist , diToImportSpec $ DIThing bitsNameTxt DITNo] [ ] forM_ pats $ \epat -> writeExportExplicit (DIPat epat) [ ilist ] [] where flagName = tname tbm bitsName = tname te baseNameTxt = T.replace "Flags" "Bitmask" flagNameTxt flagNameTxt = unVkTypeName flagName bitsNameTxt = unVkTypeName bitsName tname = name :: VkType -> VkTypeName genApiConstants :: Monad m => ModuleWriter m () genApiConstants = do vk <- ask writeFullImport "Graphics.Vulkan.Marshal" mapM_ genEnums (Map.lookup Nothing (globEnums vk)) -- | Lookup an enum in vk.xml and generate code for it genEnum :: Monad m => VkType -> ModuleWriter m () genEnum t = ask >>= \vk -> case Map.lookup (Just tname) (globEnums vk) of Nothing -> genAlias t Just e -> genEnums e where tname = (name :: VkType -> VkTypeName) t genEnums :: Monad m => VkEnums -> ModuleWriter m () genEnums VkEnums {..} = do if _vkEnumsIsBits then do writeImport $ DIThing "Bits" DITNo writeImport $ DIThing "FiniteBits" DITNo writeImport $ DIThing "VkFlags" DITNo else writeImport $ DIThing "Int32" DITNo mtname <- forM _vkEnumsTypeName $ \tname -> do writePragma "GeneralizedNewtypeDeriving" writeOptionsPragma (Just HADDOCK) "ignore-exports" writeImport $ DIThing "Storable" DITEmpty regLink <- vkRegistryLink $ unVkTypeName tname let tinsts = T.intercalate ", " derives rezComment = preComment . T.unpack $ _vkEnumsComment <:> regLink tnametxt = unVkTypeName tname writeDecl . setComment rezComment $ parseDecl' [text| newtype $tnametxt = $tnametxt $baseType deriving ($tinsts) |] genEnumShow tname (unVkTypeName tname) allPNs genEnumRead tname (unVkTypeName tname) allPNs return tnametxt epats <- (>>= maybeToList) <$> mapM enumPattern (items _vkEnumsMembers) case mtname of Nothing -> mapM_ (writeExport . DIPat) epats Just tnameTxt -> do let patCNames = map (ConName () . Ident () . T.unpack) $ tnameTxt : epats elist = EThingWith () (NoWildcard ()) (UnQual () (Ident () $ T.unpack tnameTxt)) patCNames writeExportExplicit (DIThing tnameTxt DITNo) [ diToImportSpec $ DIThing tnameTxt DITNo ] [] writeExportExplicit (DIThing tnameTxt DITEmpty) [ diToImportSpec $ DIThing tnameTxt DITEmpty ] [] writeExportExplicit (DIThing tnameTxt DITAll) [ diToImportSpec $ DIThing tnameTxt DITAll ] [ elist ] forM_ epats $ \epat -> writeExportExplicit (DIPat epat) [ diToImportSpec $ DIThing tnameTxt DITAll ] [] where derives = (if _vkEnumsIsBits then ("Bits":).("FiniteBits":) else id) ["Eq","Ord","Enum","Storable"] baseType = if _vkEnumsIsBits then "VkFlags" else "Int32" allPNs = map (unVkEnumName . _vkEnumName) . items $ _vkEnumsMembers genEnumShow :: Monad m => VkTypeName -> Text -> [Text] -> ModuleWriter m () genEnumShow (VkTypeName tname) constr xs = writeDecl $ parseDecl' $ T.unlines $ [text|instance Show $tname where|] : map (\x -> " " <> [text|showsPrec _ $x = showString "$x"|] ) xs ++ [" " <> [text|showsPrec p ($constr x) = showParen (p >= 11) (showString "$constr " . showsPrec 11 x)|] ] genEnumRead :: Monad m => VkTypeName -> Text -> [Text] -> ModuleWriter m () genEnumRead (VkTypeName tname) constr xs = do writeImport $ DIThing "Lexeme" DITAll writeImport $ DIThing "Read" DITAll writeImport $ DIVar "expectP" writeImport $ DIVar "choose" writeImport $ DIVar "parens" writeImport $ DIVar "prec" writeImport $ DIVar "step" writeImport $ DIVar "(+++)" writeDecl $ parseDecl' $ [text| instance Read $tname where readPrec = parens ( choose [ |] <> ( T.unlines . map (" " <>) $ T.lines $ T.intercalate ", " ( map (\x -> [text|("$x", pure $x)|]) xs ) <> [text| ] +++ prec 10 (expectP (Ident "$constr") >> ($constr <$> step readPrec)) ) |] ) genAlias :: Monad m => VkType -> ModuleWriter m () genAlias VkTypeSimple { name = VkTypeName s , attributes = VkTypeAttrs { requires = Just (VkTypeName refname) , comment = txt } , typeData = VkTypeData { reference = [("VkFlags", [])] } } | tnameDeclared <- DIThing s DITNo = do indeed <- isIdentDeclared tnameDeclared if indeed then do writeImport tnameDeclared writeExport tnameDeclared else do writeImport $ DIThing refname DITNo writeDecl . setComment (preComment $ T.unpack txt) $ parseDecl' [text|type $s = $refname|] writeExport tnameDeclared genAlias t@VkTypeComposite{..} = error $ "genAlias: did not expect " <> show (vkTypeCat t) <> " being a composite type (VkTypeComposite)!" genAlias VkTypeSimple { name = vkTName , attributes = VkTypeAttrs { comment = txt , category = cat } , typeData = VkTypeData { reference = [(vkTRef, _)] , comment = mtxt2 , code = ccode } } = do writePragma "GeneralizedNewtypeDeriving" writeImport $ DIVar "coerce" writeImport $ DIThing "Bits" DITEmpty writeImport $ DIThing "FiniteBits" DITEmpty writeImport $ DIThing "Storable" DITEmpty writeImport $ DIThing treftxt DITNo writeDecl . setComment rezComment $ parseDecl' $ case cat of VkTypeCatBasetype -> [text| newtype $tnametxt = $tnametxt $treftxt deriving (Eq, Ord, Num, Bounded, Enum, Integral, Real, Bits, FiniteBits, Storable) |] _ -> [text| newtype $tnametxt = $tnametxt $treftxt deriving (Eq, Ord, Enum, Bits, FiniteBits, Storable) |] mapM_ writeDecl $ parseDecls [text| instance Show $tnametxt where {-# INLINE showsPrec #-} showsPrec = coerce (showsPrec :: Int -> $treftxt -> ShowS) instance Read $tnametxt where {-# INLINE readsPrec #-} readsPrec = coerce (readsPrec :: Int -> ReadS $treftxt) |] writeExport $ DIThing tnametxt DITAll where -- tname = toQName vkTName tnametxt = unVkTypeName vkTName treftxt = unVkTypeName vkTRef rezComment = rezComment' >>= preComment . T.unpack rezComment' = if txt == mempty then mtxt2 else case mtxt2 of Nothing -> Just txt Just txt2 -> appendComLine (Just txt) txt2 genAlias t@VkTypeSimple { typeData = td@VkTypeData { reference = [] } } = genAlias t { typeData = td { reference = [("VkFlags", [])] } } genAlias t = error $ "genAlias: expected a simple enum type, but got: " <> show t bitmaskPattern :: Monad m => Text -> Text -> VkEnum -> ModuleWriter m Text bitmaskPattern tnameTxt constrTxt VkEnum { _vkEnumName = VkEnumName patnameTxt , _vkEnumComment = comm , _vkEnumValue = VkEnumIntegral n _ } = do writeDecl . setComment rezComment $ parseDecl' [text|pattern $patnameTxt :: $tnameTxt|] writeDecl $ parseDecl' [text|pattern $patnameTxt = $constrTxt $patVal|] return patnameTxt where patVal = T.pack $ show n rezComment = preComment $ T.unpack comm bitmaskPattern tnameTxt _ VkEnum { _vkEnumName = VkEnumName patnameTxt , _vkEnumComment = comm , _vkEnumValue = VkEnumAlias patAlias } = do writeDecl . setComment rezComment $ parseDecl' [text|pattern $patnameTxt :: $tnameTxt|] writeDecl $ parseDecl' [text|pattern $patnameTxt = $patVal|] return patnameTxt where patVal = unVkEnumName patAlias rezComment = preComment $ T.unpack comm bitmaskPattern _ _ p = error $ "Unexpected bitmask pattern " ++ show p enumPattern :: Monad m => VkEnum -> ModuleWriter m (Maybe Text) enumPattern vke@VkEnum {..} = do writePragma "PatternSynonyms" indeed <- isIdentDeclared patnameDeclared if indeed then do writeImport patnameDeclared writeExport patnameDeclared return Nothing else case _vkEnumValue of VkEnumReference -> do enames <- lookupDeclared (unVkEnumName _vkEnumName) mapM_ writeImport enames mapM_ writeExport enames return Nothing VkEnumString s | tyval <- "\"" <> s <> "\"" , patval <- "Ptr \"" <> s <> "\0\"#" , _patnametxt <- "_" <> patnametxt , is_patnametxt <- "is_" <> patnametxt -> do writePragma "MagicHash" writePragma "ViewPatterns" writeFullImport "Graphics.Vulkan.Marshal" writeImport $ DIThing "CString" DITNo writeImport $ DIThing "Ptr" DITAll mapM_ writeDecl . insertDeclComment (T.unpack patnametxt) rezComment $ parseDecls [text| pattern $patnametxt :: CString pattern $patnametxt <- ( $is_patnametxt -> True ) where $patnametxt = $_patnametxt # INLINE $ _ patnametxt # $_patnametxt :: CString $_patnametxt = $patval # INLINE $ is_patnametxt # $is_patnametxt :: CString -> Bool $is_patnametxt = (EQ ==) . cmpCStrings $_patnametxt type $patnametxt = $tyval |] writeExport $ DIThing patnametxt DITNo writeExport $ DIPat patnametxt return Nothing VkEnumIntegral n tnametxt | Just (VkTypeName cname) <- _vkEnumTName , patval <- T.pack $ showParen (n < 0) (shows n) "" -> do mIsBits <- preview $ to (Map.lookup (Just $ VkTypeName tnametxt) . globEnums) ._Just.vkEnumsIsBits case mIsBits of Just True -> do let basenametxt = T.replace "FlagBits" "Bitmask" tnametxt writeImport $ DIThing basenametxt DITAll Just <$> bitmaskPattern (basenametxt <> " a") basenametxt vke _ -> do writeImport $ DIThing tnametxt DITAll writeDecl . setComment rezComment $ parseDecl' [text|pattern $patnametxt :: $tnametxt|] writeDecl $ parseDecl' [text|pattern $patnametxt = $cname $patval|] return $ Just patnametxt | Nothing <- _vkEnumTName , patval <- T.pack $ show n -> do mapM_ writeDecl . insertDeclComment (T.unpack patnametxt) rezComment $ parseDecls [text| pattern $patnametxt :: $tnametxt pattern $patnametxt = $patval |] -- For positive constants, we can make a type-level value when (n >= 0) $ do writeDecl $ parseDecl' [text|type $patnametxt = $patval|] writeExport $ DIThing patnametxt DITNo writeExport $ DIPat patnametxt return Nothing VkEnumFractional r | patval <- T.pack $ show (realToFrac r :: Double) -> do writeDecl . setComment rezComment $ parseDecl' [text|pattern $patnametxt :: (Fractional a, Eq a) => a|] writeDecl $ parseDecl' [text|pattern $patnametxt = $patval|] writeExport $ DIPat patnametxt return Nothing VkEnumAlias (VkEnumName aliasname) -> do writeOptionsPragma (Just GHC) "-fno-warn-missing-pattern-synonym-signatures" writeImport $ DIPat aliasname writeDecl . setComment rezComment $ parseDecl' [text|pattern $patnametxt = $aliasname|] writeExport $ DIPat patnametxt return Nothing where patname = toQName _vkEnumName patnametxt = qNameTxt patname patnameDeclared = DIPat patnametxt rezComment = preComment $ T.unpack _vkEnumComment
null
https://raw.githubusercontent.com/achirkin/vulkan/b2e0568c71b5135010f4bba939cd8dcf7a05c361/genvulkan/src/Write/Types/Enum.hs
haskell
# LANGUAGE QuasiQuotes # # LANGUAGE Strict # Generate enums and bitmasks ^ type category bitmask ^ corresponding bits | Lookup an enum in vk.xml and generate code for it # INLINE showsPrec # # INLINE readsPrec # tname = toQName vkTName For positive constants, we can make a type-level value
# LANGUAGE DuplicateRecordFields # # LANGUAGE OverloadedStrings # # LANGUAGE RecordWildCards # module Write.Types.Enum ( genEnum , genAlias , genApiConstants , enumPattern , genBitmaskPair ) where import Control.Lens import Control.Monad import Control.Monad.Reader.Class import Data.Maybe import qualified Control . Monad . Trans . RWS.Strict as RWS import qualified Data.Map.Strict as Map import Data.Semigroup import Data.Text (Text) import qualified Data.Text as T import Language.Haskell.Exts.SimpleComments import Language.Haskell.Exts.Syntax import NeatInterpolation import VkXml.CommonTypes import VkXml.Sections import VkXml.Sections.Enums import VkXml.Sections.Types import Write.ModuleWriter import Write.Util.DeclaredNames genBitmaskPair :: Monad m => VkType -> VkType -> ModuleWriter m () genBitmaskPair tbm te = ask >>= \vk -> case Map.lookup (Just bitsName) (globEnums vk) of Nothing -> error $ "genBitmaskPair: Could not find a corresponding enum for bits type " ++ show te Just VkEnums {..} -> do writePragma "DataKinds" writePragma "KindSignatures" writePragma "StandaloneDeriving" writePragma "TypeSynonymInstances" writePragma "PatternSynonyms" writePragma "FlexibleInstances" writePragma "GeneralizedNewtypeDeriving" writeOptionsPragma (Just HADDOCK) "ignore-exports" writeImport $ DIThing "Storable" DITEmpty writeImport $ DIThing "Bits" DITEmpty writeImport $ DIThing "FiniteBits" DITEmpty writeImport $ DIThing "VkFlags" DITAll writeImport $ DIThing "FlagType" DITEmpty writeImport $ DIThing "FlagMask" DITNo writeImport $ DIThing "FlagBit" DITNo let allPNs = map (unVkEnumName . _vkEnumName) . items $ _vkEnumsMembers mapM_ writeDecl $ parseDecls [text| newtype $baseNameTxt (a :: FlagType) = $baseNameTxt VkFlags deriving ( Eq, Ord, Storable) type $flagNameTxt = $baseNameTxt FlagMask type $bitsNameTxt = $baseNameTxt FlagBit pattern $bitsNameTxt :: VkFlags -> $baseNameTxt FlagBit pattern $bitsNameTxt n = $baseNameTxt n pattern $flagNameTxt :: VkFlags -> $baseNameTxt FlagMask pattern $flagNameTxt n = $baseNameTxt n deriving instance Bits ($baseNameTxt FlagMask) deriving instance FiniteBits ($baseNameTxt FlagMask) |] genEnumShow (VkTypeName $ "(" <> baseNameTxt <> " a)") baseNameTxt allPNs genEnumRead (VkTypeName $ "(" <> baseNameTxt <> " a)") baseNameTxt allPNs pats <- mapM ( bitmaskPattern (baseNameTxt <> " a") baseNameTxt ) $ items _vkEnumsMembers let patCNames = map (ConName () . Ident () . T.unpack) $ baseNameTxt : flagNameTxt : bitsNameTxt : pats ilist = IThingAll () (Ident () (T.unpack baseNameTxt)) elist = EThingWith () (NoWildcard ()) (UnQual () (Ident () $ T.unpack baseNameTxt)) patCNames writeExportExplicit (DIThing baseNameTxt DITNo) [diToImportSpec $ DIThing baseNameTxt DITNo] [] writeExportExplicit (DIThing baseNameTxt DITEmpty) [diToImportSpec $ DIThing baseNameTxt DITEmpty] [] writeExportExplicit (DIThing baseNameTxt DITAll) [ilist] [elist] writeExportExplicit (DIThing flagNameTxt DITNo) [diToImportSpec $ DIThing flagNameTxt DITNo] [diToExportSpec $ DIThing flagNameTxt DITNo] writeExportExplicit (DIThing flagNameTxt DITEmpty) [diToImportSpec $ DIThing flagNameTxt DITEmpty] [] writeExportExplicit (DIThing bitsNameTxt DITNo) [diToImportSpec $ DIThing bitsNameTxt DITNo] [diToExportSpec $ DIThing bitsNameTxt DITNo] writeExportExplicit (DIThing bitsNameTxt DITEmpty) [diToImportSpec $ DIThing bitsNameTxt DITEmpty] [] writeExportExplicit (DIThing flagNameTxt DITAll) [ ilist , diToImportSpec $ DIThing flagNameTxt DITNo] [ ] writeExportExplicit (DIThing bitsNameTxt DITAll) [ ilist , diToImportSpec $ DIThing bitsNameTxt DITNo] [ ] forM_ pats $ \epat -> writeExportExplicit (DIPat epat) [ ilist ] [] where flagName = tname tbm bitsName = tname te baseNameTxt = T.replace "Flags" "Bitmask" flagNameTxt flagNameTxt = unVkTypeName flagName bitsNameTxt = unVkTypeName bitsName tname = name :: VkType -> VkTypeName genApiConstants :: Monad m => ModuleWriter m () genApiConstants = do vk <- ask writeFullImport "Graphics.Vulkan.Marshal" mapM_ genEnums (Map.lookup Nothing (globEnums vk)) genEnum :: Monad m => VkType -> ModuleWriter m () genEnum t = ask >>= \vk -> case Map.lookup (Just tname) (globEnums vk) of Nothing -> genAlias t Just e -> genEnums e where tname = (name :: VkType -> VkTypeName) t genEnums :: Monad m => VkEnums -> ModuleWriter m () genEnums VkEnums {..} = do if _vkEnumsIsBits then do writeImport $ DIThing "Bits" DITNo writeImport $ DIThing "FiniteBits" DITNo writeImport $ DIThing "VkFlags" DITNo else writeImport $ DIThing "Int32" DITNo mtname <- forM _vkEnumsTypeName $ \tname -> do writePragma "GeneralizedNewtypeDeriving" writeOptionsPragma (Just HADDOCK) "ignore-exports" writeImport $ DIThing "Storable" DITEmpty regLink <- vkRegistryLink $ unVkTypeName tname let tinsts = T.intercalate ", " derives rezComment = preComment . T.unpack $ _vkEnumsComment <:> regLink tnametxt = unVkTypeName tname writeDecl . setComment rezComment $ parseDecl' [text| newtype $tnametxt = $tnametxt $baseType deriving ($tinsts) |] genEnumShow tname (unVkTypeName tname) allPNs genEnumRead tname (unVkTypeName tname) allPNs return tnametxt epats <- (>>= maybeToList) <$> mapM enumPattern (items _vkEnumsMembers) case mtname of Nothing -> mapM_ (writeExport . DIPat) epats Just tnameTxt -> do let patCNames = map (ConName () . Ident () . T.unpack) $ tnameTxt : epats elist = EThingWith () (NoWildcard ()) (UnQual () (Ident () $ T.unpack tnameTxt)) patCNames writeExportExplicit (DIThing tnameTxt DITNo) [ diToImportSpec $ DIThing tnameTxt DITNo ] [] writeExportExplicit (DIThing tnameTxt DITEmpty) [ diToImportSpec $ DIThing tnameTxt DITEmpty ] [] writeExportExplicit (DIThing tnameTxt DITAll) [ diToImportSpec $ DIThing tnameTxt DITAll ] [ elist ] forM_ epats $ \epat -> writeExportExplicit (DIPat epat) [ diToImportSpec $ DIThing tnameTxt DITAll ] [] where derives = (if _vkEnumsIsBits then ("Bits":).("FiniteBits":) else id) ["Eq","Ord","Enum","Storable"] baseType = if _vkEnumsIsBits then "VkFlags" else "Int32" allPNs = map (unVkEnumName . _vkEnumName) . items $ _vkEnumsMembers genEnumShow :: Monad m => VkTypeName -> Text -> [Text] -> ModuleWriter m () genEnumShow (VkTypeName tname) constr xs = writeDecl $ parseDecl' $ T.unlines $ [text|instance Show $tname where|] : map (\x -> " " <> [text|showsPrec _ $x = showString "$x"|] ) xs ++ [" " <> [text|showsPrec p ($constr x) = showParen (p >= 11) (showString "$constr " . showsPrec 11 x)|] ] genEnumRead :: Monad m => VkTypeName -> Text -> [Text] -> ModuleWriter m () genEnumRead (VkTypeName tname) constr xs = do writeImport $ DIThing "Lexeme" DITAll writeImport $ DIThing "Read" DITAll writeImport $ DIVar "expectP" writeImport $ DIVar "choose" writeImport $ DIVar "parens" writeImport $ DIVar "prec" writeImport $ DIVar "step" writeImport $ DIVar "(+++)" writeDecl $ parseDecl' $ [text| instance Read $tname where readPrec = parens ( choose [ |] <> ( T.unlines . map (" " <>) $ T.lines $ T.intercalate ", " ( map (\x -> [text|("$x", pure $x)|]) xs ) <> [text| ] +++ prec 10 (expectP (Ident "$constr") >> ($constr <$> step readPrec)) ) |] ) genAlias :: Monad m => VkType -> ModuleWriter m () genAlias VkTypeSimple { name = VkTypeName s , attributes = VkTypeAttrs { requires = Just (VkTypeName refname) , comment = txt } , typeData = VkTypeData { reference = [("VkFlags", [])] } } | tnameDeclared <- DIThing s DITNo = do indeed <- isIdentDeclared tnameDeclared if indeed then do writeImport tnameDeclared writeExport tnameDeclared else do writeImport $ DIThing refname DITNo writeDecl . setComment (preComment $ T.unpack txt) $ parseDecl' [text|type $s = $refname|] writeExport tnameDeclared genAlias t@VkTypeComposite{..} = error $ "genAlias: did not expect " <> show (vkTypeCat t) <> " being a composite type (VkTypeComposite)!" genAlias VkTypeSimple { name = vkTName , attributes = VkTypeAttrs { comment = txt , category = cat } , typeData = VkTypeData { reference = [(vkTRef, _)] , comment = mtxt2 , code = ccode } } = do writePragma "GeneralizedNewtypeDeriving" writeImport $ DIVar "coerce" writeImport $ DIThing "Bits" DITEmpty writeImport $ DIThing "FiniteBits" DITEmpty writeImport $ DIThing "Storable" DITEmpty writeImport $ DIThing treftxt DITNo writeDecl . setComment rezComment $ parseDecl' $ case cat of VkTypeCatBasetype -> [text| newtype $tnametxt = $tnametxt $treftxt deriving (Eq, Ord, Num, Bounded, Enum, Integral, Real, Bits, FiniteBits, Storable) |] _ -> [text| newtype $tnametxt = $tnametxt $treftxt deriving (Eq, Ord, Enum, Bits, FiniteBits, Storable) |] mapM_ writeDecl $ parseDecls [text| instance Show $tnametxt where showsPrec = coerce (showsPrec :: Int -> $treftxt -> ShowS) instance Read $tnametxt where readsPrec = coerce (readsPrec :: Int -> ReadS $treftxt) |] writeExport $ DIThing tnametxt DITAll where tnametxt = unVkTypeName vkTName treftxt = unVkTypeName vkTRef rezComment = rezComment' >>= preComment . T.unpack rezComment' = if txt == mempty then mtxt2 else case mtxt2 of Nothing -> Just txt Just txt2 -> appendComLine (Just txt) txt2 genAlias t@VkTypeSimple { typeData = td@VkTypeData { reference = [] } } = genAlias t { typeData = td { reference = [("VkFlags", [])] } } genAlias t = error $ "genAlias: expected a simple enum type, but got: " <> show t bitmaskPattern :: Monad m => Text -> Text -> VkEnum -> ModuleWriter m Text bitmaskPattern tnameTxt constrTxt VkEnum { _vkEnumName = VkEnumName patnameTxt , _vkEnumComment = comm , _vkEnumValue = VkEnumIntegral n _ } = do writeDecl . setComment rezComment $ parseDecl' [text|pattern $patnameTxt :: $tnameTxt|] writeDecl $ parseDecl' [text|pattern $patnameTxt = $constrTxt $patVal|] return patnameTxt where patVal = T.pack $ show n rezComment = preComment $ T.unpack comm bitmaskPattern tnameTxt _ VkEnum { _vkEnumName = VkEnumName patnameTxt , _vkEnumComment = comm , _vkEnumValue = VkEnumAlias patAlias } = do writeDecl . setComment rezComment $ parseDecl' [text|pattern $patnameTxt :: $tnameTxt|] writeDecl $ parseDecl' [text|pattern $patnameTxt = $patVal|] return patnameTxt where patVal = unVkEnumName patAlias rezComment = preComment $ T.unpack comm bitmaskPattern _ _ p = error $ "Unexpected bitmask pattern " ++ show p enumPattern :: Monad m => VkEnum -> ModuleWriter m (Maybe Text) enumPattern vke@VkEnum {..} = do writePragma "PatternSynonyms" indeed <- isIdentDeclared patnameDeclared if indeed then do writeImport patnameDeclared writeExport patnameDeclared return Nothing else case _vkEnumValue of VkEnumReference -> do enames <- lookupDeclared (unVkEnumName _vkEnumName) mapM_ writeImport enames mapM_ writeExport enames return Nothing VkEnumString s | tyval <- "\"" <> s <> "\"" , patval <- "Ptr \"" <> s <> "\0\"#" , _patnametxt <- "_" <> patnametxt , is_patnametxt <- "is_" <> patnametxt -> do writePragma "MagicHash" writePragma "ViewPatterns" writeFullImport "Graphics.Vulkan.Marshal" writeImport $ DIThing "CString" DITNo writeImport $ DIThing "Ptr" DITAll mapM_ writeDecl . insertDeclComment (T.unpack patnametxt) rezComment $ parseDecls [text| pattern $patnametxt :: CString pattern $patnametxt <- ( $is_patnametxt -> True ) where $patnametxt = $_patnametxt # INLINE $ _ patnametxt # $_patnametxt :: CString $_patnametxt = $patval # INLINE $ is_patnametxt # $is_patnametxt :: CString -> Bool $is_patnametxt = (EQ ==) . cmpCStrings $_patnametxt type $patnametxt = $tyval |] writeExport $ DIThing patnametxt DITNo writeExport $ DIPat patnametxt return Nothing VkEnumIntegral n tnametxt | Just (VkTypeName cname) <- _vkEnumTName , patval <- T.pack $ showParen (n < 0) (shows n) "" -> do mIsBits <- preview $ to (Map.lookup (Just $ VkTypeName tnametxt) . globEnums) ._Just.vkEnumsIsBits case mIsBits of Just True -> do let basenametxt = T.replace "FlagBits" "Bitmask" tnametxt writeImport $ DIThing basenametxt DITAll Just <$> bitmaskPattern (basenametxt <> " a") basenametxt vke _ -> do writeImport $ DIThing tnametxt DITAll writeDecl . setComment rezComment $ parseDecl' [text|pattern $patnametxt :: $tnametxt|] writeDecl $ parseDecl' [text|pattern $patnametxt = $cname $patval|] return $ Just patnametxt | Nothing <- _vkEnumTName , patval <- T.pack $ show n -> do mapM_ writeDecl . insertDeclComment (T.unpack patnametxt) rezComment $ parseDecls [text| pattern $patnametxt :: $tnametxt pattern $patnametxt = $patval |] when (n >= 0) $ do writeDecl $ parseDecl' [text|type $patnametxt = $patval|] writeExport $ DIThing patnametxt DITNo writeExport $ DIPat patnametxt return Nothing VkEnumFractional r | patval <- T.pack $ show (realToFrac r :: Double) -> do writeDecl . setComment rezComment $ parseDecl' [text|pattern $patnametxt :: (Fractional a, Eq a) => a|] writeDecl $ parseDecl' [text|pattern $patnametxt = $patval|] writeExport $ DIPat patnametxt return Nothing VkEnumAlias (VkEnumName aliasname) -> do writeOptionsPragma (Just GHC) "-fno-warn-missing-pattern-synonym-signatures" writeImport $ DIPat aliasname writeDecl . setComment rezComment $ parseDecl' [text|pattern $patnametxt = $aliasname|] writeExport $ DIPat patnametxt return Nothing where patname = toQName _vkEnumName patnametxt = qNameTxt patname patnameDeclared = DIPat patnametxt rezComment = preComment $ T.unpack _vkEnumComment
8d5fc66fa5ba151f2bd307ffa011ce6bf43ef5c97256ff235550bc592175f820
vincenthz/hs-asn1
Stream.hs
-- | -- Module : Data.ASN1.Stream -- License : BSD-style Maintainer : < > -- Stability : experimental -- Portability : unknown -- module Data.ASN1.Stream ( ASN1Repr , getConstructedEnd , getConstructedEndRepr ) where import Data.ASN1.Types import Data.ASN1.Types.Lowlevel associate a list of asn1 event with an ASN1 type . - it 's sometimes required to know the exact byte sequence leading to an ASN1 type : - eg : cryptographic signature - it's sometimes required to know the exact byte sequence leading to an ASN1 type: - eg: cryptographic signature -} type ASN1Repr = (ASN1, [ASN1Event]) getConstructedEnd :: Int -> [ASN1] -> ([ASN1],[ASN1]) getConstructedEnd _ xs@[] = (xs, []) getConstructedEnd i ((x@(Start _)):xs) = let (yz, zs) = getConstructedEnd (i+1) xs in (x:yz,zs) getConstructedEnd i ((x@(End _)):xs) | i == 0 = ([], xs) | otherwise = let (ys, zs) = getConstructedEnd (i-1) xs in (x:ys,zs) getConstructedEnd i (x:xs) = let (ys, zs) = getConstructedEnd i xs in (x:ys,zs) getConstructedEndRepr :: [ASN1Repr] -> ([ASN1Repr],[ASN1Repr]) getConstructedEndRepr = g where g [] = ([], []) g (x@(Start _,_):xs) = let (ys, zs) = getEnd 1 xs in (x:ys, zs) g (x:xs) = ([x],xs) getEnd :: Int -> [ASN1Repr] -> ([ASN1Repr],[ASN1Repr]) getEnd _ [] = ([], []) getEnd 0 xs = ([], xs) getEnd i ((x@(Start _, _)):xs) = let (ys, zs) = getEnd (i+1) xs in (x:ys,zs) getEnd i ((x@(End _, _)):xs) = let (ys, zs) = getEnd (i-1) xs in (x:ys,zs) getEnd i (x:xs) = let (ys, zs) = getEnd i xs in (x:ys,zs)
null
https://raw.githubusercontent.com/vincenthz/hs-asn1/c017c03b0f71a3b45165468a1d1028a0ed7502c0/encoding/Data/ASN1/Stream.hs
haskell
| Module : Data.ASN1.Stream License : BSD-style Stability : experimental Portability : unknown
Maintainer : < > module Data.ASN1.Stream ( ASN1Repr , getConstructedEnd , getConstructedEndRepr ) where import Data.ASN1.Types import Data.ASN1.Types.Lowlevel associate a list of asn1 event with an ASN1 type . - it 's sometimes required to know the exact byte sequence leading to an ASN1 type : - eg : cryptographic signature - it's sometimes required to know the exact byte sequence leading to an ASN1 type: - eg: cryptographic signature -} type ASN1Repr = (ASN1, [ASN1Event]) getConstructedEnd :: Int -> [ASN1] -> ([ASN1],[ASN1]) getConstructedEnd _ xs@[] = (xs, []) getConstructedEnd i ((x@(Start _)):xs) = let (yz, zs) = getConstructedEnd (i+1) xs in (x:yz,zs) getConstructedEnd i ((x@(End _)):xs) | i == 0 = ([], xs) | otherwise = let (ys, zs) = getConstructedEnd (i-1) xs in (x:ys,zs) getConstructedEnd i (x:xs) = let (ys, zs) = getConstructedEnd i xs in (x:ys,zs) getConstructedEndRepr :: [ASN1Repr] -> ([ASN1Repr],[ASN1Repr]) getConstructedEndRepr = g where g [] = ([], []) g (x@(Start _,_):xs) = let (ys, zs) = getEnd 1 xs in (x:ys, zs) g (x:xs) = ([x],xs) getEnd :: Int -> [ASN1Repr] -> ([ASN1Repr],[ASN1Repr]) getEnd _ [] = ([], []) getEnd 0 xs = ([], xs) getEnd i ((x@(Start _, _)):xs) = let (ys, zs) = getEnd (i+1) xs in (x:ys,zs) getEnd i ((x@(End _, _)):xs) = let (ys, zs) = getEnd (i-1) xs in (x:ys,zs) getEnd i (x:xs) = let (ys, zs) = getEnd i xs in (x:ys,zs)
731fb030a3f5b43acdce749d19ff8043ffd8116234b7ac8c9ef00fc0ce09f8a3
szynwelski/nlambda
Nondeterministic.hs
module Nominal.Automaton.Nondeterministic where import Nominal.Atoms import Nominal.Automaton.Base import Nominal.Automaton.Deterministic (isDeterministic) import Nominal.Formula import Nominal.Set import Nominal.Type import Nominal.Variants import Prelude hiding (not) ---------------------------------------------------------------------------------------------------- Nondeterministic automaton ---------------------------------------------------------------------------------------------------- -- | The constructor of a nondeterministic automaton. na :: (Nominal q, Nominal a) => Set q -> Set a -> Set (q, a, q) -> Set q -> Set q -> Automaton q a na = automaton -- | The constructor of a nondeterministic automaton with additional not accepting state. naWithTrashCan :: (Nominal q, Nominal a) => Set q -> Set a -> Set (q, a, q) -> Set q -> Set q -> Automaton (Maybe q) a naWithTrashCan = automatonWithTrashCan -- | The constructor of a nondeterministic automaton with atoms as states. atomsNA :: Nominal q => Set q -> Set (q, Atom, q) -> Set q -> Set q -> Automaton q Atom atomsNA q = na q atoms -- | The constructor of a nondeterministic automaton with atoms as states with additional not accepting state. atomsNAWithTrashCan :: Nominal q => Set q -> Set (q, Atom, q) -> Set q -> Set q -> Automaton (Maybe q) Atom atomsNAWithTrashCan q = naWithTrashCan q atoms -- | Checks whether an automaton is nondeterministic. isNondeterministic :: (Nominal q, Nominal a) => Automaton q a -> Formula isNondeterministic = not . isDeterministic
null
https://raw.githubusercontent.com/szynwelski/nlambda/8357a5f661180438ca6f08104b3f3395d157c0c2/src/Nominal/Automaton/Nondeterministic.hs
haskell
-------------------------------------------------------------------------------------------------- -------------------------------------------------------------------------------------------------- | The constructor of a nondeterministic automaton. | The constructor of a nondeterministic automaton with additional not accepting state. | The constructor of a nondeterministic automaton with atoms as states. | The constructor of a nondeterministic automaton with atoms as states with additional not accepting state. | Checks whether an automaton is nondeterministic.
module Nominal.Automaton.Nondeterministic where import Nominal.Atoms import Nominal.Automaton.Base import Nominal.Automaton.Deterministic (isDeterministic) import Nominal.Formula import Nominal.Set import Nominal.Type import Nominal.Variants import Prelude hiding (not) Nondeterministic automaton na :: (Nominal q, Nominal a) => Set q -> Set a -> Set (q, a, q) -> Set q -> Set q -> Automaton q a na = automaton naWithTrashCan :: (Nominal q, Nominal a) => Set q -> Set a -> Set (q, a, q) -> Set q -> Set q -> Automaton (Maybe q) a naWithTrashCan = automatonWithTrashCan atomsNA :: Nominal q => Set q -> Set (q, Atom, q) -> Set q -> Set q -> Automaton q Atom atomsNA q = na q atoms atomsNAWithTrashCan :: Nominal q => Set q -> Set (q, Atom, q) -> Set q -> Set q -> Automaton (Maybe q) Atom atomsNAWithTrashCan q = naWithTrashCan q atoms isNondeterministic :: (Nominal q, Nominal a) => Automaton q a -> Formula isNondeterministic = not . isDeterministic
60c6c264770608a809507d0c741c56cb326017cb9d1b2905bce08028b477bd09
pezipink/asi64
reader.rkt
` Copyright , 2017 #lang s-exp syntax/module-reader asi64 #:wrapper1 wrapper1 #:language-info #(asi64/lang/language-info get-language-info #f) (require "../reader.rkt")
null
https://raw.githubusercontent.com/pezipink/asi64/81e61a25a6f35e137df6326353b9c54f50f2d829/lang/reader.rkt
racket
` Copyright , 2017 #lang s-exp syntax/module-reader asi64 #:wrapper1 wrapper1 #:language-info #(asi64/lang/language-info get-language-info #f) (require "../reader.rkt")
e001cb5a3fa94681ca0c0fc7713bc3080a4f25bcc05a18572300c8102d11dc65
JacobGabrielson/cl-rogue
armor.lisp
;;;; This file contains misc functions for dealing with armor @(#)armor.c 3.9 ( Berkeley ) 6/15/81 (in-package :cl-rogue) (defun wear () "The player wants to wear something, so let him/her put it on." (if cur-armor (progn (addmsg "You are already wearing some") (verbose (addmsg ". You'll have to take it off first")) (endmsg) (setf *after* nil)) (when-let (obj (get-item "wear" ARMOR)) (if (not (eql (object-o-type obj) ARMOR)) (msg "You can't wear that.") (progn (waste-time) (addmsg (if terse "W" "You are now w")) (msg (format nil "earing ~a" (aref a-names (object-o-which obj)))) (setf cur-armor obj) (logior! (object-o-flags obj) ISKNOW)))))) (defun take-off () "Get the armor off of the player's back." (let ((obj cur-armor)) (if obj (when (dropcheck cur-armor) (setf cur-armor nil) (addmsg (if terse "Was" "You used to be ")) (msg (format nil " wearing ~a) ~a" (pack-char obj) (inv-name obj t)))) (msg (if terse "Not wearing armor" "You aren't wearing any armor"))))) (defun waste-time () "Do nothing but let other things happen." (do-daemons BEFORE) (do-fuses BEFORE) (do-daemons AFTER) (do-fuses AFTER))
null
https://raw.githubusercontent.com/JacobGabrielson/cl-rogue/ecc0eba9224313cbc7f8003c15e35dbb0d2b57eb/armor.lisp
lisp
This file contains misc functions for dealing with armor
@(#)armor.c 3.9 ( Berkeley ) 6/15/81 (in-package :cl-rogue) (defun wear () "The player wants to wear something, so let him/her put it on." (if cur-armor (progn (addmsg "You are already wearing some") (verbose (addmsg ". You'll have to take it off first")) (endmsg) (setf *after* nil)) (when-let (obj (get-item "wear" ARMOR)) (if (not (eql (object-o-type obj) ARMOR)) (msg "You can't wear that.") (progn (waste-time) (addmsg (if terse "W" "You are now w")) (msg (format nil "earing ~a" (aref a-names (object-o-which obj)))) (setf cur-armor obj) (logior! (object-o-flags obj) ISKNOW)))))) (defun take-off () "Get the armor off of the player's back." (let ((obj cur-armor)) (if obj (when (dropcheck cur-armor) (setf cur-armor nil) (addmsg (if terse "Was" "You used to be ")) (msg (format nil " wearing ~a) ~a" (pack-char obj) (inv-name obj t)))) (msg (if terse "Not wearing armor" "You aren't wearing any armor"))))) (defun waste-time () "Do nothing but let other things happen." (do-daemons BEFORE) (do-fuses BEFORE) (do-daemons AFTER) (do-fuses AFTER))
7027c673bd61c0c395b29b0163ff1b0648c3aec589558c0600c78f5236fbacd0
typesafety/aoc2021
Day05.hs
module Solutions.Day05 ( solveP1, solveP2, ) where import CustomPrelude import Data.Sequence qualified as Seq import Data.HashMap.Strict qualified as M import Text.Megaparsec qualified as P import Text.Megaparsec.Char qualified as P import Text.Megaparsec.Char.Lexer qualified as Lex * Part 1 solveP1 :: Text -> Int solveP1 = M.foldl' (\acc x -> if x >= 2 then acc + 1 else acc) 0 . foldl' (\acc l -> fromMaybe acc (addNonDiagonalLine acc l)) M.empty . unsafeParseInput -- | Map from coordinate to number of vents. type VentMap = M.HashMap (Int, Int) Int -- | Add the vents described by a Line to a VentMap. addNonDiagonalLine :: VentMap -> Line -> Maybe VentMap addNonDiagonalLine vm = foldl' (flip addVent) vm <.> ventsInNonDiagonalLine where addVent :: (Int, Int) -> VentMap -> VentMap addVent v = M.insertWith (+) v 1 -- | Only considers horizontal and vertical lines. ventsInNonDiagonalLine :: Line -> Maybe (Seq (Int, Int)) ventsInNonDiagonalLine (Line (x1, y1) (x2, y2)) -- Vertical line | x1 == x2 = Just $ let ys = [min y1 y2 .. max y1 y2] in Seq.zip (Seq.replicate (length ys) x1) ys Horizontal line | y1 == y2 = Just $ let xs = [min x1 x2 .. max x1 x2] in Seq.zip xs (Seq.replicate (length xs) y1) Diagonal line | otherwise = Nothing data Line = Line (Int, Int) (Int, Int) deriving (Eq, Show) type Parser = P.Parsec Void Text unsafeParseInput :: Text -> Seq Line unsafeParseInput = fromMaybe (error "Day5: bad parse") . P.parseMaybe pInput pInput :: Parser (Seq Line) pInput = fromList <$> P.many (pLine >>= \l -> void P.newline <|> P.eof >> pure l) pLine :: Parser Line pLine = do start <- pCoord _ <- P.space *> P.string "->" *> P.space end <- pCoord pure $ Line start end pCoord :: Parser (Int, Int) pCoord = do x <- Lex.decimal _ <- P.char ',' y <- Lex.decimal pure (x, y) * Part 2 solveP2 :: Text -> Int solveP2 = M.foldl' (\acc x -> if x >= 2 then acc + 1 else acc) 0 . foldl' addLine M.empty . unsafeParseInput addLine :: VentMap -> Line -> VentMap addLine vm = foldl' (\acc v -> M.insertWith (+) v 1 acc) vm . ventsInLine ventsInLine :: Line -> Seq (Int, Int) ventsInLine l@(Line (x1, y1) (x2, y2)) = fromMaybe diagonal (ventsInNonDiagonalLine l) where diagonal :: Seq (Int, Int) diagonal = let xs = if x1 > x2 then [x1, x1 - 1 .. x2] else [x1 .. x2] ys = if y1 > y2 then [y1, y1 - 1 .. y2] else [y1 .. y2] in Seq.zip xs ys
null
https://raw.githubusercontent.com/typesafety/aoc2021/578980d74b06383ce0008bcc0f4d6a75f64f210d/src/Solutions/Day05.hs
haskell
| Map from coordinate to number of vents. | Add the vents described by a Line to a VentMap. | Only considers horizontal and vertical lines. Vertical line
module Solutions.Day05 ( solveP1, solveP2, ) where import CustomPrelude import Data.Sequence qualified as Seq import Data.HashMap.Strict qualified as M import Text.Megaparsec qualified as P import Text.Megaparsec.Char qualified as P import Text.Megaparsec.Char.Lexer qualified as Lex * Part 1 solveP1 :: Text -> Int solveP1 = M.foldl' (\acc x -> if x >= 2 then acc + 1 else acc) 0 . foldl' (\acc l -> fromMaybe acc (addNonDiagonalLine acc l)) M.empty . unsafeParseInput type VentMap = M.HashMap (Int, Int) Int addNonDiagonalLine :: VentMap -> Line -> Maybe VentMap addNonDiagonalLine vm = foldl' (flip addVent) vm <.> ventsInNonDiagonalLine where addVent :: (Int, Int) -> VentMap -> VentMap addVent v = M.insertWith (+) v 1 ventsInNonDiagonalLine :: Line -> Maybe (Seq (Int, Int)) ventsInNonDiagonalLine (Line (x1, y1) (x2, y2)) | x1 == x2 = Just $ let ys = [min y1 y2 .. max y1 y2] in Seq.zip (Seq.replicate (length ys) x1) ys Horizontal line | y1 == y2 = Just $ let xs = [min x1 x2 .. max x1 x2] in Seq.zip xs (Seq.replicate (length xs) y1) Diagonal line | otherwise = Nothing data Line = Line (Int, Int) (Int, Int) deriving (Eq, Show) type Parser = P.Parsec Void Text unsafeParseInput :: Text -> Seq Line unsafeParseInput = fromMaybe (error "Day5: bad parse") . P.parseMaybe pInput pInput :: Parser (Seq Line) pInput = fromList <$> P.many (pLine >>= \l -> void P.newline <|> P.eof >> pure l) pLine :: Parser Line pLine = do start <- pCoord _ <- P.space *> P.string "->" *> P.space end <- pCoord pure $ Line start end pCoord :: Parser (Int, Int) pCoord = do x <- Lex.decimal _ <- P.char ',' y <- Lex.decimal pure (x, y) * Part 2 solveP2 :: Text -> Int solveP2 = M.foldl' (\acc x -> if x >= 2 then acc + 1 else acc) 0 . foldl' addLine M.empty . unsafeParseInput addLine :: VentMap -> Line -> VentMap addLine vm = foldl' (\acc v -> M.insertWith (+) v 1 acc) vm . ventsInLine ventsInLine :: Line -> Seq (Int, Int) ventsInLine l@(Line (x1, y1) (x2, y2)) = fromMaybe diagonal (ventsInNonDiagonalLine l) where diagonal :: Seq (Int, Int) diagonal = let xs = if x1 > x2 then [x1, x1 - 1 .. x2] else [x1 .. x2] ys = if y1 > y2 then [y1, y1 - 1 .. y2] else [y1 .. y2] in Seq.zip xs ys
7319ac204dd5668507e75439986ac994364881675ab61868978e9ecae487b741
kind2-mc/kind2
lib.ml
This file is part of the Kind 2 model checker . Copyright ( c ) 2015 by the Board of Trustees of the University of Iowa 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 . Copyright (c) 2015 by the Board of Trustees of the University of Iowa 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. *) open Format exception Unsupported of string (** function thunk for unimplimented features*) let todo = fun s -> raise (Unsupported s) (* ********************************************************************** *) (* Helper functions *) (* ********************************************************************** *) (* Identity function. *) let identity anything = anything Prints the first argument and returns the second . let print_pass s whatever = printf "%s@." s ; whatever (* Returns true when given unit. *) let true_of_unit () = true (* Returns false when given unit. *) let false_of_unit () = false (* Returns None when given unit. *) let none_of_unit () = None (* Returns true *) let true_of_any _ = true (* Returns false s*) let false_of_any _ = false (* Creates a directory if it does not already exist. *) let mk_dir dir = try Unix.mkdir dir 0o740 with Unix.Unix_error(Unix.EEXIST, _, _) -> () (* Flips the expected argument of the function *) let flip f = fun b a -> f a b (* ********************************************************************** *) (* Arithmetic functions *) (* ********************************************************************** *) (* Compute [m * h + i] and make sure that the result does not overflow to a negtive number *) let safe_hash_interleave h m i = abs(i + (m * h) mod max_int) (* ********************************************************************** *) (* List functions *) (* ********************************************************************** *) (* Add element to the head of the list if the option value is not [None] *) let ( @:: ) = function | None -> (function l -> l) | Some e -> (function l -> e :: l) Creates a size - n list equal to [ f 0 ; f 1 ; ... ; f ( n-1 ) ] let list_init f n = if n = 0 then [] else let rec init_aux i = if i = n-1 then [f i] else (f i) :: (init_aux (i+1)) in init_aux 0 (* Returns the maximum element of a non-empty list *) let list_max l = assert (List.length l > 0); let rec list_max_aux l acc = match l with | [] -> acc | hd :: tl -> list_max_aux tl (max hd acc) in list_max_aux l (List.hd l) Return the index of the first element that satisfies the predicate [ p ] let list_index p = let rec list_index p i = function | [] -> raise Not_found | x :: l -> if p x then i else list_index p (succ i) l in list_index p 0 [ list_indexes l1 l2 ] returns the indexes in list [ l2 ] of elements in list [ l1 ] list [l1] *) let rec list_indexes' accum pos l = function | [] -> List.rev accum | h :: tl -> if List.mem h l then list_indexes' (pos :: accum) (succ pos) l tl else list_indexes' accum (succ pos) l tl let list_indexes l1 l2 = list_indexes' [] 0 l1 l2 (* [list_filter_nth l [p1; p2; ...]] returns the elements [l] at positions [p1], [p2] etc. *) let rec list_filter_nth' current_pos accum = function | [] -> (function _ -> List.rev accum) | h :: list_tl -> (function | next_pos :: positions_tl when current_pos = next_pos -> (match positions_tl with | next_pos' :: _ when next_pos >= next_pos' -> raise (Invalid_argument "list_filter_nth: list of position is not sorted") | _ -> list_filter_nth' (succ current_pos) (h :: accum) list_tl positions_tl) | positions -> list_filter_nth' (succ current_pos) accum list_tl positions) let list_filter_nth l p = list_filter_nth' 0 [] l p let list_extract_nth l i = let rec aux acc l i = match i, l with | 0, x :: r -> x, List.rev_append acc r | i, x :: r when i > 0 -> aux (x :: acc) r (i - 1) | _ -> raise (Invalid_argument "list_extract_nth") in aux [] l i let rec list_remove_nth n = function | [] -> [] | h :: tl -> if n = 0 then tl else h :: list_remove_nth (n - 1) tl let rec list_insert_at x n = function | [] -> [x] | h :: tl as l -> if n = 0 then x :: l else h :: list_insert_at x (n - 1) tl let rec list_apply_at f n = function | [] -> [] | h :: tl -> if n = 0 then f h :: tl else h :: list_apply_at f (n - 1) tl let rec fold_until f acc n = function | [] -> (acc, []) | h :: t as l -> if n = 0 then (acc, l) else fold_until f (f acc h) (n - 1) t let list_slice list i k = let _, list = (* drop n elements *) fold_until (fun _ _ -> []) [] i list in let taken, _ = (* take (k - i + 1) elements *) fold_until (fun acc h -> h :: acc) [] (k - i + 1) list in List.rev taken (* [chain_list \[e1; e2; ...\]] is \[\[e1; e2\]; \[e2; e3\]; ... \]]*) let chain_list = function | [] | _ :: [] -> invalid_arg "chain_list" | h :: tl -> let chain_list (accum, last) curr = ([last; curr] :: accum, curr) in List.rev (fst (List.fold_left chain_list ([], h) tl)) [ chain_list_p \[e1 ; e2 ; ... \ ] ] is [ \[(e1 , e2 ) ; ( e2 , e3 ) ; ... \ ] ] let chain_list_p = function | [] | _ :: [] -> invalid_arg "chain_list_p" | h :: tl -> let chain_list' (accum, last) curr = ((last, curr) :: accum, curr) in List.rev (fst (List.fold_left chain_list' ([], h) tl)) Return a list containing all values in the first list that are not in the second list in the second list *) let list_subtract l1 l2 = List.filter (function e -> not (List.mem e l2)) l1 (* From a sorted list return a list with physical duplicates removed *) let list_uniq l = let rec list_uniq accum = function | [] -> List.rev accum | h1 :: tl -> match accum with | [] -> list_uniq [h1] tl | h2 :: _ -> if h1 == h2 then list_uniq accum tl else list_uniq (h1 :: accum) tl in list_uniq [] l (* Merge two sorted lists without physical duplicates to a sorted list without physical duplicates *) let list_merge_uniq cmp l1 l2 = let rec list_merge_uniq cmp accum l1 l2 = match l1, l2 with One of the lists is empty : reverse accumulator , append other list and return other list and return *) | [], l | l, [] -> List.rev_append accum l First and second head elements are physically equal : remove head element from second list head element from second list *) | h1 :: _, h2 :: tl when h1 == h2 -> list_merge_uniq cmp accum l1 tl First head element is smaller than second : add first head element to accumulator element to accumulator *) | h1 :: tl, h2 :: _ when cmp h1 h2 < 0 -> list_merge_uniq cmp (h1 :: accum) tl l2 First head element is greater than second : add second head element to accumulator element to accumulator *) | h1 :: _, h2 :: tl when cmp h1 h2 > 0 -> list_merge_uniq cmp (h2 :: accum) l1 tl (* Head elements are structurally but not physically equal: keep both in original order *) | h1 :: tl1, h2 :: tl2 -> list_merge_uniq cmp (h2 :: h1 :: accum) tl1 tl2 in list_merge_uniq cmp [] l1 l2 From two sorted lists without physical duplicates return a sorted list without physical duplicates containing elements in both lists list without physical duplicates containing elements in both lists *) let list_inter_uniq cmp l1 l2 = let rec list_inter_uniq cmp accum l1 l2 = match l1, l2 with One of the lists is empty : reverse accumulator and return | [], _ | _, [] -> List.rev accum First and second head elements are physically equal : add first head element to accumulator head element to accumulator *) | h1 :: tl1, h2 :: tl2 when h1 == h2 -> list_inter_uniq cmp (h1 :: accum) tl1 tl2 First head element is smaller than second : remove first head element from list element from list *) | h1 :: tl, h2 :: _ when cmp h1 h2 < 0 -> list_inter_uniq cmp accum tl l2 First head element is greater than or structurally but not physically equal to second : remove second head element from list physically equal to second: remove second head element from list *) | _ :: _, _ :: tl -> list_inter_uniq cmp accum l1 tl in list_inter_uniq cmp [] l1 l2 From two sorted lists without physical duplicates return a sorted list without physical duplicates containing elements in the first but not in the second list list without physical duplicates containing elements in the first but not in the second list *) let list_diff_uniq cmp l1 l2 = let rec list_diff_uniq cmp accum l1 l2 = match l1, l2 with First list is empty : reverse accumulator and return | [], _ -> List.rev accum Second list is empty : reverse accumulator , append first list and return and return *) | l, [] -> List.rev_append accum l First and second head elements are physically equal : remove both head elements both head elements *) | h1 :: tl1, h2 :: tl2 when h1 == h2 -> list_diff_uniq cmp accum tl1 tl2 First head element is smaller than second : add first head element to accumulator element to accumulator *) | h1 :: tl, h2 :: _ when cmp h1 h2 < 0 -> list_diff_uniq cmp (h1 :: accum) tl l2 First head element is greater than second : remove first head element from list element from list *) | _ :: _, _ :: tl -> list_diff_uniq cmp accum l1 tl in list_diff_uniq cmp [] l1 l2 For two sorted lists without physical duplicates return true if the first list contains a physically equal element for each element in the second list first list contains a physically equal element for each element in the second list *) let rec list_subset_uniq cmp l1 l2 = match l1, l2 with (* Both lists are empty: return true *) | [], [] -> true First list is empty , but second list not : return true | [], _ -> true Second list is empty , but first list not : return false | _, [] -> false First and second head elements are physically equal : remove both head elements both head elements *) | h1 :: tl1, h2 :: tl2 when h1 == h2 -> list_subset_uniq cmp tl1 tl2 First head element is smaller than second : return false | h1 :: _, h2 :: _ when cmp h1 h2 < 0 -> false First head element is greater than the second or structurally but not physically equal : remove first head element but not physically equal: remove first head element *) | _ :: _, _ :: tl -> list_subset_uniq cmp l1 tl comparison of pairs let compare_pairs cmp_a cmp_b (a1, b1) (a2, b2) = let c_a = cmp_a a1 a2 in if c_a = 0 then cmp_b b1 b2 else c_a comparison of lists let rec compare_lists f l1 l2 = match l1, l2 with Two empty lists are equal | [], [] -> 0 (* An empty list is smaller than a non-empty list *) | [], _ -> -1 (* An non-empty list is greater than an empty list *) | _, [] -> 1 Compare two non - empty lists | h1 :: tl1, h2 :: tl2 -> (* Compare head elements of lists *) let c = f h1 h2 in (* If head elements are equal, compare tails of lists, otherwise return comparison of head elements *) if c = 0 then compare_lists f tl1 tl2 else c Given two ordered association lists with identical keys , push the values of each element of the first association list to the list of elements of the second association list . The returned association list is in the order of the input lists , the function [ equal ] is used to compare keys . values of each element of the first association list to the list of elements of the second association list. The returned association list is in the order of the input lists, the function [equal] is used to compare keys. *) let list_join equal l1 l2 = let rec list_join' equal accum l1 l2 = match l1, l2 with (* Both lists consumed, return in original order *) | [], [] -> List.rev accum (* Keys of head elements in both lists equal *) | (((k1, v1) :: tl1), ((k2, v2) :: tl2)) when equal k1 k2 -> (* Add to accumulator and continue *) list_join' equal ((k1, (v1 :: v2)) :: accum) tl1 tl2 (* Keys of head elements different, or one of the lists is empty *) | _ -> failwith "list_join" in Second list is empty ? match l2 with Initialize with singleton elements from first list | [] -> List.map (fun (k, v) -> (k, [v])) l1 (* Call recursive function with initial accumulator *) | _ -> list_join' equal [] l1 l2 let list_filter_map f = let rec aux accu = function | [] -> List.rev accu | x :: l -> match f x with | None -> aux accu l | Some v -> aux (v :: accu) l in aux [] let rec list_apply: ('a -> 'b) list -> 'a -> 'b list = fun fs arg -> match fs with | [] -> [] | f :: rest -> f arg :: (list_apply rest arg) let rec find_map f = function | [] -> None | h :: tl -> ( match f h with | None -> find_map f tl | v -> v ) let rec drop_last: 'a list -> 'a list = function | [] -> failwith "drop_last" | [_] -> [] | e :: r -> e :: drop_last r (* ********************************************************************** *) (* Array functions *) (* ********************************************************************** *) (* Returns the maximum element of a non-empty array *) let array_max a = assert (Array.length a > 0); let max_val = ref a.(0) in Array.iter (fun x -> if x > !max_val then max_val := x else ()) a; !max_val (* ********************************************************************** *) (* Set functions *) (* ********************************************************************** *) (* Set of integers *) module IntegerSet = Set.Make (Int) (* Hashtable of integers *) module IntegerHashtbl = Hashtbl.Make (struct type t = int let hash i = i let equal = (=) end) (* ********************************************************************** *) Generic pretty - printing (* ********************************************************************** *) (* Pretty-print an array *) let pp_print_arrayi pp sep ppf array = let n = Array.length array in let print_element i = if i = n-1 then pp ppf i array.(i) else (pp ppf i array.(i); fprintf ppf sep) in let indices = list_init (fun i -> i) n in List.iter print_element indices let pp_print_pair pp1 pp2 sep ppf (left, right) = pp1 ppf left; fprintf ppf sep; pp2 ppf right let pp_print_triple pp1 pp2 pp3 sep ppf (p1, p2, p3) = pp1 ppf p1; fprintf ppf sep; pp2 ppf p2; fprintf ppf sep; pp3 ppf p3 (* Pretty-print a list *) let rec pp_print_list pp sep ppf = function (* Output nothing for the empty list *) | [] -> () (* Output a single element in the list *) | e :: [] -> pp ppf e (* Output a single element and a space *) | e :: tl -> Output one element pp_print_list pp sep ppf [e]; (* Output separator *) fprintf ppf sep; (* Output the rest of the list *) pp_print_list pp sep ppf tl (* Pretty-print a list with a counter of its elements *) let rec pp_print_listi' pp sep ppf = function (* Output nothing for the empty list *) | (_, []) -> () (* Output a single element in the list *) | (i, e :: []) -> pp ppf i e (* Output a single element and a space *) | (i, e :: tl) -> Output one element pp ppf i e; (* Output separator *) fprintf ppf sep; (* Output the rest of the list *) pp_print_listi' pp sep ppf (succ i, tl) (* Pretty-print a list with a counter of its elements *) let pp_print_listi pp sep ppf l = pp_print_listi' pp sep ppf (0, l) let rec pp_print_list2i' pp sep ppf = function | _, [], [] -> () | i, [e1], [e2] -> pp ppf i e1 e2 | i, e1 :: tl1, e2 :: tl2 -> pp ppf i e1 e2; (* Output separator *) fprintf ppf sep; Output the rest of the two lists pp_print_list2i' pp sep ppf (succ i, tl1, tl2) | _ -> invalid_arg "pp_print_list2i" Pretty - print two lists of the same length with a counter of their elements elements *) let pp_print_list2i pp sep ppf l1 l2 = pp_print_list2i' pp sep ppf (0, l1, l2) (* Pretty-print a list wrapped in parentheses *) let pp_print_paren_list ppf list = (* Begin expression with opening parenthesis *) pp_print_string ppf "("; (* Output elements of list *) pp_print_list pp_print_string "@ " ppf list; (* End expression with closing parenthesis *) pp_print_string ppf ")" (* Pretty-print an option type *) let pp_print_option pp ppf = function | None -> fprintf ppf "None" | Some s -> fprintf ppf "@[<hv>Some@ %a@]" pp s (* Print if list is not empty *) let pp_print_if_not_empty s ppf = function | [] -> () | _ -> fprintf ppf s (* Pretty-print into a string *) let string_of_t pp t = (* Create a buffer *) let buf = Buffer.create 80 in (* Create a formatter printing into the buffer *) let ppf = formatter_of_buffer buf in (* Output into buffer *) pp ppf t; (* Flush the formatter *) pp_print_flush ppf (); (* Return the buffer contents *) Buffer.contents buf (* Return the strings as a parenthesized and space separated list *) let paren_string_of_string_list list = string_of_t pp_print_paren_list list (* Return the width of the string, meaning the wisth of it's longest line *) let width_of_string s = let lines = Str.split (Str.regexp "\n") s in List.fold_left (fun max_width s -> max max_width (String.length s) ) 0 lines let escape_json_string s = let backslash = Str.regexp "\\" in let double_quotes = Str.regexp "\"" in let newline = Str.regexp "\n" in s |> Str.global_replace backslash "\\\\" |> Str.global_replace double_quotes "\'" |> Str.global_replace newline "\\n" let escape_xml_string s = let ltr = Str.regexp "<" in let gtr = Str.regexp ">" in let ampr = Str.regexp "&" in s |> Str.global_replace ltr "&lt;" |> Str.global_replace gtr "&gt;" |> Str.global_replace ampr "&amp;" (* ********************************************************************** *) (* Option types *) (* ********************************************************************** *) (* Return the value of an option type, raise [Invalid_argument "get"] if the option value is [None] *) let get = function None -> raise (Invalid_argument "get") | Some x -> x (** Check if an option has some content *) let is_some = function | Some _ -> true | None -> false let join = function | Some x -> x | None -> None let min_option f1 f2 = match f1, f2 with | None, None -> None | Some f, None | None, Some f -> Some f | Some f1, Some f2 -> if f1 < f2 then Some f1 else Some f2 (* ********************************************************************** *) (* String *) (* ********************************************************************** *) Return true if the first characters of [ s1 ] up to the length of [ s2 ] are ientical to [ s2 ] . Return false if [ s2 ] is longer than [ s1 ] . [s2] are ientical to [s2]. Return false if [s2] is longer than [s1]. *) let string_starts_with s1 s2 = (String.length s1 >= String.length s2) && (String.sub s1 0 (String.length s2) = s2) (* ********************************************************************** *) (* Log levels *) (* ********************************************************************** *) (* Levels of log messages *) type log_level = | L_off | L_fatal | L_error | L_warn | L_note | L_info | L_debug | L_trace (* Default log level. *) let default_log_level = L_note (* Associate an integer with each level to induce a total ordering *) let int_of_log_level = function | L_off -> -1 | L_fatal -> 0 | L_error -> 1 | L_warn -> 2 | L_note -> 3 | L_info -> 4 | L_debug -> 5 | L_trace -> 6 let log_level_of_int = function | -1 -> L_off | 0 -> L_fatal | 1 -> L_error | 2 -> L_warn | 3 -> L_note | 4 -> L_info | 5 -> L_debug | 6 -> L_trace | _ -> raise (Invalid_argument "log_level_of_int") let string_of_log_level = function | L_off -> "off" | L_fatal -> "fatal" | L_error -> "error" | L_warn -> "warn" | L_note -> "note" | L_info -> "info" | L_debug -> "debug" | L_trace -> "trace" Compare two levels let compare_levels l1 l2 = Int.compare (int_of_log_level l1) (int_of_log_level l2) (* Current log level *) let log_level = ref L_warn (* Set log level *) let set_log_level l = log_level := l (* Log level *) let get_log_level () = !log_level (* Level is of higher or equal priority than current log level? *) let output_on_level level = compare_levels level !log_level <= 0 Return fprintf if level is is of higher or equal priority than current log level , otherwise return ifprintf than current log level, otherwise return ifprintf *) let ignore_or_fprintf level = if output_on_level level then fprintf else ifprintf (* Return kfprintf if level is is of higher or equal priority than current log level, otherwise return ikfprintf *) let ignore_or_kfprintf level = if output_on_level level then kfprintf else ikfprintf (* ********************************************************************** *) (* Output target *) (* ********************************************************************** *) (* Current formatter for output *) let log_ppf = ref std_formatter (* Set file to write log messages to *) let log_to_file f = Open channel to logfile let oc = try open_out f with | Sys_error _ -> failwith "Could not open logfile" in (* Create and store formatter for logfile *) log_ppf := formatter_of_out_channel oc (* Write messages to standard output *) let log_to_stdout () = log_ppf := std_formatter (* ********************************************************************** *) (* System functions *) (* ********************************************************************** *) let pp_print_banner ppf () = fprintf ppf "%s %s" Version.package_name Version.version let pp_print_version ppf = pp_print_banner ppf () (* Kind modules *) type kind_module = [ `IC3 | `BMC | `IND | `IND2 | `INVGEN | `INVGENOS | `INVGENINT | `INVGENINTOS | `INVGENMACH | `INVGENMACHOS | `INVGENINT8 | `INVGENINT8OS | `INVGENINT16 | `INVGENINT16OS | `INVGENINT32 | `INVGENINT32OS | `INVGENINT64 | `INVGENINT64OS | `INVGENUINT8 | `INVGENUINT8OS | `INVGENUINT16 | `INVGENUINT16OS | `INVGENUINT32 | `INVGENUINT32OS | `INVGENUINT64 | `INVGENUINT64OS | `INVGENREAL | `INVGENREALOS | `C2I | `Interpreter | `Supervisor | `Parser | `Certif | `MCS | `CONTRACTCK ] (* Pretty-print the type of the process *) let pp_print_kind_module ppf = function | `IC3 -> fprintf ppf "property directed reachability" | `BMC -> fprintf ppf "bounded model checking" | `IND -> fprintf ppf "inductive step" | `IND2 -> fprintf ppf "2-induction" | `INVGEN -> fprintf ppf "two state invariant generator (bool)" | `INVGENOS -> fprintf ppf "one state invariant generator (bool)" | `INVGENINT -> fprintf ppf "two state invariant generator (int)" | `INVGENINTOS -> fprintf ppf "one state invariant generator (int)" | `INVGENMACH -> fprintf ppf "two state invariant generator (mach int)" | `INVGENMACHOS -> fprintf ppf "one state invariant generator (mach int)" | `INVGENINT8 -> fprintf ppf "two state invariant generator (int8)" | `INVGENINT8OS -> fprintf ppf "one state invariant generator (int8)" | `INVGENINT16 -> fprintf ppf "two state invariant generator (int16)" | `INVGENINT16OS -> fprintf ppf "one state invariant generator (int16)" | `INVGENINT32 -> fprintf ppf "two state invariant generator (int32)" | `INVGENINT32OS -> fprintf ppf "one state invariant generator (int32)" | `INVGENINT64 -> fprintf ppf "two state invariant generator (int64)" | `INVGENINT64OS -> fprintf ppf "one state invariant generator (int64)" | `INVGENUINT8 -> fprintf ppf "two state invariant generator (uint8)" | `INVGENUINT8OS -> fprintf ppf "one state invariant generator (uint8)" | `INVGENUINT16 -> fprintf ppf "two state invariant generator (uint16)" | `INVGENUINT16OS -> fprintf ppf "one state invariant generator (uint16)" | `INVGENUINT32 -> fprintf ppf "two state invariant generator (uint32)" | `INVGENUINT32OS -> fprintf ppf "one state invariant generator (uint32)" | `INVGENUINT64 -> fprintf ppf "two state invariant generator (uint64)" | `INVGENUINT64OS -> fprintf ppf "one state invariant generator (uint64)" | `INVGENREAL -> fprintf ppf "two state invariant generator (real)" | `INVGENREALOS -> fprintf ppf "one state invariant generator (real)" | `C2I -> fprintf ppf "c2i" | `Interpreter -> fprintf ppf "interpreter" | `Supervisor -> fprintf ppf "invariant manager" | `Parser -> fprintf ppf "parser" | `Certif -> Format.fprintf ppf "certificate" | `MCS -> Format.fprintf ppf "minimal cut set" | `CONTRACTCK -> Format.fprintf ppf "contract checker" (* String representation of a process type *) let string_of_kind_module = string_of_t pp_print_kind_module (* Return a short representation of kind module *) let short_name_of_kind_module = function | `IC3 -> "ic3" | `BMC -> "bmc" | `IND -> "ind" | `IND2 -> "ind2" | `INVGEN -> "invgents" | `INVGENOS -> "invgenos" | `INVGENINT -> "invgenintts" | `INVGENINTOS -> "invgenintos" | `INVGENMACH -> "invgenmachts" | `INVGENMACHOS -> "invgenmachos" | `INVGENINT8 -> "invgenint8ts" | `INVGENINT8OS -> "invgenint8os" | `INVGENINT16 -> "invgenint16ts" | `INVGENINT16OS -> "invgenint16os" | `INVGENINT32 -> "invgenint32ts" | `INVGENINT32OS -> "invgenint32os" | `INVGENINT64 -> "invgenuint64ts" | `INVGENINT64OS -> "invgenuint64os" | `INVGENUINT8 -> "invgenuint8ts" | `INVGENUINT8OS -> "invgenuint8os" | `INVGENUINT16 -> "invgenuint16ts" | `INVGENUINT16OS -> "invgenuint16os" | `INVGENUINT32 -> "invgenuint32ts" | `INVGENUINT32OS -> "invgenuint32os" | `INVGENUINT64 -> "invgenuint64ts" | `INVGENUINT64OS -> "invgenuint64os" | `INVGENREAL -> "invgenintts" | `INVGENREALOS -> "invgenintos" | `C2I -> "c2i" | `Interpreter -> "interp" | `Supervisor -> "super" | `Parser -> "parse" | `Certif -> "certif" | `MCS -> "mcs" | `CONTRACTCK -> "contractck" (* Process type of a string *) let kind_module_of_string = function | "IC3" -> `IC3 | "BMC" -> `BMC | "IND" -> `IND | "IND2" -> `IND2 | "INVGEN" -> `INVGEN | "INVGENOS" -> `INVGENOS | "INVGENINT" -> `INVGENINT | "INVGENINTOS" -> `INVGENINTOS | "INVGENMACH" -> `INVGENMACH | "INVGENMACHOS" -> `INVGENMACHOS | "INVGENINT8" -> `INVGENINT8 | "INVGENINT8OS" -> `INVGENINT8OS | "INVGENINT16" -> `INVGENINT16 | "INVGENINT16OS" -> `INVGENINT16OS | "INVGENINT32" -> `INVGENINT32 | "INVGENINT32OS" -> `INVGENINT32OS | "INVGENINT64" -> `INVGENINT64 | "INVGENINT64OS" -> `INVGENINT64OS | "INVGENUINT8" -> `INVGENUINT8 | "INVGENUINT8OS" -> `INVGENUINT8OS | "INVGENUINT16" -> `INVGENUINT16 | "INVGENUINT16OS" -> `INVGENUINT16OS | "INVGENUINT32" -> `INVGENUINT32 | "INVGENUINT32OS" -> `INVGENUINT32OS | "INVGENUINT64" -> `INVGENUINT64 | "INVGENUINT64OS" -> `INVGENUINT64OS | "INVGENREAL" -> `INVGENREAL | "INVGENREALOS" -> `INVGENREALOS | "C2I" -> `C2I | _ -> raise (Invalid_argument "kind_module_of_string") let int_of_kind_module = function | `CONTRACTCK -> -6 | `MCS -> -5 | `Certif -> -4 | `Parser -> -3 | `Interpreter -> -2 | `Supervisor -> -1 | `BMC -> 1 | `IND -> 2 | `IND2 -> 3 | `IC3 -> 4 | `INVGEN -> 5 | `INVGENOS -> 6 | `INVGENINT -> 7 | `INVGENINTOS -> 8 | `INVGENREAL -> 9 | `INVGENREALOS -> 10 | `C2I -> 11 | `INVGENINT8 -> 12 | `INVGENINT8OS -> 13 | `INVGENINT16 -> 14 | `INVGENINT16OS -> 15 | `INVGENINT32 -> 16 | `INVGENINT32OS -> 17 | `INVGENINT64 -> 18 | `INVGENINT64OS -> 19 | `INVGENUINT8 -> 20 | `INVGENUINT8OS -> 21 | `INVGENUINT16 -> 22 | `INVGENUINT16OS -> 23 | `INVGENUINT32 -> 24 | `INVGENUINT32OS -> 25 | `INVGENUINT64 -> 26 | `INVGENUINT64OS -> 27 | `INVGENMACH -> 28 | `INVGENMACHOS -> 29 (* Timeouts *) exception TimeoutWall exception TimeoutVirtual (* System signal caught *) exception Signal of int (* String representation of signal *) let string_of_signal = function | s when s = Sys.sigabrt -> "SIGABRT" | s when s = Sys.sigalrm -> "SIGALRM" | s when s = Sys.sigfpe -> "SIGFPE" | s when s = Sys.sighup -> "SIGHUP" | s when s = Sys.sigill -> "SIGILL" | s when s = Sys.sigint -> "SIGINT" | s when s = Sys.sigkill -> "SIGKILL" | s when s = Sys.sigpipe -> "SIGPIPE" | s when s = Sys.sigquit -> "SIGQUIT" | s when s = Sys.sigsegv -> "SIGSEGV" | s when s = Sys.sigterm -> "SIGTERM" | s when s = Sys.sigusr1 -> "SIGUSR1" | s when s = Sys.sigusr2 -> "SIGUSR2" | s when s = Sys.sigchld -> "SIGCHLD" | s when s = Sys.sigcont -> "SIGCONT" | s when s = Sys.sigstop -> "SIGSTOP" | s when s = Sys.sigtstp -> "SIGTSTP" | s when s = Sys.sigttin -> "SIGTTIN" | s when s = Sys.sigttou -> "SIGTTOU" | s when s = Sys.sigvtalrm -> "SIGVTALRM" | s when s = Sys.sigprof -> "SIGPROF" | s -> string_of_int s let pp_print_signal ppf s = fprintf ppf "%s" (string_of_signal s) (* Pretty-print the termination status of a process *) let pp_print_process_status ppf = function | Unix.WEXITED s -> fprintf ppf "exited with return code %d" s | Unix.WSIGNALED s -> fprintf ppf "killed by signal %a" pp_print_signal s | Unix.WSTOPPED s -> fprintf ppf "stopped by signal %a" pp_print_signal s (* Raise exception on signal *) let exception_on_signal signal = printf " Signal % a caught " pp_print_signal signal ; raise (Signal signal) Sleep for seconds , resolution is in ms let minisleep sec = try Sleep for the given seconds , yield to other threads Thread.delay sec with Signal caught while in kernel | Unix.Unix_error(Unix.EINTR, _, _) -> (* Cannot find out signal number *) raise (Signal 0) (* Return full path to executable, search PATH environment variable and current working directory *) let find_on_path exec = let rec find_on_path' exec path = (* Terminate on empty path *) if path = "" then raise Not_found; (* Split path at first colon *) let path_hd, path_tl = try (* Position of colon in string *) let colon_index = String.index path ':' in (* Length of string *) let path_len = String.length path in (* Return string up to colon *) (String.sub path 0 colon_index, (* Return string after colon *) String.sub path (colon_index + 1) (path_len - colon_index - 1)) (* Colon not found, return whole string and empty string *) with Not_found -> path, "" in Combine path and filename let exec_path = Filename.concat path_hd exec in if (* Check if file exists on path *) Sys.file_exists exec_path then (* Return full path to file TODO: Check if file is executable here? *) exec_path else (* Continue on remaining path entries *) find_on_path' exec path_tl in try if Filename.is_relative exec then (* Return filename on path, fail with Not_found if path is empty or [exec] not found on path *) find_on_path' exec (Unix.getenv "PATH") else if (* Check if file exists on path *) Sys.file_exists exec then (* Return full path to file TODO: Check if file is executable here? *) exec else raise Not_found with Not_found -> (* Check current directory as last resort *) let exec_path = Filename.concat (Sys.getcwd ()) exec in (* Return full path if file exists, fail otherwise *) if Sys.file_exists exec_path then exec_path else raise Not_found let rec find_file filename = function | [] -> None | dir :: include_dirs -> let path = Filename.concat dir filename in if Sys.file_exists path then Some path else find_file filename include_dirs (* ********************************************************************** *) Parser and lexer functions (* ********************************************************************** *) (* A position in a file The column is the actual colum number, not an offset from the beginning of the file as in Lexing.position *) type position = { pos_fname : string; pos_lnum: int; pos_cnum: int } let equal_pos { pos_fname = p1; pos_lnum = l1; pos_cnum = c1 } { pos_fname = p2; pos_lnum = l2; pos_cnum = c2 } = l1=l2 && c1=c2 && String.equal p1 p2 (* Comparision on positions *) let compare_pos { pos_fname = p1; pos_lnum = l1; pos_cnum = c1 } { pos_fname = p2; pos_lnum = l2; pos_cnum = c2 } = compare_pairs String.compare (compare_pairs Int.compare Int.compare) (p1, (l1, c1)) (p2, (l2, c2)) (* A dummy position, different from any valid position *) let dummy_pos = { pos_fname = ""; pos_lnum = 0; pos_cnum = -1 } (* (* A dummy position in the specified file *) let dummy_pos_in_file fname = { pos_fname = fname; pos_lnum = 0; pos_cnum = -1 } *) (* Pretty-print a position *) let pp_print_position ppf ( { pos_fname; pos_lnum; pos_cnum } as pos ) = if pos = dummy_pos then fprintf ppf "(unknown)" else if pos_lnum = 0 && pos_cnum = -1 then fprintf ppf "%s" pos_fname else let fname = if pos_fname = "" then "(stdin)" else pos_fname in fprintf ppf "%s:%d:%d" fname pos_lnum pos_cnum (** Pretty-print line and column *) let pp_print_line_and_column ppf { pos_lnum; pos_cnum } = if pos_lnum >= 0 && pos_cnum >= 0 then fprintf ppf "[l%dc%d]" pos_lnum pos_cnum else fprintf ppf "[unknown]" let pp_print_lines_and_columns ppf positions = pp_print_list pp_print_line_and_column ", " ppf positions Convert a position from Lexing to a position let position_of_lexing { Lexing.pos_fname; Lexing.pos_lnum; Lexing.pos_bol; Lexing.pos_cnum } = (* Colum number is relative to the beginning of the file *) { pos_fname = pos_fname; pos_lnum = pos_lnum; pos_cnum = pos_cnum - pos_bol + 1} (* Return true if position is a dummy position *) let is_dummy_pos = function | { pos_cnum = -1 } -> true | _ -> false (* Return the file, line and column of a position; fail if the position is a dummy position *) let file_row_col_of_pos = function (* Fail if position is a dummy position *) | p when is_dummy_pos p -> raise (Invalid_argument "file_row_col_of_pos") (* Return tuple of filename, line and column *) | { pos_fname; pos_lnum; pos_cnum } -> (pos_fname, pos_lnum, pos_cnum) (* Return the file of a position *) let file_of_pos { pos_fname } = pos_fname (* Return the line and column of a position; fail if the position is a dummy position *) let row_col_of_pos = function (* Fail if position is a dummy position *) | p when is_dummy_pos p -> raise (Invalid_argument "row_col_of_pos") (* Return tuple of line and column *) | { pos_lnum; pos_cnum } -> (pos_lnum, pos_cnum) let print_backtrace fmt bt = match Printexc.backtrace_slots bt with | None -> () | Some slots -> let n = Array.length slots in Array.iteri (fun i s -> match Printexc.Slot.format i s with | None -> () | Some s -> pp_print_string fmt s; if i < n - 1 then pp_force_newline fmt () ) slots let pos_of_file_row_col (pos_fname, pos_lnum, pos_cnum) = { pos_fname; pos_lnum; pos_cnum } let set_lexer_filename lexbuf fname = lexbuf.Lexing.lex_curr_p <- {lexbuf.Lexing.lex_curr_p with pos_fname = fname} (* Split a string at its first dot. Raises {Not_found} if there are not dots *) let split_dot s = let open String in let n = (index s '.') in sub s 0 n, sub s (n+1) (length s - n - 1) (* Extract scope from a concatenated name *) let extract_scope_name name = let rec loop s scope = try let next_scope, s' = split_dot s in loop s' (next_scope :: scope) with Not_found -> s, List.rev scope in loop name [] (* Create a directory if it does not already exists. *) let create_dir dir = try if not (Sys.is_directory dir) then failwith (dir^" is not a directory") with Sys_error _ -> Unix.mkdir dir 0o755 Copy file . Implementation adapted from " Unix system programming in OCaml " by and Implementation adapted from "Unix system programming in OCaml" by Xavier Leroy and Didier Remy*) let copy_fds fd_in fd_out = let open Unix in let buffer_size = 8192 in let buffer = Bytes.create buffer_size in let rec copy_loop () = match read fd_in buffer 0 buffer_size with | 0 -> () | r -> ignore (write fd_out buffer 0 r); copy_loop () in copy_loop () let file_copy input_name output_name = let open Unix in let fd_in = openfile input_name [O_RDONLY] 0 in let fd_out = openfile output_name [O_WRONLY; O_CREAT; O_TRUNC] 0o666 in copy_fds fd_in fd_out; close fd_in; close fd_out let files_cat_open ?(add_prefix=fun _ -> ()) files output_name = let open Unix in let fd_out = openfile output_name [O_WRONLY; O_CREAT; O_TRUNC] 0o666 in add_prefix (out_channel_of_descr fd_out |> Format.formatter_of_out_channel); let _, fd_out = List.fold_left (fun (first, fd_out) input_name -> let fd_in = openfile input_name [O_RDONLY] 0 in copy_fds fd_in fd_out; let fd_out = if first then begin close fd_out; openfile output_name [O_WRONLY; O_CREAT; O_APPEND] 0o666 end else fd_out in false, fd_out ) (true, fd_out) files in fd_out (* Captures the output and exit status of a unix command : aux func *) let syscall cmd = let so, si, se = Unix.open_process_full cmd (Unix.environment ()) in let buf = Buffer.create 16 in (try while true do Buffer.add_channel buf so 1 done with End_of_file -> ()); ignore(Unix.close_process_full (so, si, se)); Buffer.contents buf let reset_gc_params = let gc_c = Gc.get() in fun () -> Gc.set gc_c let set_liberal_gc () = Gc.full_major (); let gc_c = { (Gc.get ()) with Gc.verbose = 0x3FF ; default 32000 default 124000 default 80 % des donnes vivantes } in Gc.set gc_c (* ********************************************************************** *) (* Paths techniques write to *) (* ********************************************************************** *) module Paths = struct let testgen = "tests" let oracle = "oracle" let implem = "implem" end (* ********************************************************************** *) (* Reserved identifiers *) (* ********************************************************************** *) module ReservedIds = struct let abs_ident_string = "abs" let oracle_ident_string = "nondet" let instance_ident_string = "instance" let init_flag_ident_string = "init_flag" let all_req_ident_string = "all_req" let all_ens_ident_string = "all_ens" let inst_ident_string = "inst" let init_uf_string = "__node_init" let trans_uf_string = "__node_trans" let index_ident_string = "__index" let function_of_inputs = "__function_of_inputs" let state_string = "state" let restart_string = "restart" let state_selected_string = "state.selected" let restart_selected_string = "restart.selected" let state_selected_next_string = "state.selected.next" let restart_selected_next_string = "restart.selected.next" let handler_string = "handler" let unless_string = "unless" Init flag string . let init_flag_string = "__init_flag" (* Abstraction depth input string. *) let depth_input_string = "__depth_input" (* Abstraction depth input string. *) let max_depth_input_string = "__max_depth_input" let reserved_strings = [ init_flag_string ; depth_input_string ; max_depth_input_string ; function_of_inputs ; abs_ident_string ; oracle_ident_string ; instance_ident_string ; init_flag_ident_string ; all_req_ident_string ; all_ens_ident_string ; inst_ident_string ; init_uf_string ; trans_uf_string ; index_ident_string ; ] end (* |===| Exit codes. *) (** Exit codes. *) module ExitCodes = struct let unknown = 0 let unsafe = 10 let safe = 20 let error = 2 let kid_status = 128 end (* |===| File names. *) (** File names. *) module Names = struct (** Contract generation file. *) let contract_gen_file = "kind2_contract.lus" (** Contract name for contract generation. *) let contract_name = Format.asprintf "%a_spec" (pp_print_list Format.pp_print_string "_") (** Invariant logging file. *) let inv_log_file = "kind2_strengthening.lus" (** Contract name for invariant logging. *) let inv_log_contract_name = Format.asprintf "%a_str_spec" (pp_print_list Format.pp_print_string "_") end Local Variables : compile - command : " make -C .. -k " tuareg - interactive - program : " ./kind2.top -I ./_build -I / SExpr " indent - tabs - mode : nil End : Local Variables: compile-command: "make -C .. -k" tuareg-interactive-program: "./kind2.top -I ./_build -I ./_build/SExpr" indent-tabs-mode: nil End: *)
null
https://raw.githubusercontent.com/kind2-mc/kind2/f353437dc4f4f9f0055861916e5cbb6e564cfc65/src/utils/lib.ml
ocaml
* function thunk for unimplimented features ********************************************************************** Helper functions ********************************************************************** Identity function. Returns true when given unit. Returns false when given unit. Returns None when given unit. Returns true Returns false s Creates a directory if it does not already exist. Flips the expected argument of the function ********************************************************************** Arithmetic functions ********************************************************************** Compute [m * h + i] and make sure that the result does not overflow to a negtive number ********************************************************************** List functions ********************************************************************** Add element to the head of the list if the option value is not [None] Returns the maximum element of a non-empty list [list_filter_nth l [p1; p2; ...]] returns the elements [l] at positions [p1], [p2] etc. drop n elements take (k - i + 1) elements [chain_list \[e1; e2; ...\]] is \[\[e1; e2\]; \[e2; e3\]; ... \]] From a sorted list return a list with physical duplicates removed Merge two sorted lists without physical duplicates to a sorted list without physical duplicates Head elements are structurally but not physically equal: keep both in original order Both lists are empty: return true An empty list is smaller than a non-empty list An non-empty list is greater than an empty list Compare head elements of lists If head elements are equal, compare tails of lists, otherwise return comparison of head elements Both lists consumed, return in original order Keys of head elements in both lists equal Add to accumulator and continue Keys of head elements different, or one of the lists is empty Call recursive function with initial accumulator ********************************************************************** Array functions ********************************************************************** Returns the maximum element of a non-empty array ********************************************************************** Set functions ********************************************************************** Set of integers Hashtable of integers ********************************************************************** ********************************************************************** Pretty-print an array Pretty-print a list Output nothing for the empty list Output a single element in the list Output a single element and a space Output separator Output the rest of the list Pretty-print a list with a counter of its elements Output nothing for the empty list Output a single element in the list Output a single element and a space Output separator Output the rest of the list Pretty-print a list with a counter of its elements Output separator Pretty-print a list wrapped in parentheses Begin expression with opening parenthesis Output elements of list End expression with closing parenthesis Pretty-print an option type Print if list is not empty Pretty-print into a string Create a buffer Create a formatter printing into the buffer Output into buffer Flush the formatter Return the buffer contents Return the strings as a parenthesized and space separated list Return the width of the string, meaning the wisth of it's longest line ********************************************************************** Option types ********************************************************************** Return the value of an option type, raise [Invalid_argument "get"] if the option value is [None] * Check if an option has some content ********************************************************************** String ********************************************************************** ********************************************************************** Log levels ********************************************************************** Levels of log messages Default log level. Associate an integer with each level to induce a total ordering Current log level Set log level Log level Level is of higher or equal priority than current log level? Return kfprintf if level is is of higher or equal priority than current log level, otherwise return ikfprintf ********************************************************************** Output target ********************************************************************** Current formatter for output Set file to write log messages to Create and store formatter for logfile Write messages to standard output ********************************************************************** System functions ********************************************************************** Kind modules Pretty-print the type of the process String representation of a process type Return a short representation of kind module Process type of a string Timeouts System signal caught String representation of signal Pretty-print the termination status of a process Raise exception on signal Cannot find out signal number Return full path to executable, search PATH environment variable and current working directory Terminate on empty path Split path at first colon Position of colon in string Length of string Return string up to colon Return string after colon Colon not found, return whole string and empty string Check if file exists on path Return full path to file TODO: Check if file is executable here? Continue on remaining path entries Return filename on path, fail with Not_found if path is empty or [exec] not found on path Check if file exists on path Return full path to file TODO: Check if file is executable here? Check current directory as last resort Return full path if file exists, fail otherwise ********************************************************************** ********************************************************************** A position in a file The column is the actual colum number, not an offset from the beginning of the file as in Lexing.position Comparision on positions A dummy position, different from any valid position (* A dummy position in the specified file Pretty-print a position * Pretty-print line and column Colum number is relative to the beginning of the file Return true if position is a dummy position Return the file, line and column of a position; fail if the position is a dummy position Fail if position is a dummy position Return tuple of filename, line and column Return the file of a position Return the line and column of a position; fail if the position is a dummy position Fail if position is a dummy position Return tuple of line and column Split a string at its first dot. Raises {Not_found} if there are not dots Extract scope from a concatenated name Create a directory if it does not already exists. Captures the output and exit status of a unix command : aux func ********************************************************************** Paths techniques write to ********************************************************************** ********************************************************************** Reserved identifiers ********************************************************************** Abstraction depth input string. Abstraction depth input string. |===| Exit codes. * Exit codes. |===| File names. * File names. * Contract generation file. * Contract name for contract generation. * Invariant logging file. * Contract name for invariant logging.
This file is part of the Kind 2 model checker . Copyright ( c ) 2015 by the Board of Trustees of the University of Iowa 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 . Copyright (c) 2015 by the Board of Trustees of the University of Iowa 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. *) open Format exception Unsupported of string let todo = fun s -> raise (Unsupported s) let identity anything = anything Prints the first argument and returns the second . let print_pass s whatever = printf "%s@." s ; whatever let true_of_unit () = true let false_of_unit () = false let none_of_unit () = None let true_of_any _ = true let false_of_any _ = false let mk_dir dir = try Unix.mkdir dir 0o740 with Unix.Unix_error(Unix.EEXIST, _, _) -> () let flip f = fun b a -> f a b let safe_hash_interleave h m i = abs(i + (m * h) mod max_int) let ( @:: ) = function | None -> (function l -> l) | Some e -> (function l -> e :: l) Creates a size - n list equal to [ f 0 ; f 1 ; ... ; f ( n-1 ) ] let list_init f n = if n = 0 then [] else let rec init_aux i = if i = n-1 then [f i] else (f i) :: (init_aux (i+1)) in init_aux 0 let list_max l = assert (List.length l > 0); let rec list_max_aux l acc = match l with | [] -> acc | hd :: tl -> list_max_aux tl (max hd acc) in list_max_aux l (List.hd l) Return the index of the first element that satisfies the predicate [ p ] let list_index p = let rec list_index p i = function | [] -> raise Not_found | x :: l -> if p x then i else list_index p (succ i) l in list_index p 0 [ list_indexes l1 l2 ] returns the indexes in list [ l2 ] of elements in list [ l1 ] list [l1] *) let rec list_indexes' accum pos l = function | [] -> List.rev accum | h :: tl -> if List.mem h l then list_indexes' (pos :: accum) (succ pos) l tl else list_indexes' accum (succ pos) l tl let list_indexes l1 l2 = list_indexes' [] 0 l1 l2 let rec list_filter_nth' current_pos accum = function | [] -> (function _ -> List.rev accum) | h :: list_tl -> (function | next_pos :: positions_tl when current_pos = next_pos -> (match positions_tl with | next_pos' :: _ when next_pos >= next_pos' -> raise (Invalid_argument "list_filter_nth: list of position is not sorted") | _ -> list_filter_nth' (succ current_pos) (h :: accum) list_tl positions_tl) | positions -> list_filter_nth' (succ current_pos) accum list_tl positions) let list_filter_nth l p = list_filter_nth' 0 [] l p let list_extract_nth l i = let rec aux acc l i = match i, l with | 0, x :: r -> x, List.rev_append acc r | i, x :: r when i > 0 -> aux (x :: acc) r (i - 1) | _ -> raise (Invalid_argument "list_extract_nth") in aux [] l i let rec list_remove_nth n = function | [] -> [] | h :: tl -> if n = 0 then tl else h :: list_remove_nth (n - 1) tl let rec list_insert_at x n = function | [] -> [x] | h :: tl as l -> if n = 0 then x :: l else h :: list_insert_at x (n - 1) tl let rec list_apply_at f n = function | [] -> [] | h :: tl -> if n = 0 then f h :: tl else h :: list_apply_at f (n - 1) tl let rec fold_until f acc n = function | [] -> (acc, []) | h :: t as l -> if n = 0 then (acc, l) else fold_until f (f acc h) (n - 1) t let list_slice list i k = fold_until (fun _ _ -> []) [] i list in fold_until (fun acc h -> h :: acc) [] (k - i + 1) list in List.rev taken let chain_list = function | [] | _ :: [] -> invalid_arg "chain_list" | h :: tl -> let chain_list (accum, last) curr = ([last; curr] :: accum, curr) in List.rev (fst (List.fold_left chain_list ([], h) tl)) [ chain_list_p \[e1 ; e2 ; ... \ ] ] is [ \[(e1 , e2 ) ; ( e2 , e3 ) ; ... \ ] ] let chain_list_p = function | [] | _ :: [] -> invalid_arg "chain_list_p" | h :: tl -> let chain_list' (accum, last) curr = ((last, curr) :: accum, curr) in List.rev (fst (List.fold_left chain_list' ([], h) tl)) Return a list containing all values in the first list that are not in the second list in the second list *) let list_subtract l1 l2 = List.filter (function e -> not (List.mem e l2)) l1 let list_uniq l = let rec list_uniq accum = function | [] -> List.rev accum | h1 :: tl -> match accum with | [] -> list_uniq [h1] tl | h2 :: _ -> if h1 == h2 then list_uniq accum tl else list_uniq (h1 :: accum) tl in list_uniq [] l let list_merge_uniq cmp l1 l2 = let rec list_merge_uniq cmp accum l1 l2 = match l1, l2 with One of the lists is empty : reverse accumulator , append other list and return other list and return *) | [], l | l, [] -> List.rev_append accum l First and second head elements are physically equal : remove head element from second list head element from second list *) | h1 :: _, h2 :: tl when h1 == h2 -> list_merge_uniq cmp accum l1 tl First head element is smaller than second : add first head element to accumulator element to accumulator *) | h1 :: tl, h2 :: _ when cmp h1 h2 < 0 -> list_merge_uniq cmp (h1 :: accum) tl l2 First head element is greater than second : add second head element to accumulator element to accumulator *) | h1 :: _, h2 :: tl when cmp h1 h2 > 0 -> list_merge_uniq cmp (h2 :: accum) l1 tl | h1 :: tl1, h2 :: tl2 -> list_merge_uniq cmp (h2 :: h1 :: accum) tl1 tl2 in list_merge_uniq cmp [] l1 l2 From two sorted lists without physical duplicates return a sorted list without physical duplicates containing elements in both lists list without physical duplicates containing elements in both lists *) let list_inter_uniq cmp l1 l2 = let rec list_inter_uniq cmp accum l1 l2 = match l1, l2 with One of the lists is empty : reverse accumulator and return | [], _ | _, [] -> List.rev accum First and second head elements are physically equal : add first head element to accumulator head element to accumulator *) | h1 :: tl1, h2 :: tl2 when h1 == h2 -> list_inter_uniq cmp (h1 :: accum) tl1 tl2 First head element is smaller than second : remove first head element from list element from list *) | h1 :: tl, h2 :: _ when cmp h1 h2 < 0 -> list_inter_uniq cmp accum tl l2 First head element is greater than or structurally but not physically equal to second : remove second head element from list physically equal to second: remove second head element from list *) | _ :: _, _ :: tl -> list_inter_uniq cmp accum l1 tl in list_inter_uniq cmp [] l1 l2 From two sorted lists without physical duplicates return a sorted list without physical duplicates containing elements in the first but not in the second list list without physical duplicates containing elements in the first but not in the second list *) let list_diff_uniq cmp l1 l2 = let rec list_diff_uniq cmp accum l1 l2 = match l1, l2 with First list is empty : reverse accumulator and return | [], _ -> List.rev accum Second list is empty : reverse accumulator , append first list and return and return *) | l, [] -> List.rev_append accum l First and second head elements are physically equal : remove both head elements both head elements *) | h1 :: tl1, h2 :: tl2 when h1 == h2 -> list_diff_uniq cmp accum tl1 tl2 First head element is smaller than second : add first head element to accumulator element to accumulator *) | h1 :: tl, h2 :: _ when cmp h1 h2 < 0 -> list_diff_uniq cmp (h1 :: accum) tl l2 First head element is greater than second : remove first head element from list element from list *) | _ :: _, _ :: tl -> list_diff_uniq cmp accum l1 tl in list_diff_uniq cmp [] l1 l2 For two sorted lists without physical duplicates return true if the first list contains a physically equal element for each element in the second list first list contains a physically equal element for each element in the second list *) let rec list_subset_uniq cmp l1 l2 = match l1, l2 with | [], [] -> true First list is empty , but second list not : return true | [], _ -> true Second list is empty , but first list not : return false | _, [] -> false First and second head elements are physically equal : remove both head elements both head elements *) | h1 :: tl1, h2 :: tl2 when h1 == h2 -> list_subset_uniq cmp tl1 tl2 First head element is smaller than second : return false | h1 :: _, h2 :: _ when cmp h1 h2 < 0 -> false First head element is greater than the second or structurally but not physically equal : remove first head element but not physically equal: remove first head element *) | _ :: _, _ :: tl -> list_subset_uniq cmp l1 tl comparison of pairs let compare_pairs cmp_a cmp_b (a1, b1) (a2, b2) = let c_a = cmp_a a1 a2 in if c_a = 0 then cmp_b b1 b2 else c_a comparison of lists let rec compare_lists f l1 l2 = match l1, l2 with Two empty lists are equal | [], [] -> 0 | [], _ -> -1 | _, [] -> 1 Compare two non - empty lists | h1 :: tl1, h2 :: tl2 -> let c = f h1 h2 in if c = 0 then compare_lists f tl1 tl2 else c Given two ordered association lists with identical keys , push the values of each element of the first association list to the list of elements of the second association list . The returned association list is in the order of the input lists , the function [ equal ] is used to compare keys . values of each element of the first association list to the list of elements of the second association list. The returned association list is in the order of the input lists, the function [equal] is used to compare keys. *) let list_join equal l1 l2 = let rec list_join' equal accum l1 l2 = match l1, l2 with | [], [] -> List.rev accum | (((k1, v1) :: tl1), ((k2, v2) :: tl2)) when equal k1 k2 -> list_join' equal ((k1, (v1 :: v2)) :: accum) tl1 tl2 | _ -> failwith "list_join" in Second list is empty ? match l2 with Initialize with singleton elements from first list | [] -> List.map (fun (k, v) -> (k, [v])) l1 | _ -> list_join' equal [] l1 l2 let list_filter_map f = let rec aux accu = function | [] -> List.rev accu | x :: l -> match f x with | None -> aux accu l | Some v -> aux (v :: accu) l in aux [] let rec list_apply: ('a -> 'b) list -> 'a -> 'b list = fun fs arg -> match fs with | [] -> [] | f :: rest -> f arg :: (list_apply rest arg) let rec find_map f = function | [] -> None | h :: tl -> ( match f h with | None -> find_map f tl | v -> v ) let rec drop_last: 'a list -> 'a list = function | [] -> failwith "drop_last" | [_] -> [] | e :: r -> e :: drop_last r let array_max a = assert (Array.length a > 0); let max_val = ref a.(0) in Array.iter (fun x -> if x > !max_val then max_val := x else ()) a; !max_val module IntegerSet = Set.Make (Int) module IntegerHashtbl = Hashtbl.Make (struct type t = int let hash i = i let equal = (=) end) Generic pretty - printing let pp_print_arrayi pp sep ppf array = let n = Array.length array in let print_element i = if i = n-1 then pp ppf i array.(i) else (pp ppf i array.(i); fprintf ppf sep) in let indices = list_init (fun i -> i) n in List.iter print_element indices let pp_print_pair pp1 pp2 sep ppf (left, right) = pp1 ppf left; fprintf ppf sep; pp2 ppf right let pp_print_triple pp1 pp2 pp3 sep ppf (p1, p2, p3) = pp1 ppf p1; fprintf ppf sep; pp2 ppf p2; fprintf ppf sep; pp3 ppf p3 let rec pp_print_list pp sep ppf = function | [] -> () | e :: [] -> pp ppf e | e :: tl -> Output one element pp_print_list pp sep ppf [e]; fprintf ppf sep; pp_print_list pp sep ppf tl let rec pp_print_listi' pp sep ppf = function | (_, []) -> () | (i, e :: []) -> pp ppf i e | (i, e :: tl) -> Output one element pp ppf i e; fprintf ppf sep; pp_print_listi' pp sep ppf (succ i, tl) let pp_print_listi pp sep ppf l = pp_print_listi' pp sep ppf (0, l) let rec pp_print_list2i' pp sep ppf = function | _, [], [] -> () | i, [e1], [e2] -> pp ppf i e1 e2 | i, e1 :: tl1, e2 :: tl2 -> pp ppf i e1 e2; fprintf ppf sep; Output the rest of the two lists pp_print_list2i' pp sep ppf (succ i, tl1, tl2) | _ -> invalid_arg "pp_print_list2i" Pretty - print two lists of the same length with a counter of their elements elements *) let pp_print_list2i pp sep ppf l1 l2 = pp_print_list2i' pp sep ppf (0, l1, l2) let pp_print_paren_list ppf list = pp_print_string ppf "("; pp_print_list pp_print_string "@ " ppf list; pp_print_string ppf ")" let pp_print_option pp ppf = function | None -> fprintf ppf "None" | Some s -> fprintf ppf "@[<hv>Some@ %a@]" pp s let pp_print_if_not_empty s ppf = function | [] -> () | _ -> fprintf ppf s let string_of_t pp t = let buf = Buffer.create 80 in let ppf = formatter_of_buffer buf in pp ppf t; pp_print_flush ppf (); Buffer.contents buf let paren_string_of_string_list list = string_of_t pp_print_paren_list list let width_of_string s = let lines = Str.split (Str.regexp "\n") s in List.fold_left (fun max_width s -> max max_width (String.length s) ) 0 lines let escape_json_string s = let backslash = Str.regexp "\\" in let double_quotes = Str.regexp "\"" in let newline = Str.regexp "\n" in s |> Str.global_replace backslash "\\\\" |> Str.global_replace double_quotes "\'" |> Str.global_replace newline "\\n" let escape_xml_string s = let ltr = Str.regexp "<" in let gtr = Str.regexp ">" in let ampr = Str.regexp "&" in s |> Str.global_replace ltr "&lt;" |> Str.global_replace gtr "&gt;" |> Str.global_replace ampr "&amp;" let get = function None -> raise (Invalid_argument "get") | Some x -> x let is_some = function | Some _ -> true | None -> false let join = function | Some x -> x | None -> None let min_option f1 f2 = match f1, f2 with | None, None -> None | Some f, None | None, Some f -> Some f | Some f1, Some f2 -> if f1 < f2 then Some f1 else Some f2 Return true if the first characters of [ s1 ] up to the length of [ s2 ] are ientical to [ s2 ] . Return false if [ s2 ] is longer than [ s1 ] . [s2] are ientical to [s2]. Return false if [s2] is longer than [s1]. *) let string_starts_with s1 s2 = (String.length s1 >= String.length s2) && (String.sub s1 0 (String.length s2) = s2) type log_level = | L_off | L_fatal | L_error | L_warn | L_note | L_info | L_debug | L_trace let default_log_level = L_note let int_of_log_level = function | L_off -> -1 | L_fatal -> 0 | L_error -> 1 | L_warn -> 2 | L_note -> 3 | L_info -> 4 | L_debug -> 5 | L_trace -> 6 let log_level_of_int = function | -1 -> L_off | 0 -> L_fatal | 1 -> L_error | 2 -> L_warn | 3 -> L_note | 4 -> L_info | 5 -> L_debug | 6 -> L_trace | _ -> raise (Invalid_argument "log_level_of_int") let string_of_log_level = function | L_off -> "off" | L_fatal -> "fatal" | L_error -> "error" | L_warn -> "warn" | L_note -> "note" | L_info -> "info" | L_debug -> "debug" | L_trace -> "trace" Compare two levels let compare_levels l1 l2 = Int.compare (int_of_log_level l1) (int_of_log_level l2) let log_level = ref L_warn let set_log_level l = log_level := l let get_log_level () = !log_level let output_on_level level = compare_levels level !log_level <= 0 Return fprintf if level is is of higher or equal priority than current log level , otherwise return ifprintf than current log level, otherwise return ifprintf *) let ignore_or_fprintf level = if output_on_level level then fprintf else ifprintf let ignore_or_kfprintf level = if output_on_level level then kfprintf else ikfprintf let log_ppf = ref std_formatter let log_to_file f = Open channel to logfile let oc = try open_out f with | Sys_error _ -> failwith "Could not open logfile" in log_ppf := formatter_of_out_channel oc let log_to_stdout () = log_ppf := std_formatter let pp_print_banner ppf () = fprintf ppf "%s %s" Version.package_name Version.version let pp_print_version ppf = pp_print_banner ppf () type kind_module = [ `IC3 | `BMC | `IND | `IND2 | `INVGEN | `INVGENOS | `INVGENINT | `INVGENINTOS | `INVGENMACH | `INVGENMACHOS | `INVGENINT8 | `INVGENINT8OS | `INVGENINT16 | `INVGENINT16OS | `INVGENINT32 | `INVGENINT32OS | `INVGENINT64 | `INVGENINT64OS | `INVGENUINT8 | `INVGENUINT8OS | `INVGENUINT16 | `INVGENUINT16OS | `INVGENUINT32 | `INVGENUINT32OS | `INVGENUINT64 | `INVGENUINT64OS | `INVGENREAL | `INVGENREALOS | `C2I | `Interpreter | `Supervisor | `Parser | `Certif | `MCS | `CONTRACTCK ] let pp_print_kind_module ppf = function | `IC3 -> fprintf ppf "property directed reachability" | `BMC -> fprintf ppf "bounded model checking" | `IND -> fprintf ppf "inductive step" | `IND2 -> fprintf ppf "2-induction" | `INVGEN -> fprintf ppf "two state invariant generator (bool)" | `INVGENOS -> fprintf ppf "one state invariant generator (bool)" | `INVGENINT -> fprintf ppf "two state invariant generator (int)" | `INVGENINTOS -> fprintf ppf "one state invariant generator (int)" | `INVGENMACH -> fprintf ppf "two state invariant generator (mach int)" | `INVGENMACHOS -> fprintf ppf "one state invariant generator (mach int)" | `INVGENINT8 -> fprintf ppf "two state invariant generator (int8)" | `INVGENINT8OS -> fprintf ppf "one state invariant generator (int8)" | `INVGENINT16 -> fprintf ppf "two state invariant generator (int16)" | `INVGENINT16OS -> fprintf ppf "one state invariant generator (int16)" | `INVGENINT32 -> fprintf ppf "two state invariant generator (int32)" | `INVGENINT32OS -> fprintf ppf "one state invariant generator (int32)" | `INVGENINT64 -> fprintf ppf "two state invariant generator (int64)" | `INVGENINT64OS -> fprintf ppf "one state invariant generator (int64)" | `INVGENUINT8 -> fprintf ppf "two state invariant generator (uint8)" | `INVGENUINT8OS -> fprintf ppf "one state invariant generator (uint8)" | `INVGENUINT16 -> fprintf ppf "two state invariant generator (uint16)" | `INVGENUINT16OS -> fprintf ppf "one state invariant generator (uint16)" | `INVGENUINT32 -> fprintf ppf "two state invariant generator (uint32)" | `INVGENUINT32OS -> fprintf ppf "one state invariant generator (uint32)" | `INVGENUINT64 -> fprintf ppf "two state invariant generator (uint64)" | `INVGENUINT64OS -> fprintf ppf "one state invariant generator (uint64)" | `INVGENREAL -> fprintf ppf "two state invariant generator (real)" | `INVGENREALOS -> fprintf ppf "one state invariant generator (real)" | `C2I -> fprintf ppf "c2i" | `Interpreter -> fprintf ppf "interpreter" | `Supervisor -> fprintf ppf "invariant manager" | `Parser -> fprintf ppf "parser" | `Certif -> Format.fprintf ppf "certificate" | `MCS -> Format.fprintf ppf "minimal cut set" | `CONTRACTCK -> Format.fprintf ppf "contract checker" let string_of_kind_module = string_of_t pp_print_kind_module let short_name_of_kind_module = function | `IC3 -> "ic3" | `BMC -> "bmc" | `IND -> "ind" | `IND2 -> "ind2" | `INVGEN -> "invgents" | `INVGENOS -> "invgenos" | `INVGENINT -> "invgenintts" | `INVGENINTOS -> "invgenintos" | `INVGENMACH -> "invgenmachts" | `INVGENMACHOS -> "invgenmachos" | `INVGENINT8 -> "invgenint8ts" | `INVGENINT8OS -> "invgenint8os" | `INVGENINT16 -> "invgenint16ts" | `INVGENINT16OS -> "invgenint16os" | `INVGENINT32 -> "invgenint32ts" | `INVGENINT32OS -> "invgenint32os" | `INVGENINT64 -> "invgenuint64ts" | `INVGENINT64OS -> "invgenuint64os" | `INVGENUINT8 -> "invgenuint8ts" | `INVGENUINT8OS -> "invgenuint8os" | `INVGENUINT16 -> "invgenuint16ts" | `INVGENUINT16OS -> "invgenuint16os" | `INVGENUINT32 -> "invgenuint32ts" | `INVGENUINT32OS -> "invgenuint32os" | `INVGENUINT64 -> "invgenuint64ts" | `INVGENUINT64OS -> "invgenuint64os" | `INVGENREAL -> "invgenintts" | `INVGENREALOS -> "invgenintos" | `C2I -> "c2i" | `Interpreter -> "interp" | `Supervisor -> "super" | `Parser -> "parse" | `Certif -> "certif" | `MCS -> "mcs" | `CONTRACTCK -> "contractck" let kind_module_of_string = function | "IC3" -> `IC3 | "BMC" -> `BMC | "IND" -> `IND | "IND2" -> `IND2 | "INVGEN" -> `INVGEN | "INVGENOS" -> `INVGENOS | "INVGENINT" -> `INVGENINT | "INVGENINTOS" -> `INVGENINTOS | "INVGENMACH" -> `INVGENMACH | "INVGENMACHOS" -> `INVGENMACHOS | "INVGENINT8" -> `INVGENINT8 | "INVGENINT8OS" -> `INVGENINT8OS | "INVGENINT16" -> `INVGENINT16 | "INVGENINT16OS" -> `INVGENINT16OS | "INVGENINT32" -> `INVGENINT32 | "INVGENINT32OS" -> `INVGENINT32OS | "INVGENINT64" -> `INVGENINT64 | "INVGENINT64OS" -> `INVGENINT64OS | "INVGENUINT8" -> `INVGENUINT8 | "INVGENUINT8OS" -> `INVGENUINT8OS | "INVGENUINT16" -> `INVGENUINT16 | "INVGENUINT16OS" -> `INVGENUINT16OS | "INVGENUINT32" -> `INVGENUINT32 | "INVGENUINT32OS" -> `INVGENUINT32OS | "INVGENUINT64" -> `INVGENUINT64 | "INVGENUINT64OS" -> `INVGENUINT64OS | "INVGENREAL" -> `INVGENREAL | "INVGENREALOS" -> `INVGENREALOS | "C2I" -> `C2I | _ -> raise (Invalid_argument "kind_module_of_string") let int_of_kind_module = function | `CONTRACTCK -> -6 | `MCS -> -5 | `Certif -> -4 | `Parser -> -3 | `Interpreter -> -2 | `Supervisor -> -1 | `BMC -> 1 | `IND -> 2 | `IND2 -> 3 | `IC3 -> 4 | `INVGEN -> 5 | `INVGENOS -> 6 | `INVGENINT -> 7 | `INVGENINTOS -> 8 | `INVGENREAL -> 9 | `INVGENREALOS -> 10 | `C2I -> 11 | `INVGENINT8 -> 12 | `INVGENINT8OS -> 13 | `INVGENINT16 -> 14 | `INVGENINT16OS -> 15 | `INVGENINT32 -> 16 | `INVGENINT32OS -> 17 | `INVGENINT64 -> 18 | `INVGENINT64OS -> 19 | `INVGENUINT8 -> 20 | `INVGENUINT8OS -> 21 | `INVGENUINT16 -> 22 | `INVGENUINT16OS -> 23 | `INVGENUINT32 -> 24 | `INVGENUINT32OS -> 25 | `INVGENUINT64 -> 26 | `INVGENUINT64OS -> 27 | `INVGENMACH -> 28 | `INVGENMACHOS -> 29 exception TimeoutWall exception TimeoutVirtual exception Signal of int let string_of_signal = function | s when s = Sys.sigabrt -> "SIGABRT" | s when s = Sys.sigalrm -> "SIGALRM" | s when s = Sys.sigfpe -> "SIGFPE" | s when s = Sys.sighup -> "SIGHUP" | s when s = Sys.sigill -> "SIGILL" | s when s = Sys.sigint -> "SIGINT" | s when s = Sys.sigkill -> "SIGKILL" | s when s = Sys.sigpipe -> "SIGPIPE" | s when s = Sys.sigquit -> "SIGQUIT" | s when s = Sys.sigsegv -> "SIGSEGV" | s when s = Sys.sigterm -> "SIGTERM" | s when s = Sys.sigusr1 -> "SIGUSR1" | s when s = Sys.sigusr2 -> "SIGUSR2" | s when s = Sys.sigchld -> "SIGCHLD" | s when s = Sys.sigcont -> "SIGCONT" | s when s = Sys.sigstop -> "SIGSTOP" | s when s = Sys.sigtstp -> "SIGTSTP" | s when s = Sys.sigttin -> "SIGTTIN" | s when s = Sys.sigttou -> "SIGTTOU" | s when s = Sys.sigvtalrm -> "SIGVTALRM" | s when s = Sys.sigprof -> "SIGPROF" | s -> string_of_int s let pp_print_signal ppf s = fprintf ppf "%s" (string_of_signal s) let pp_print_process_status ppf = function | Unix.WEXITED s -> fprintf ppf "exited with return code %d" s | Unix.WSIGNALED s -> fprintf ppf "killed by signal %a" pp_print_signal s | Unix.WSTOPPED s -> fprintf ppf "stopped by signal %a" pp_print_signal s let exception_on_signal signal = printf " Signal % a caught " pp_print_signal signal ; raise (Signal signal) Sleep for seconds , resolution is in ms let minisleep sec = try Sleep for the given seconds , yield to other threads Thread.delay sec with Signal caught while in kernel | Unix.Unix_error(Unix.EINTR, _, _) -> raise (Signal 0) let find_on_path exec = let rec find_on_path' exec path = if path = "" then raise Not_found; let path_hd, path_tl = try let colon_index = String.index path ':' in let path_len = String.length path in (String.sub path 0 colon_index, String.sub path (colon_index + 1) (path_len - colon_index - 1)) with Not_found -> path, "" in Combine path and filename let exec_path = Filename.concat path_hd exec in if Sys.file_exists exec_path then exec_path else find_on_path' exec path_tl in try if Filename.is_relative exec then find_on_path' exec (Unix.getenv "PATH") else if Sys.file_exists exec then exec else raise Not_found with Not_found -> let exec_path = Filename.concat (Sys.getcwd ()) exec in if Sys.file_exists exec_path then exec_path else raise Not_found let rec find_file filename = function | [] -> None | dir :: include_dirs -> let path = Filename.concat dir filename in if Sys.file_exists path then Some path else find_file filename include_dirs Parser and lexer functions type position = { pos_fname : string; pos_lnum: int; pos_cnum: int } let equal_pos { pos_fname = p1; pos_lnum = l1; pos_cnum = c1 } { pos_fname = p2; pos_lnum = l2; pos_cnum = c2 } = l1=l2 && c1=c2 && String.equal p1 p2 let compare_pos { pos_fname = p1; pos_lnum = l1; pos_cnum = c1 } { pos_fname = p2; pos_lnum = l2; pos_cnum = c2 } = compare_pairs String.compare (compare_pairs Int.compare Int.compare) (p1, (l1, c1)) (p2, (l2, c2)) let dummy_pos = { pos_fname = ""; pos_lnum = 0; pos_cnum = -1 } let dummy_pos_in_file fname = { pos_fname = fname; pos_lnum = 0; pos_cnum = -1 } *) let pp_print_position ppf ( { pos_fname; pos_lnum; pos_cnum } as pos ) = if pos = dummy_pos then fprintf ppf "(unknown)" else if pos_lnum = 0 && pos_cnum = -1 then fprintf ppf "%s" pos_fname else let fname = if pos_fname = "" then "(stdin)" else pos_fname in fprintf ppf "%s:%d:%d" fname pos_lnum pos_cnum let pp_print_line_and_column ppf { pos_lnum; pos_cnum } = if pos_lnum >= 0 && pos_cnum >= 0 then fprintf ppf "[l%dc%d]" pos_lnum pos_cnum else fprintf ppf "[unknown]" let pp_print_lines_and_columns ppf positions = pp_print_list pp_print_line_and_column ", " ppf positions Convert a position from Lexing to a position let position_of_lexing { Lexing.pos_fname; Lexing.pos_lnum; Lexing.pos_bol; Lexing.pos_cnum } = { pos_fname = pos_fname; pos_lnum = pos_lnum; pos_cnum = pos_cnum - pos_bol + 1} let is_dummy_pos = function | { pos_cnum = -1 } -> true | _ -> false let file_row_col_of_pos = function | p when is_dummy_pos p -> raise (Invalid_argument "file_row_col_of_pos") | { pos_fname; pos_lnum; pos_cnum } -> (pos_fname, pos_lnum, pos_cnum) let file_of_pos { pos_fname } = pos_fname let row_col_of_pos = function | p when is_dummy_pos p -> raise (Invalid_argument "row_col_of_pos") | { pos_lnum; pos_cnum } -> (pos_lnum, pos_cnum) let print_backtrace fmt bt = match Printexc.backtrace_slots bt with | None -> () | Some slots -> let n = Array.length slots in Array.iteri (fun i s -> match Printexc.Slot.format i s with | None -> () | Some s -> pp_print_string fmt s; if i < n - 1 then pp_force_newline fmt () ) slots let pos_of_file_row_col (pos_fname, pos_lnum, pos_cnum) = { pos_fname; pos_lnum; pos_cnum } let set_lexer_filename lexbuf fname = lexbuf.Lexing.lex_curr_p <- {lexbuf.Lexing.lex_curr_p with pos_fname = fname} let split_dot s = let open String in let n = (index s '.') in sub s 0 n, sub s (n+1) (length s - n - 1) let extract_scope_name name = let rec loop s scope = try let next_scope, s' = split_dot s in loop s' (next_scope :: scope) with Not_found -> s, List.rev scope in loop name [] let create_dir dir = try if not (Sys.is_directory dir) then failwith (dir^" is not a directory") with Sys_error _ -> Unix.mkdir dir 0o755 Copy file . Implementation adapted from " Unix system programming in OCaml " by and Implementation adapted from "Unix system programming in OCaml" by Xavier Leroy and Didier Remy*) let copy_fds fd_in fd_out = let open Unix in let buffer_size = 8192 in let buffer = Bytes.create buffer_size in let rec copy_loop () = match read fd_in buffer 0 buffer_size with | 0 -> () | r -> ignore (write fd_out buffer 0 r); copy_loop () in copy_loop () let file_copy input_name output_name = let open Unix in let fd_in = openfile input_name [O_RDONLY] 0 in let fd_out = openfile output_name [O_WRONLY; O_CREAT; O_TRUNC] 0o666 in copy_fds fd_in fd_out; close fd_in; close fd_out let files_cat_open ?(add_prefix=fun _ -> ()) files output_name = let open Unix in let fd_out = openfile output_name [O_WRONLY; O_CREAT; O_TRUNC] 0o666 in add_prefix (out_channel_of_descr fd_out |> Format.formatter_of_out_channel); let _, fd_out = List.fold_left (fun (first, fd_out) input_name -> let fd_in = openfile input_name [O_RDONLY] 0 in copy_fds fd_in fd_out; let fd_out = if first then begin close fd_out; openfile output_name [O_WRONLY; O_CREAT; O_APPEND] 0o666 end else fd_out in false, fd_out ) (true, fd_out) files in fd_out let syscall cmd = let so, si, se = Unix.open_process_full cmd (Unix.environment ()) in let buf = Buffer.create 16 in (try while true do Buffer.add_channel buf so 1 done with End_of_file -> ()); ignore(Unix.close_process_full (so, si, se)); Buffer.contents buf let reset_gc_params = let gc_c = Gc.get() in fun () -> Gc.set gc_c let set_liberal_gc () = Gc.full_major (); let gc_c = { (Gc.get ()) with Gc.verbose = 0x3FF ; default 32000 default 124000 default 80 % des donnes vivantes } in Gc.set gc_c module Paths = struct let testgen = "tests" let oracle = "oracle" let implem = "implem" end module ReservedIds = struct let abs_ident_string = "abs" let oracle_ident_string = "nondet" let instance_ident_string = "instance" let init_flag_ident_string = "init_flag" let all_req_ident_string = "all_req" let all_ens_ident_string = "all_ens" let inst_ident_string = "inst" let init_uf_string = "__node_init" let trans_uf_string = "__node_trans" let index_ident_string = "__index" let function_of_inputs = "__function_of_inputs" let state_string = "state" let restart_string = "restart" let state_selected_string = "state.selected" let restart_selected_string = "restart.selected" let state_selected_next_string = "state.selected.next" let restart_selected_next_string = "restart.selected.next" let handler_string = "handler" let unless_string = "unless" Init flag string . let init_flag_string = "__init_flag" let depth_input_string = "__depth_input" let max_depth_input_string = "__max_depth_input" let reserved_strings = [ init_flag_string ; depth_input_string ; max_depth_input_string ; function_of_inputs ; abs_ident_string ; oracle_ident_string ; instance_ident_string ; init_flag_ident_string ; all_req_ident_string ; all_ens_ident_string ; inst_ident_string ; init_uf_string ; trans_uf_string ; index_ident_string ; ] end module ExitCodes = struct let unknown = 0 let unsafe = 10 let safe = 20 let error = 2 let kid_status = 128 end module Names = struct let contract_gen_file = "kind2_contract.lus" let contract_name = Format.asprintf "%a_spec" (pp_print_list Format.pp_print_string "_") let inv_log_file = "kind2_strengthening.lus" let inv_log_contract_name = Format.asprintf "%a_str_spec" (pp_print_list Format.pp_print_string "_") end Local Variables : compile - command : " make -C .. -k " tuareg - interactive - program : " ./kind2.top -I ./_build -I / SExpr " indent - tabs - mode : nil End : Local Variables: compile-command: "make -C .. -k" tuareg-interactive-program: "./kind2.top -I ./_build -I ./_build/SExpr" indent-tabs-mode: nil End: *)
9a7e8317048c30991c2ce82bc9d081ce4b4e1ce5960ad3fca4ca71900cd3e7f2
screenshotbot/screenshotbot-oss
binding.lisp
(pkg:define-package :util/java/binding (:use #:cl #:alexandria) (:import-from #:util/java/java #:invoke) (:export #:bind-instance)) (defun javafy-name (name) (let ((name (string name))) (cond ((str:ends-with-p "-P" name) (str:camel-case (format nil "is-~a" (cl-ppcre:regex-replace-all "-P$" name "")))) (t (str:camel-case (format nil "get-~A" name)))))) (defun bind-instance (type java-object) (let ((ret (make-instance type))) (loop for slot in (closer-mop:class-slots (find-class type)) do (let ((slot-name (closer-mop:slot-definition-name slot))) (setf (slot-value ret slot-name) (invoke java-object (javafy-name slot-name))))) ret))
null
https://raw.githubusercontent.com/screenshotbot/screenshotbot-oss/4e9a99ee9dac3821843238e357c86e31745f7df2/src/util/java/binding.lisp
lisp
(pkg:define-package :util/java/binding (:use #:cl #:alexandria) (:import-from #:util/java/java #:invoke) (:export #:bind-instance)) (defun javafy-name (name) (let ((name (string name))) (cond ((str:ends-with-p "-P" name) (str:camel-case (format nil "is-~a" (cl-ppcre:regex-replace-all "-P$" name "")))) (t (str:camel-case (format nil "get-~A" name)))))) (defun bind-instance (type java-object) (let ((ret (make-instance type))) (loop for slot in (closer-mop:class-slots (find-class type)) do (let ((slot-name (closer-mop:slot-definition-name slot))) (setf (slot-value ret slot-name) (invoke java-object (javafy-name slot-name))))) ret))
e547b14b45deb1c5e513ffe5926b80886600695918118e7cec5ac2deaf0ea6ee
ciderpunx/57-exercises-for-programmers
P16DrivingAgeSpec.hs
module P16DrivingAgeSpec (main,spec) where import Test.Hspec import P16DrivingAge hiding (main) main :: IO () main = hspec spec spec :: Spec spec = do describe "drivingMsg" $ do it "gives are of driving age for UK, 17" $ drivingMsg "UK" 17 `shouldBe` "You are old enough to drive in UK" it "gives are not of driving age for UK, 16" $ drivingMsg "UK" 16 `shouldBe` "You are not old enough to drive in UK" describe "countryStr" $ do it "gives UK for UK" $ countryStr "UK" `shouldBe` "UK" it "gives US for US" $ countryStr "US" `shouldBe` "US" it "gives UK and dont know msg for Belgium" $ countryStr "Belgium" `shouldBe` "UK, don't know about Belgium" describe "knownCountry" $ do it "is true for UK" $ knownCountry "UK" `shouldBe` True it "is true for US" $ knownCountry "US" `shouldBe` True it "is false for Belgium" $ knownCountry "Belgium" `shouldBe` False describe "isOfDrivingAge" $ do it "gives true for UK 17" $ isOfDrivingAge "UK" 17 `shouldBe` True it "gives true for UK 18" $ isOfDrivingAge "UK" 18 `shouldBe` True it "gives false for UK 16" $ isOfDrivingAge "UK" 16 `shouldBe` False it "gives true for US 16" $ isOfDrivingAge "US" 16 `shouldBe` True it "gives true for US 17" $ isOfDrivingAge "US" 17 `shouldBe` True it "gives false for US 15" $ isOfDrivingAge "US" 15 `shouldBe` False
null
https://raw.githubusercontent.com/ciderpunx/57-exercises-for-programmers/25958ab80cc3edc29756d3bddd2d89815fd390bf/test/P16DrivingAgeSpec.hs
haskell
module P16DrivingAgeSpec (main,spec) where import Test.Hspec import P16DrivingAge hiding (main) main :: IO () main = hspec spec spec :: Spec spec = do describe "drivingMsg" $ do it "gives are of driving age for UK, 17" $ drivingMsg "UK" 17 `shouldBe` "You are old enough to drive in UK" it "gives are not of driving age for UK, 16" $ drivingMsg "UK" 16 `shouldBe` "You are not old enough to drive in UK" describe "countryStr" $ do it "gives UK for UK" $ countryStr "UK" `shouldBe` "UK" it "gives US for US" $ countryStr "US" `shouldBe` "US" it "gives UK and dont know msg for Belgium" $ countryStr "Belgium" `shouldBe` "UK, don't know about Belgium" describe "knownCountry" $ do it "is true for UK" $ knownCountry "UK" `shouldBe` True it "is true for US" $ knownCountry "US" `shouldBe` True it "is false for Belgium" $ knownCountry "Belgium" `shouldBe` False describe "isOfDrivingAge" $ do it "gives true for UK 17" $ isOfDrivingAge "UK" 17 `shouldBe` True it "gives true for UK 18" $ isOfDrivingAge "UK" 18 `shouldBe` True it "gives false for UK 16" $ isOfDrivingAge "UK" 16 `shouldBe` False it "gives true for US 16" $ isOfDrivingAge "US" 16 `shouldBe` True it "gives true for US 17" $ isOfDrivingAge "US" 17 `shouldBe` True it "gives false for US 15" $ isOfDrivingAge "US" 15 `shouldBe` False
95ecfe4ab3779853c374f94afd1f70ca2f17f8fb00f893a038f0fb5e728f6fd6
andreasabel/miniagda
Eval.hs
# LANGUAGE TupleSections , FlexibleInstances , FlexibleContexts , NamedFieldPuns # # LANGUAGE NoImplicitPrelude # # LANGUAGE CPP # # OPTIONS_GHC -fno - warn - orphans # Activate this flag if i < $ i should only hold for i < # . # define module Eval where import Prelude hiding (mapM, null, pi) #if !MIN_VERSION_base(4,8,0) import Control.Applicative #endif import Control.Monad hiding (mapM) import Control.Monad.State (StateT, execStateT, get, gets, put) import Control.Monad.Except (runExcept, MonadError) import Control.Monad.Reader (asks, local) import qualified Data.Array as Array import qualified Data.List as List import qualified Data.Map as Map #if !MIN_VERSION_base(4,8,0) import Data.Foldable (foldMap) import Data.Monoid import Data.Traversable (traverse) #endif import Data.Traversable (mapM) -- import Debug.Trace (trace) import Abstract import Polarity as Pol import Value import TCM import PrettyTCM hiding ((<>)) import qualified PrettyTCM as P import Warshall -- positivity checking import TraceError import Util traceEta, traceRecord, traceMatch, traceLoop, traceSize :: String -> a -> a traceEtaM, traceRecordM, traceMatchM, traceLoopM, traceSizeM :: Monad m => String -> m () traceEta msg a = a -- trace msg a traceEtaM msg = return () -- traceM msg traceEta msg a = trace msg a traceEtaM msg = traceM msg traceEta msg a = trace msg a traceEtaM msg = traceM msg -} traceRecord msg a = a traceRecordM msg = return () traceMatch msg a = a -- trace msg a traceMatchM msg = return () -- traceM msg traceMatch msg a = trace msg a traceMatchM msg = traceM msg traceMatch msg a = trace msg a traceMatchM msg = traceM msg -} traceLoop msg a = a -- trace msg a traceLoopM msg = return () -- traceM msg {- traceLoop msg a = trace msg a traceLoopM msg = traceM msg -} traceSize msg a = a -- trace msg a traceSizeM msg = return () -- traceM msg {- traceSize msg a = trace msg a traceSizeM msg = traceM msg -} failValInv :: (MonadError TraceError m) => Val -> m a failValInv v = throwErrorMsg $ "internal error: value " ++ show v ++ " violates representation invariant" -- evaluation with rewriting ------------------------------------- Rewriting rules have the form blocked -- > pattern this means that at the root , at most one rewriting step is possible . Rewriting rules are considered computational , since they trigger new ( symbolic ) computations . At least they have to be applied in - pattern matching - equality checking When a new rule b -- > p is added , b should be in -- > normal form . Otherwise there could be inconsistencies , like adding both rules b -- > true b -- > false If after adding b -- > true b is rewritten to nf , then the second rule would be true -- > false , which can be captured by . Also , after adding a new rule , it could be used to rewrite the old rules . Implementation : - add a set of local rewriting rules to the context ( not to the state ) - keep values in -- > weak head normal form - untyped equality test between values Rewriting rules have the form blocked --> pattern this means that at the root, at most one rewriting step is possible. Rewriting rules are considered computational, since they trigger new (symbolic) computations. At least they have to be applied in - pattern matching - equality checking When a new rule b --> p is added, b should be in --> normal form. Otherwise there could be inconsistencies, like adding both rules b --> true b --> false If after adding b --> true b is rewritten to nf, then the second rule would be true --> false, which can be captured by MiniAgda. Also, after adding a new rule, it could be used to rewrite the old rules. Implementation: - add a set of local rewriting rules to the context (not to the state) - keep values in --> weak head normal form - untyped equality test between values -} class Reval a where reval' :: Valuation -> a -> TypeCheck a reval :: a -> TypeCheck a reval = reval' emptyVal instance Reval a => Reval (Maybe a) where reval' valu ma = traverse (reval' valu) ma instance Reval b => Reval (a,b) where reval' valu (x,v) = (x,) <$> reval' valu v instance Reval a => Reval [a] where reval' valu vs = mapM (reval' valu) vs instance Reval Env where reval' valu (Environ rho mmeas) = flip Environ mmeas <$> reval' valu rho no need to reevaluate , since only sizes -- | When combining valuations, the old one takes priority. -- @[sigma][tau]v = [[sigma]tau]v@ instance Reval Valuation where reval' valu (Valuation valu') = Valuation . (++ valuation valu) <$> reval' valu valu' instance Reval a => Reval (Measure a) where reval' valu beta = traverse (reval' valu) beta instance Reval a => Reval (Bound a) where reval' valu beta = traverse (reval' valu) beta instance Reval Val where reval' valu u = traceLoop ("reval " ++ show u) $ do let reval v = reval' valu v reEnv rho = reval' valu rho reFun fv = reval' valu fv case u of VSort (CoSet v) -> VSort . CoSet <$> reval v VSort{} -> return u VInfty -> return u VZero -> return u VSucc{} -> return u -- no rewriting in size expressions VMax{} -> return u VPlus{} -> return u VProj{} -> return u -- cannot rewrite projection VPair v1 v2 -> VPair <$> reval v1 <*> reval v2 VRecord ri rho -> VRecord ri <$> mapAssocM reval rho VApp v vl -> do v' <- reval v vl' <- mapM reval vl w <- foldM app v' vl' reduce w -- since we only have rewrite rules at base types -- we do not need to reduces prefixes of w VDef{} -> return $ VApp u [] -- restore invariant CAN'T rewrite defined fun / data VGen i -> reduce (valuateGen i valu) -- CAN rewrite variable VCase v tv env cl -> do v' <- reval v tv' <- reval tv env' <- reEnv env evalCase v' tv' env' cl VBelow ltle v -> VBelow ltle <$> reval v VGuard beta v -> VGuard <$> reval beta <*> reval v VQuant pisig x dom fv -> VQuant pisig x <$> mapM reval dom <*> reFun fv > do dom ' < - mapM reval dom env ' < - reEnv env return $ VQuant pisig x dom ' env ' b VQuant pisig x dom env b -> do dom' <- mapM reval dom env' <- reEnv env return $ VQuant pisig x dom' env' b -} VConst v -> VConst <$> reval' valu v VLam x env e -> flip (VLam x) e <$> reval' valu env VAbs x i v valu' -> VAbs x i v <$> reval' valu valu' VUp v tv -> up False ==<< (reval' valu v, reval' valu tv) -- do not force at this point VClos env e -> do env' <- reEnv env return $ VClos env' e VMeta i env k -> do env' <- reEnv env return $ VMeta i env' k VSing v tv -> vSing ==<< (reval v, reval tv) VIrr -> return u v -> throwErrorMsg $ "NYI : reval " ++ show v TODO : singleton Sigma types -- <t : Pi x:a.f> = Pi x:a <t x : f x> -- <t : A -> B > = Pi x:A <t x : B> -- <t : <t' : a>> = <t' : a> vSing :: Val -> TVal -> TypeCheck TVal vSing v (VQuant Pi x' dom fv) = do let x = fresh $ if emptyName x' then "xSing#" else suggestion x' VQuant Pi x dom <$> do underAbs_ x dom fv $ \ i xv bv -> do v <- app v xv vAbs x i <$> vSing v bv vSing _ tv@(VSing{}) = return $ tv vSing v tv = return $ VSing v tv -- This is a bit of a hack ( finding a fresh name ) -- < t : Pi x : : a < t x : b > -- < t : Pi x : a.f > = Pi x : a < t x : f x > -- < t : < t ' : a > > = < t ' : a > vSing : : Val - > TVal - > TVal vSing v ( VQuant Pi x dom env b ) | not ( emptyName x ) = -- xv ` seq ` x ' ` seq ` ( VQuant Pi x dom ( update env xv v ) $ Sing ( App ( ) ( Var x ) ) b ) where xv = fresh ( " vSing # " + + suggestion x ) vSing v ( VQuant Pi x dom env b ) = -- | otherwise = ( VQuant Pi x ' dom ( update env xv v ) $ Sing ( App ( ) ( Var x ' ) ) b ' ) where xv = fresh ( " vSing # " + + suggestion x ) x ' = fresh $ if emptyName x then " xSing # " else suggestion x b ' = parSubst ( \ y - > Var $ if y = = x then x ' else y ) b vSing _ tv@(VSing { } ) = tv vSing v tv = VSing v tv -- This is a bit of a hack (finding a fresh name) -- <t : Pi x:a.b> = Pi x:a <t x : b> -- <t : Pi x:a.f> = Pi x:a <t x : f x> -- <t : <t' : a>> = <t' : a> vSing :: Val -> TVal -> TVal vSing v (VQuant Pi x dom env b) | not (emptyName x) = -- xv `seq` x' `seq` (VQuant Pi x dom (update env xv v) $ Sing (App (Var xv) (Var x)) b) where xv = fresh ("vSing#" ++ suggestion x) vSing v (VQuant Pi x dom env b) = -- | otherwise = (VQuant Pi x' dom (update env xv v) $ Sing (App (Var xv) (Var x')) b') where xv = fresh ("vSing#" ++ suggestion x) x' = fresh $ if emptyName x then "xSing#" else suggestion x b' = parSubst (\ y -> Var $ if y == x then x' else y) b vSing _ tv@(VSing{}) = tv vSing v tv = VSing v tv -} -- reduce the root of a value reduce :: Val -> TypeCheck Val reduce v = traceLoop ("reduce " ++ show v) $ do rewrules <- asks rewrites mr <- findM (\ rr -> equal v (lhs rr)) rewrules case mr of Nothing -> return v Just rr -> traceRew ("firing " ++ show rr) $ return (rhs rr) -- equal v v' tests values for untyped equality -- precond: v v' are in --> whnf equal :: Val -> Val -> TypeCheck Bool equal u1 u2 = traceLoop ("equal " ++ show u1 ++ " =?= " ++ show u2) $ case (u1,u2) of (v1,v2) | v1 == v2 -> return True -- includes all size expressions -- (VSucc v1, VSucc v2) -> equal v1 v2 -- NO REDUCING NECC. HERE (Size expr) (VApp v1 vl1, VApp v2 vl2) -> (equal v1 v2) `andLazy` (equals' vl1 vl2) (VQuant pisig1 x1 dom1 fv1, VQuant pisig2 x2 dom2 fv2) | pisig1 == pisig2 -> andLazy (equal (typ dom1) (typ dom2)) $ -- NO RED. NECC. (Type) new x1 dom1 $ \ vx -> equal ==<< (app fv1 vx, app fv2 vx) (VProj _ p, VProj _ q) -> return $ p == q (VPair v1 w1, VPair v2 w2) -> (equal v1 v2) `andLazy` (equal w1 w2) (VBelow ltle1 v1, VBelow ltle2 v2) | ltle1 == ltle2 -> equal v1 v2 (VSing v1 tv1, VSing v2 tv2) -> (equal v1 v2) `andLazy` (equal tv1 tv2) PROBLEM : DOM . MISSING , CAN'T " up " fresh variable addName (bestName [absName fv1, absName fv2]) $ \ vx -> equal ==<< (app fv1 vx, app fv2 vx) {- (VLam x1 env1 b1, VLam x2 env2 b2) -> -- PROBLEM: DOMAIN MISSING addName x1 $ \ vx -> do -- CAN'T "up" fresh variable do v1 <- whnf (update env1 x1 vx) b1 v2 <- whnf (update env2 x2 vx) b2 equal v1 v2 -} (VRecord ri1 rho1, VRecord ri2 rho2) | notDifferentNames ri1 ri2 -> and <$> zipWithM (\ (n1,v1) (n2,v2) -> ((n1 == n2) &&) <$> equal' v1 v2) rho1 rho2 _ -> return False notDifferentNames :: RecInfo -> RecInfo -> Bool notDifferentNames (NamedRec _ n _ _) (NamedRec _ n' _ _) = n == n' notDifferentNames _ _ = True equals' :: [Val] -> [Val] -> TypeCheck Bool equals' [] [] = return True equals' (w1:vs1) (w2:vs2) = (equal' w1 w2) `andLazy` (equals' vs1 vs2) equals' vl1 vl2 = return False equal' :: Val -> Val -> TypeCheck Bool equal' w1 w2 = whnfClos w1 >>= \ v1 -> equal v1 =<< whnfClos w2 {- LEADS TO NON-TERMINATION -- equal' v1 v2 tests values for untyped equality -- v1 v2 are not necessarily in --> whnf equal' v1 v2 = do v1' <- reduce v1 v2' <- reduce v2 equal v1' v2' -} -- normalization ----------------------------------------------------- reify :: Val -> TypeCheck Expr reify v = reify' (5, True) v -- normalize to depth m reify' :: (Int, Bool) -> Val -> TypeCheck Expr reify' m v0 = do let reify = reify' m -- default recursive call case v0 of (VClos rho e) -> whnf rho e >>= reify (VZero) -> return $ Zero (VInfty) -> return $ Infty (VSucc v) -> Succ <$> reify v (VMax vs) -> maxE <$> mapM reify vs (VPlus vs) -> Plus <$> mapM reify vs (VMeta x rho n) -> -- error $ "cannot reify meta-variable " ++ show v0 return $ iterate Succ (Meta x) !! n (VSort (CoSet v)) -> Sort . CoSet <$> reify v (VSort s) -> return $ Sort $ vSortToSort s (VBelow ltle v) -> Below ltle <$> reify v (VQuant pisig x dom fv) -> do dom' <- mapM reify dom underAbs_ x dom fv $ \ k xv vb -> do let x' = unsafeName (suggestion x ++ "~" ++ show k) piSig pisig (TBind x' dom') <$> reify vb (VSing v tv) -> liftM2 Sing (reify v) (reify tv) fv | isFun fv -> do let x = absName fv addName x $ \ xv@(VGen k) -> do vb <- app fv xv let x' = unsafeName (suggestion x ++ "~" ++ show k) TODO : dec ! ? (VUp v tv) -> reify v -- TODO: type directed reification (VGen k) -> return $ Var $ unsafeName $ "~" ++ show k (VDef d) -> return $ Def d (VProj fx n) -> return $ Proj fx n (VPair v1 v2) -> Pair <$> reify v1 <*> reify v2 (VRecord ri rho) -> Record ri <$> mapAssocM reify rho (VApp v vl) -> if fst m > 0 && snd m then force v0 >>= reify' (fst m - 1, True) -- forgotten the meaning of the boolean, WAS: False) else let m' = (fst m, True) in liftM2 (foldl App) (reify' m' v) (mapM (reify' m') vl) (VCase v tv rho cls) -> do e <- reify v t <- reify tv return $ Case e (Just t) cls -- TODO: properly evaluate clauses!! (VIrr) -> return $ Irr v -> failDoc (text "Eval.reify" <+> prettyTCM v <+> text "not implemented") printing ( conversion to ) ------------------------------------- -- similar to reify toExpr :: Val -> TypeCheck Expr toExpr v = case v of VClos rho e -> closToExpr rho e VZero -> return $ Zero VInfty -> return $ Infty (VSucc v) -> Succ <$> toExpr v VMax vs -> maxE <$> mapM toExpr vs VPlus vs -> Plus <$> mapM toExpr vs VMeta x rho n -> metaToExpr x rho n VSort s -> Sort <$> mapM toExpr s {- VSort (CoSet v) -> (Sort . CoSet) <$> toExpr v VSort (Set v) -> (Sort . Set) <$> toExpr v VSort (SortC s) -> return $ Sort (SortC s) -} VMeasured mu bv -> pi <$> (TMeasure <$> mapM toExpr mu) <*> toExpr bv VGuard beta bv -> pi <$> (TBound <$> mapM toExpr beta) <*> toExpr bv VBelow Le VInfty -> return $ Sort $ SortC Size VBelow ltle bv -> Below ltle <$> toExpr bv VQuant pisig x dom fv -> underAbs' x fv $ \ xv bv -> piSig pisig <$> (TBind x <$> mapM toExpr dom) <*> toExpr bv VSing v tv -> Sing <$> toExpr v <*> toExpr tv fv | isFun fv -> addName (absName fv) $ \ xv -> toExpr =<< app fv xv VLam x rho e - > addNameEnv x rho $ \ x rho - > defaultDec x < $ > closToExpr rho e VLam x rho e -> addNameEnv x rho $ \ x rho -> Lam defaultDec x <$> closToExpr rho e -} VUp v tv -> toExpr v VGen k -> Var <$> nameOfGen k VDef d -> return $ Def d VProj fx n -> return $ Proj fx n VPair v1 v2 -> Pair <$> toExpr v1 <*> toExpr v2 VRecord ri rho -> Record ri <$> mapAssocM toExpr rho VApp v vl -> liftM2 (foldl App) (toExpr v) (mapM toExpr vl) VCase v tv rho cls -> Case <$> toExpr v <*> (Just <$> toExpr tv) <*> mapM (clauseToExpr rho) cls VIrr -> return $ Irr {- addBindEnv :: TBind -> Env -> (Env -> TypeCheck a) -> TypeCheck a addBindEnv (TBind x dom) rho cont = do let dom' = fmap (VClos rho) dom newWithGen x dom' $ \ k _ -> cont (update rho x (VGen k)) -} addNameEnv :: Name -> Env -> (Name -> Env -> TypeCheck a) -> TypeCheck a --addNameEnv "" rho cont = cont "" rho addNameEnv x rho cont = do let dom' = defaultDomain VIrr -- error $ "internal error: variable " ++ show x ++ " comes without domain" newWithGen x dom' $ \ k _ -> do x' <- nameOfGen k cont x' (update rho x (VGen k)) addPatternEnv :: Pattern -> Env -> (Pattern -> Env -> TypeCheck a) -> TypeCheck a addPatternEnv p rho cont = case p of VarP x -> addNameEnv x rho $ cont . VarP -- \ x rho -> cont (VarP x) rho SizeP e x -> addNameEnv x rho $ cont . VarP PairP p1 p2 -> addPatternEnv p1 rho $ \ p1 rho -> addPatternEnv p2 rho $ \ p2 rho -> cont (PairP p1 p2) rho \ ps rho - > cont ( ConP pi n ps ) rho SuccP p -> addPatternEnv p rho $ cont . SuccP UnusableP p -> addPatternEnv p rho $ cont . UnusableP DotP e -> do { e <- closToExpr rho e ; cont (DotP e) rho } AbsurdP -> cont AbsurdP rho ErasedP p -> addPatternEnv p rho $ cont . ErasedP addPatternsEnv :: [Pattern] -> Env -> ([Pattern] -> Env -> TypeCheck a) -> TypeCheck a addPatternsEnv [] rho cont = cont [] rho addPatternsEnv (p:ps) rho cont = addPatternEnv p rho $ \ p rho -> addPatternsEnv ps rho $ \ ps rho -> cont (p:ps) rho {- class BindClosToExpr a where bindClosToExpr :: Env -> a -> (Env -> a -> TCM b) -> TCM b instance ClosToExpr a => BindClosToExpr (TBinding a) where bindClosToExpr -} class ClosToExpr a where closToExpr :: Env -> a -> TypeCheck a bindClosToExpr :: Env -> a -> (Env -> a -> TypeCheck b) -> TypeCheck b -- default : no binding closToExpr rho a = bindClosToExpr rho a $ \ rho a -> return a bindClosToExpr rho a cont = cont rho =<< closToExpr rho a instance ClosToExpr a => ClosToExpr [a] where closToExpr = traverse . closToExpr instance ClosToExpr a => ClosToExpr (Maybe a) where closToExpr = traverse . closToExpr instance ClosToExpr a => ClosToExpr (Dom a) where closToExpr = traverse . closToExpr instance ClosToExpr a => ClosToExpr (Sort a) where closToExpr = traverse . closToExpr instance ClosToExpr a => ClosToExpr (Measure a) where closToExpr = traverse . closToExpr instance ClosToExpr a => ClosToExpr (Bound a) where closToExpr = traverse . closToExpr instance ClosToExpr a => ClosToExpr (Tagged a) where closToExpr = traverse . closToExpr instance ClosToExpr a => ClosToExpr (TBinding a) where bindClosToExpr rho (TBind x a) cont = do a <- closToExpr rho a addNameEnv x rho $ \ x rho -> cont rho $ TBind x a bindClosToExpr rho (TMeasure mu) cont = cont rho . TMeasure =<< closToExpr rho mu bindClosToExpr rho (TBound beta) cont = cont rho . TBound =<< closToExpr rho beta instance ClosToExpr Telescope where bindClosToExpr rho (Telescope tel) cont = loop rho tel $ \ rho -> cont rho . Telescope where loop rho [] cont = cont rho [] loop rho (tb : tel) cont = bindClosToExpr rho tb $ \ rho tb -> loop rho tel $ \ rho tel -> cont rho $ tb : tel instance ClosToExpr Expr where closToExpr rho e = case e of Sort s -> Sort <$> closToExpr rho s Zero -> return e Succ e -> Succ <$> closToExpr rho e Infty -> return e Max es -> Max <$> closToExpr rho es Plus es -> Plus <$> closToExpr rho es Meta x -> return e Var x -> toExpr =<< whnf rho e Def d -> return e Case e mt cls -> Case <$> closToExpr rho e <*> closToExpr rho mt <*> mapM (clauseToExpr rho) cls LLet tb tel e1 e2 | null tel -> do e1 <- closToExpr rho e1 bindClosToExpr rho tb $ \ rho tb -> LLet tb tel e1 <$> closToExpr rho e2 Proj fx n -> return e Record ri rs -> Record ri <$> mapAssocM (closToExpr rho) rs Pair e1 e2 -> Pair <$> closToExpr rho e1 <*> closToExpr rho e2 App e1 e2 -> App <$> closToExpr rho e1 <*> closToExpr rho e2 Lam dec x e -> addNameEnv x rho $ \ x rho -> Lam dec x <$> closToExpr rho e Below ltle e -> Below ltle <$> closToExpr rho e { } e | null tel - > pi < $ > closToExpr rho mu < * > closToExpr rho e { } e | null tel - > pi < $ > closToExpr rho beta < * > closToExpr rho e Quant Pi tel mu@TMeasure{} e | null tel -> pi <$> closToExpr rho mu <*> closToExpr rho e Quant Pi tel beta@TBound{} e | null tel -> pi <$> closToExpr rho beta <*> closToExpr rho e -} Quant piSig tb e -> bindClosToExpr rho tb $ \ rho tb -> Quant piSig tb <$> closToExpr rho e -- Quant piSig tel tb e -> bindClosToExpr rho tel $ \ rho tel -> -- bindClosToExpr rho tb $ \ rho tb -> Quant piSig tel tb <$> closToExpr rho e Sing e1 e2 -> Sing <$> closToExpr rho e1 <*> closToExpr rho e2 Ann taggedE -> Ann <$> closToExpr rho taggedE Irr -> return e metaToExpr :: Int -> Env -> Int -> TypeCheck Expr metaToExpr x rho k = return $ iterate Succ (Meta x) !! k clauseToExpr :: Env -> Clause -> TypeCheck Clause clauseToExpr rho (Clause vtel ps me) = addPatternsEnv ps rho $ \ ps rho -> Clause vtel ps <$> mapM (closToExpr rho) me -- evaluation -------------------------------------------------------- -- | Weak head normal form. , since it reads the globally defined constants from the signature . are expanded away . whnf :: Env -> Expr -> TypeCheck Val whnf env e = enter ("whnf " ++ show e) $ case e of Meta i -> do let v = VMeta i env 0 traceMetaM $ "whnf meta " ++ show v return v LLet (TBind x dom) tel e1 e2 | null tel -> do let v1 = mkClos env e1 whnf (update env x v1) e2 -- ALT : remove erased lambdas entirely e1 | erased dec - > whnf env e1 | otherwise - > return $ VLam x env e1 -- ALT: remove erased lambdas entirely Lam dec x e1 | erased dec -> whnf env e1 | otherwise -> return $ VLam x env e1 -} Lam dec x e1 -> return $ vLam x env e1 Below ltle e -> VBelow ltle <$> whnf env e Quant pisig (TBind x dom) b -> do Pi is strict in its first argument return $ VQuant pisig x dom' $ vLam x env b -- a measured type evaluates to -- - a bounded type if measure present in environment (rhs of funs) - otherwise to a measured type ( lhs of funs ) Quant Pi (TMeasure mu) b -> do muv <- whnfMeasure env mu bv <- whnf env b -- not adding measure constraint to context! case (envBound env) of Nothing -> return $ VMeasured muv bv -- throwErrorMsg $ "panic: whnf " ++ show e ++ " : no measure in environment " ++ show env Just muv' -> return $ VGuard (Bound Lt muv muv') bv Quant Pi (TBound (Bound ltle mu mu')) b -> do muv <- whnfMeasure env mu muv' <- whnfMeasure env mu' bv <- whnf env b -- not adding measure constraint to context! return $ VGuard (Bound ltle muv muv') bv Sing e t -> do tv <- whnf env t sing env e tv Pair e1 e2 -> VPair <$> whnf env e1 <*> whnf env e2 Proj fx n -> return $ VProj fx n Record ri@(NamedRec Cons _ _ _) rs -> VRecord ri <$> mapAssocM (whnf env) rs -- coinductive and anonymous records are treated lazily: Record ri rs -> return $ VRecord ri $ mapAssoc (mkClos env) rs -- ALT : filter out all erased arguments from application App e1 el - > do v1 < - whnf env e1 vl < - liftM ( filter ( /= VIrr ) ) $ mapM ( whnf env ) el app v1 vl -- ALT: filter out all erased arguments from application App e1 el -> do v1 <- whnf env e1 vl <- liftM (filter (/= VIrr)) $ mapM (whnf env) el app v1 vl -} App f e -> do vf <- whnf env f let ve = mkClos env e app vf ve App e1 el - > do v1 < - whnf env e1 vl < - mapM ( whnf env ) el app v1 vl App e1 el -> do v1 <- whnf env e1 vl <- mapM (whnf env) el app v1 vl -} Case e (Just t) cs -> do v <- whnf env e vt <- whnf env t evalCase v vt env cs -- trace ("case head evaluates to " ++ showVal v) $ return () Sort s -> whnfSort env s >>= return . vSort Infty -> return VInfty Zero -> return VZero Succ e1 -> do v <- whnf env e1 -- succ is strict return $ succSize v Max es -> do vs <- mapM (whnf env) es -- max is strict return $ maxSize vs Plus es -> do vs <- mapM (whnf env) es -- plus is strict return $ plusSizes vs Def (DefId LetK n) -> do item <- lookupSymbQ n whnfClos (definingVal item) Def (DefId (ConK DefPat) n) -> whnfClos . definingVal =<< lookupSymbQ n ( DefId ( ConK DefPat ) n ) - > throwErrorMsg $ " internal error : whnf of defined pattern " + + show n Def id -> return $ vDef id Con co n - > return $ VCon co n Def n - > return $ VDef n Let n - > do sig < - gets signature let ( LetSig _ v ) = lookupSig n sig return v -- let ( LetSig _ e ) = lookupSig n sig -- whnf [ ] e Con co n -> return $ VCon co n Def n -> return $ VDef n Let n -> do sig <- gets signature let (LetSig _ v) = lookupSig n sig return v -- let (LetSig _ e) = lookupSig n sig -- whnf [] e -} Var y -> lookupEnv env y >>= whnfClos return VIrr -- NEED TO KEEP because of eta - exp ! Irr -> return VIrr e -> throwErrorMsg $ "NYI whnf " ++ show e whnfMeasure :: Env -> Measure Expr -> TypeCheck (Measure Val) whnfMeasure rho (Measure mu) = mapM (whnf rho) mu >>= return . Measure whnfSort :: Env -> Sort Expr -> TypeCheck (Sort Val) whnfSort rho (SortC c) = return $ SortC c whnfSort rho (CoSet e) = whnf rho e >>= return . CoSet whnfSort rho (Set e) = whnf rho e >>= return . Set whnfClos :: Clos -> TypeCheck Val whnfClos v = -- trace ("whnfClos " ++ show v) $ case v of (VClos e rho) -> whnf e rho ( VApp ( VProj Pre n ) [ u ] ) - > app u ( VProj Post n ) -- NO EFFECT THIS IS TO SOLVE A PROBLEM v -> return v {- THE PROBLEM IS that (tail (x Up Stream)) Up Stream is a whnf, because Up Stream is lazy in equality checking this is a problem when the Up is removed. -} -- evaluate in standard environment whnf' :: Expr -> TypeCheck Val whnf' e = do env <- getEnv whnf env e < t : Pi x : : a < t x : b > -- <t : <t' : a>> = <t' : a> sing :: Env -> Expr -> TVal -> TypeCheck TVal sing rho e tv = do let v = mkClos rho e -- v <- whnf rho e vSing v tv sing env ' e ( VPi dec x av env b ) = do return $ VPi dec x ' av env '' ( Sing ( App e ( Var x ' ) ) b ) where env '' = env ' + + env -- super ugly HACK x ' = if x = = " " then fresh env '' else x -- Should work with just x since shadowing is forbidden sing _ _ tv@(VSing { } ) = return $ tv sing env e tv = do v < - whnf env e -- singleton strict , is this OK ? ! return $ VSing v tv sing env' e (VPi dec x av env b) = do return $ VPi dec x' av env'' (Sing (App e (Var x')) b) where env'' = env' ++ env -- super ugly HACK x' = if x == "" then fresh env'' else x -- Should work with just x since shadowing is forbidden sing _ _ tv@(VSing{}) = return $ tv sing env e tv = do v <- whnf env e -- singleton strict, is this OK?! return $ VSing v tv -} sing' :: Expr -> TVal -> TypeCheck TVal sing' e tv = do env <- getEnv sing env e tv evalCase :: Val -> TVal -> Env -> [Clause] -> TypeCheck Val evalCase v tv env cs = do m <- matchClauses env cs [v] case m of Nothing -> return $ VCase v tv env cs Just v' -> return $ v' piApp :: TVal -> Clos -> TypeCheck TVal piApp (VGuard beta bv) w = piApp bv w piApp (VQuant Pi x dom fv) w = app fv w piApp tv@(VApp (VDef (DefId DatK n)) vl) (VProj Post p) = projectType tv p VIrr -- no rec value here piApp tv w = failDoc (text "piApp: IMPOSSIBLE to instantiate" <+> prettyTCM tv <+> text "to argument" <+> prettyTCM w) piApps :: TVal -> [Clos] -> TypeCheck TVal piApps tv [] = return tv piApps tv (v:vs) = do tv' <- piApp tv v piApps tv' vs updateValu :: Valuation -> Int -> Val -> TypeCheck Valuation updateValu valu i v = reval' (sgVal i v) valu in app u v , u might be a VDef ( e.g. when coming from reval ) app :: Val -> Clos -> TypeCheck Val app = app' True -- | Application of arguments and projections. app' :: Bool -> Val -> Clos -> TypeCheck Val app' expandDefs u v = do let app = app' expandDefs appDef' True f vs = appDef f vs appDef' False f vs = return $ VDef (DefId FunK f) `VApp` vs appDef_ = appDef' expandDefs case u of VProj Pre n -> flip (app' expandDefs) (VProj Post n) =<< whnfClos v VRecord ri rho -> do let VProj Post n = v maybe (throwErrorMsg $ "app: projection " ++ show n ++ " not found in " ++ show u) whnfClos (lookup n rho) VDef (DefId FunK n) -> appDef_ n [v] VApp (VDef (DefId FunK n)) vl -> appDef_ n (vl ++ [v]) VApp h@(VDef (DefId (ConK Cons) n)) vl -> do v <- whnfClos v -- inductive constructors are strict! return $ VApp h (vl ++ [v]) -- VDef n -> appDef n [v] VApp ( VDef i d ) vl - > VApp ( VDef i d ) ( vl + + [ v ] ) VApp v1 vl -> return $ VApp v1 (vl ++ [v]) -- VSing is a type! VSing u ( ) - > vSing < $ > app u v < * > app fu v VLam x env e -> whnf (update env x v) e VConst u -> whnfClos u VAbs x i u valu -> flip reval' u =<< updateValu valu i v VUp u (VQuant Pi x dom fu) -> up False ==<< (app u v, app fu v) VUp u1 ( b ) - > do { - -- ALT : erased functions are not applied to their argument ! v1 < - if erased dec then return v else app v [ w ] -- eta - expand w ? ? VUp u1 (VQuant Pi x dom rho b) -> do {- -- ALT: erased functions are not applied to their argument! v1 <- if erased dec then return v else app v [w] -- eta-expand w ?? -} v1 <- app u1 v -- eta-expand v ?? bv <- whnf (update rho x v) b up False v1 bv -} VUp u1 (VApp (VDef (DefId DatK n)) vl) -> do u' <- force u app u' v VIrr -> return VIrr 2010 - 11 - 01 this breaks extraction for System U example VIrr - > throwErrorMsg $ " app internal error : " + + show ( VApp u [ v ] ) VIrr -> throwErrorMsg $ "app internal error: " ++ show (VApp u [v]) -} _ -> return $ VApp u [v] -- app : : Val - > [ Val ] - > -- app u [] = return $ u -- app u c = do -- case (u,c) of ( VApp u2 c2 , _ ) - > app u2 ( c2 + + c ) -- (VLam x env e,(v:vl)) -> do v' <- whnf (update env x v) e -- app v' vl -- (VDef n,_) -> appDef n c ( VUp v ( VPi dec x av rho b ) , w : wl ) - > do -- {- -- -- ALT: erased functions are not applied to their argument! -- v1 <- if erased dec then return v else app v [w] -- eta-expand w ?? -- -} -- v1 <- app v [w] -- eta-expand w ?? -- bv <- whnf (update rho x w) b -- v2 <- up v1 bv -- app v2 wl -- {- -- ALT : VIrr consumes applications ( VIrr , _ ) - > return VIrr -- -} ( VIrr , _ ) - > throwErrorMsg $ " app internal error : " + + show ( VApp u c ) _ - > return $ VApp u c unroll a corecursive definition one time ( until constructor appears ) force' :: Bool -> Val -> TypeCheck (Bool, Val) force' b (VSing v tv) = do -- for singleton types, force type! (b',tv') <- force' b tv return (b', VSing v tv') force' b (VUp v tv) = up True v tv >>= \ v' -> return (True, v') -- force eta expansion force' b (VClos rho e) = do v <- whnf rho e force' b v force' b v@(VDef (DefId FunK n)) = failValInv v --trace ( " force " + + show v ) $ do sig < - gets signature case lookupSig n sig of ( FunSig CoInd t cl True ) - > do m < - matchClauses [ ] cl [ ] case m of Just v ' - > force v ' Nothing - > return v _ - > return v --trace ("force " ++ show v) $ do sig <- gets signature case lookupSig n sig of (FunSig CoInd t cl True) -> do m <- matchClauses [] cl [] case m of Just v' -> force v' Nothing -> return v _ -> return v -} force' b v@(VApp (VDef (DefId FunK n)) vl) = enterDoc (text "force" <+> prettyTCM v) $ do sig <- gets signature case Map.lookup n sig of Just (FunSig isCo t ki ar cl True _) -> traceMatch ("forcing " ++ show v) $ do m <- matchClauses emptyEnv cl vl case m of Just v' -> traceMatch ("forcing " ++ show n ++ " succeeded") $ force' True v' Nothing -> traceMatch ("forcing " ++ show n ++ " failed") $ return (b, v) _ -> return (b, v) force' b v = return (b, v) force :: Val -> TypeCheck Val force v = -- trace ("forcing " ++ show v) $ liftM snd $ force' False v -- apply a recursive function -- corecursive ones are not expanded even if the arity is exceeded -- this is because a coinductive type needs to be destructed by pattern matching appDef :: QName -> [Val] -> TypeCheck Val trace ( " appDef " + + n ) $ do -- identifier might not be in signature yet, e.g. ind.-rec.def. sig <- gets signature case (Map.lookup n sig) of Just (FunSig { isCo = Ind, arity = ar, clauses = cl, isTypeChecked = True }) | length vl >= fullArity ar -> do m <- matchClauses emptyEnv cl vl case m of Nothing -> return $ VApp (VDef (DefId FunK n)) vl Just v2 -> return v2 _ -> return $ VApp (VDef (DefId FunK n)) vl -- reflection and reification --------------------------------------- -- TODO: eta for builtin sigma-types !? -- up force v tv -- force==True also expands at coinductive type up :: Bool -> Val -> TVal -> TypeCheck Val up f (VUp v tv') tv = up f v tv up f v tv@VQuant{ vqPiSig = Pi } = return $ VUp v tv up f _ (VSing v vt) = up f v vt up f v (VDef d) = failValInv $ VDef d up f v (VApp (VDef (DefId DatK d)) vl) = upData f v d vl up f v _ = return v Most of the code to eta expand on data types is in TypeChecker.hs " typeCheckDeclaration " Currently , eta expansion only happens at data * types * with exactly one constructor . In a first step , this will be extended to non - recursive pattern inductive families . The strategy is : match type value with result type for all the constructors 0 . if there are no matches , eta expand to * ( VIrr ) 1 . if there is exactly one match , eta expand accordingly using destructors 2 . if there are more matches , do not eta - expand up{Vec A ( suc n ) } x = ( head A n x ) ( tail A n x ) up{Vec ( suc zero ) } x = vcons Bool zero ( head ) ( tail Bool zero x ) For patterns of : ( A : Set ) - > Nat - > Set are [ A , suc n ] - matching Bool , suc zero against A , suc n yields A = Bool , n = zero - this means we can eta expand to through the fields of vcons - if Index use value obtained by matching - if Field destr , use destr < all pars > < all indices > x TypeChecker.hs "typeCheckDeclaration" Currently, eta expansion only happens at data *types* with exactly one constructor. In a first step, this will be extended to non-recursive pattern inductive families. The strategy is: match type value with result type for all the constructors 0. if there are no matches, eta expand to * (VIrr) 1. if there is exactly one match, eta expand accordingly using destructors 2. if there are more matches, do not eta-expand up{Vec A (suc n)} x = vcons A n (head A n x) (tail A n x) up{Vec Bool (suc zero)} x = vcons Bool zero (head Bool zero x) (tail Bool zero x) For vcons - the patterns of Vec : (A : Set) -> Nat -> Set are [A,suc n] - matching Bool,suc zero against A,suc n yields A=Bool,n=zero - this means we can eta expand to vcons - go through the fields of vcons - if Index use value obtained by matching - if Field destr, use destr <all pars> <all indices> x -} -- matchingConstructors is for use in checkPattern -- matchingConstructors (D vs) returns all the constructors -- each as tuple (ci,rho) -- of family D whose target matches (D vs) under substitution rho matchingConstructors :: Val -> TypeCheck (Maybe [(ConstructorInfo,Env)]) matchingConstructors v@(VDef d) = failValInv v -- matchingConstructors' d [] matchingConstructors (VApp (VDef (DefId DatK d)) vl) = matchingConstructors' d vl >>= return . Just matchingConstructors v = return Nothing -- throwErrorMsg $ "matchingConstructors: not a data type: " ++ show v -- return [] matchingConstructors' :: QName -> [Val] -> TypeCheck [(ConstructorInfo,Env)] matchingConstructors' n vl = do sige <- lookupSymbQ n case sige of if ( null cs ) then ret [ ] else do -- no constructor matchingConstructors'' True vl dv cs -- matchingConstructors'' -- Arguments: -- symm symmetric match -- vl arguments to D (instance of D) -- dv complete type value of D -- cs constructors -- Returns a list [(ci,rho)] of matching constructors together with the -- environments which are solutions for the free variables in the constr.type -- this is also for use in upData matchingConstructors'' :: Bool -> [Val] -> Val -> [ConstructorInfo] -> TypeCheck [(ConstructorInfo,Env)] matchingConstructors'' symm vl dv cs = do vl <- mapM whnfClos vl compressMaybes <$> do forM cs $ \ ci -> do let ps = snd (cPatFam ci) list of patterns ps where D ps is the constructor target fmap (ci,) <$> nonLinMatchList symm emptyEnv ps vl dv data MatchingConstructors a = NoConstructor | OneConstructor a | ManyConstructors | UnknownConstructors deriving (Eq,Show) getMatchingConstructor eta : must the field be set of the data type -> QName -- d : the name of the data types -> [Val] -- vl : the arguments of the data type -> TypeCheck (MatchingConstructors ( Co -- co : coinductive type? parvs : the parameter half of the arguments , Env -- rho : the substitution for the index variables to arrive at d vl indvs : the index values of the constructor , ConstructorInfo -- ci : the only matching constructor )) getMatchingConstructor eta n vl = traceRecord ("getMatchingConstructor " ++ show (n, vl)) $ do when checking a mutual data , the sig entry of the second data is not yet in place when checking the first , thus , lookup may fail sig <- gets signature case Map.lookup n sig of Just (DataSig {symbTyp = dv, numPars = npars, isCo = co, constructors = cs, etaExpand}) | eta `implies` etaExpand -> if (null cs) then return NoConstructor else do -- no constructor: empty type -- for each constructor, match its core against the type -- produces a list of maybe (c.info, environment) cenvs <- matchingConstructors'' False vl dv cs traceRecordM $ "Matching constructors: " ++ show cenvs case cenvs of exactly one matching constructor : can eta expand [ ( ci , env ) ] - > if not ( eta ` implies ` cEtaExp ci ) then return UnknownConstructors else do [(ci,env)] -> if eta && not (cEtaExp ci) then return UnknownConstructors else do -- get list of index values from environment let fis = cFields ci let indices = filter (\ fi -> fClass fi == Index) fis let indvs = map (\ fi -> lookupPure env (fName fi)) indices let (pars, _) = splitAt npars vl return $ OneConstructor (co, pars, env, indvs, ci) more or less than one matching constructors : can not eta expand l -> -- trace ("getMatchingConstructor: " ++ show (length l) ++ " patterns match at type " ++ show n ++ show vl) $ return ManyConstructors _ -> traceRecord ("no eta expandable type") $ return UnknownConstructors getFieldsAtType :: QName -- d : the name of the data types -> [Val] -- vl : the arguments of the data type -> TypeCheck (Maybe -- Nothing if not a record type [(Name -- list of projection names ,TVal)]) -- and their instantiated type R ... -> C getFieldsAtType n vl = do mc <- getMatchingConstructor False n vl case mc of OneConstructor (_, pars, _, indvs, ci) -> do let pi = pars ++ indvs -- for each argument of constructor, get value let arg (FieldInfo { fName = x, fClass = Index }) = return [] arg (FieldInfo { fName = d, fClass = Field _ }) = do -- lookup type sig t of destructor d t <- lookupSymbTyp d -- pi-apply destructor type to parameters and indices t' <- piApps t pi return [(d,t')] Just . concat <$> mapM arg (cFields ci) _ -> return Nothing similar to piApp , but for record types and projections projectType :: TVal -> Name -> Val -> TypeCheck TVal projectType tv p rv = do let fail1 = failDoc (text "expected record type when taking the projection" <+> prettyTCM (Proj Post p) P.<> comma <+> text "but found type" <+> prettyTCM tv) let fail2 = failDoc (text "record type" <+> prettyTCM tv <+> text "does not have field" <+> prettyTCM p) case tv of VApp (VDef (DefId DatK d)) vl -> do mfs <- getFieldsAtType d vl case mfs of Nothing -> fail1 Just ptvs -> case lookup p ptvs of Nothing -> fail2 Just tv -> piApp tv rv -- apply to record arg _ -> fail1 -- eta expand v at data type n vl upData :: Bool -> Val -> QName -> [Val] -> TypeCheck Val upData force v n vl = -- trace ("upData " ++ show v ++ " at " ++ n ++ show vl) $ do let ret v' = traceEta ("Eta-expanding: " ++ show v ++ " --> " ++ show v' ++ " at type " ++ show n ++ show vl) $ return v' mc <- getMatchingConstructor True n vl case mc of NoConstructor -> ret VIrr OneConstructor (co, pars, env, indvs, ci) -> -- lazy eta-expansion for coinductive records like streams! if (co==CoInd && not force) then return $ VUp v (VApp (VDef $ DefId DatK n) vl) else do -- get list of index values from environment let fis = cFields ci let piv = pars ++ indvs ++ [v] -- for each argument of constructor, get value let arg (FieldInfo { fName = x, fClass = Index }) = lookupEnv env x arg (FieldInfo { fName = d, fClass = Field _ }) = do -- lookup type sig t of destructor d LetSig {symbTyp = t, definingVal = w} <- lookupSymb d -- pi-apply destructor type to parameters, indices and value v t' <- piApps t piv -- recursively eta expand (d <pars> v) -- OLD, defined projections: -- w <- foldM (app' False) w piv -- LAZY: only unfolds let, not def -- NEW, builtin projections: w <- app' False v (VProj Post d) up False w t' -- now: LAZY vs <- mapM arg fis let fs = map fName fis v' = VRecord (NamedRec (coToConK co) (cName ci) False notDotted) $ zip fs vs v ' < - foldM app ( ( coToConK co ) ( cName ci ) ) vs -- 2012 - 01 - 22 PARS GONE : ( pars + + vs ) ret v' -- more constructors or unknown situation: do not eta expand _ -> return v -- eta expand v at data type n vl upData : : Bool - > Val - > Name - > [ Val ] - > vl = -- trace ( " upData " + + show v + + " at " + + n + + show vl ) $ do let ret v ' = traceEta ( " Eta - expanding : " + + show v + + " -- > " + + show v ' + + " at type " + + n + + show vl ) $ return v ' -- when checking a mutual data , the sig entry of the second data -- is not yet in place when checking the first , thus , lookup may fail sig < - gets signature case Map.lookup n sig of Just ( DataSig { symbTyp = dv , numPars = npars , isCo = co , constructors = cs , etaExpand = True } ) - > if ( null cs ) then ret VIrr else do -- no constructor : empty type let ( pars , inds ) = splitAt npars vl -- for each constructor , match its core against the type -- produces a list of maybe ( c.info , environment ) False vl dv cs -- traceM $ " Matching constructors : " + + show cenvs case cenvs of -- exactly one matching constructor : can eta expand [ ( ci , env ) ] - > if not ( cEtaExp ci ) then return v else if ( co==CoInd & & not force ) then return $ VUp v ( VApp ( VDef $ DefId Dat n ) vl ) else do -- get list of index values from environment let cFields ci let indices = filter ( \ fi - > fClass fi = = Index ) fis let indvs = map ( \ fi - > lookupPure env ( fName fi ) ) indices let piv = pars + + indvs + + [ v ] -- for each argument of constructor , get value let arg ( FieldInfo { fName = x , = Index } ) = lookupEnv env x arg ( FieldInfo { fName = d , fClass = Field _ } ) = do -- lookup type sig t of destructor d t < - lookupSymbTyp d -- pi - apply destructor type to parameters , indices and value v t ' < - piApps t piv -- recursively eta expand ( d < pars > v ) -- WAS : up ( VDef ( DefId Fun d ) ` VApp ` piv ) t ' up False ( VDef ( DefId Fun d ) ` VApp ` piv ) t ' -- now : LAZY vs < - mapM arg fis v ' < - foldM app ( vCon co ( cName ci ) ) ( pars + + vs ) ret v ' -- more or less than one matching constructors : can not eta expand l - > -- trace ( " Eta : " + + show ( length l ) + + " patterns match at type " + + show n + + show vl ) $ return v _ - > return v -- eta expand v at data type n vl upData :: Bool -> Val -> Name -> [Val] -> TypeCheck Val upData force v n vl = -- trace ("upData " ++ show v ++ " at " ++ n ++ show vl) $ do let ret v' = traceEta ("Eta-expanding: " ++ show v ++ " --> " ++ show v' ++ " at type " ++ n ++ show vl) $ return v' -- when checking a mutual data decl, the sig entry of the second data -- is not yet in place when checking the first, thus, lookup may fail sig <- gets signature case Map.lookup n sig of Just (DataSig {symbTyp = dv, numPars = npars, isCo = co, constructors = cs, etaExpand = True}) -> if (null cs) then ret VIrr else do -- no constructor: empty type let (pars, inds) = splitAt npars vl -- for each constructor, match its core against the type -- produces a list of maybe (c.info, environment) cenvs <- matchingConstructors'' False vl dv cs -- traceM $ "Matching constructors: " ++ show cenvs case cenvs of -- exactly one matching constructor: can eta expand [(ci,env)] -> if not (cEtaExp ci) then return v else if (co==CoInd && not force) then return $ VUp v (VApp (VDef $ DefId Dat n) vl) else do -- get list of index values from environment let fis = cFields ci let indices = filter (\ fi -> fClass fi == Index) fis let indvs = map (\ fi -> lookupPure env (fName fi)) indices let piv = pars ++ indvs ++ [v] -- for each argument of constructor, get value let arg (FieldInfo { fName = x, fClass = Index }) = lookupEnv env x arg (FieldInfo { fName = d, fClass = Field _ }) = do -- lookup type sig t of destructor d t <- lookupSymbTyp d -- pi-apply destructor type to parameters, indices and value v t' <- piApps t piv -- recursively eta expand (d <pars> v) -- WAS: up (VDef (DefId Fun d) `VApp` piv) t' up False (VDef (DefId Fun d) `VApp` piv) t' -- now: LAZY vs <- mapM arg fis v' <- foldM app (vCon co (cName ci)) (pars ++ vs) ret v' -- more or less than one matching constructors: cannot eta expand l -> -- trace ("Eta: " ++ show (length l) ++ " patterns match at type " ++ show n ++ show vl) $ return v _ -> return v -} let matchC ( c , ps , ds ) = do [ ] ps inds dv case of Nothing - > return False Just env - > do let grps = groupBy ( \ ( x , _ ) ( y , _ ) - > x = = y ) env -- TODO : now compare elements in the group -- NEED types for equality check -- trivial if groups are singletons return $ all ( \ l - > length l < = 1 ) grps cs ' < - filterM matchC cs case cs ' of [ ] - > return $ VIrr [ ( c,_,ds ) ] - > do let parsv = pars + + [ v ] let aux d = do -- lookup type sig t of destructor d let FunSig { symbTyp = t } = lookupSig d sig -- pi - apply destructor type to parameters and value v t ' < - piApps t parsv -- recursively eta expand ( d < pars > v ) up ( VDef d ` VApp ` parsv ) t ' vs < - mapM aux ds app ( VCon co c ) ( pars + + vs ) _ - > return v _ - > return v let matchC (c, ps, ds) = do menv <- nonLinMatchList [] ps inds dv case menv of Nothing -> return False Just env -> do let grps = groupBy (\ (x,_) (y,_) -> x == y) env -- TODO: now compare elements in the group -- NEED types for equality check -- trivial if groups are singletons return $ all (\ l -> length l <= 1) grps cs' <- filterM matchC cs case cs' of [] -> return $ VIrr [(c,_,ds)] -> do let parsv = pars ++ [v] let aux d = do -- lookup type sig t of destructor d let FunSig { symbTyp = t } = lookupSig d sig -- pi-apply destructor type to parameters and value v t' <- piApps t parsv -- recursively eta expand (d <pars> v) up (VDef d `VApp` parsv) t' vs <- mapM aux ds app (VCon co c) (pars ++ vs) _ -> return v _ -> return v -} {- refl : [A : Set] -> [a : A] -> Id A a a up{Id T t t'} x Id T t t' =?= Id A a a --> A = T, a = t, a = t' -} OLD CODE FOR NON - DEPENDENT RECORDS ONLY -- erase if n is a empty type ( DataSig { constructors = [ ] } ) - > return $ VIrr -- eta expand v if n is a tuple type ( DataSig { isCo = co , constructors = [ c ] , destructors = Just ds } ) - > do let vlv = vl + + [ v ] let aux d = do -- lookup type sig t of destructor d let FunSig { symbTyp = t } = lookupSig d sig -- pi - apply destructor type to parameters and value v t ' < - piApps t vlv -- recursively eta expand ( d < pars > v ) up ( VDef d ` VApp ` vlv ) t ' vs < - mapM aux ds app ( VCon co c ) ( vl + + vs ) -- ( map ( \d - > VDef d ` VApp ` ( vl + + [ v ] ) ) ds ) _ - > return v END OLD CODE -- erase if n is a empty type (DataSig {constructors = []}) -> return $ VIrr -- eta expand v if n is a tuple type (DataSig {isCo = co, constructors = [c], destructors = Just ds}) -> do let vlv = vl ++ [v] let aux d = do -- lookup type sig t of destructor d let FunSig { symbTyp = t } = lookupSig d sig -- pi-apply destructor type to parameters and value v t' <- piApps t vlv -- recursively eta expand (d <pars> v) up (VDef d `VApp` vlv) t' vs <- mapM aux ds app (VCon co c) (vl ++ vs) -- (map (\d -> VDef d `VApp` (vl ++ [v])) ds) _ -> return v END OLD CODE -} -- pattern matching --------------------------------------------------- matchClauses :: Env -> [Clause] -> [Val] -> TypeCheck (Maybe Val) matchClauses env cl vl0 = do REWRITE before matching ( 2010 - 07 - 12 dysfunctional because of lazy ? ) loop cl vl where loop [] vl = return Nothing loop (Clause _ pl Nothing : cl2) vl = loop cl2 vl -- no need to try absurd clauses loop (Clause _ pl (Just rhs) : cl2) vl = do x <- matchClause env pl rhs vl case x of Nothing -> loop cl2 vl Just v -> return $ Just v bindMaybe :: Monad m => m (Maybe a) -> (a -> m (Maybe b)) -> m (Maybe b) bindMaybe mma k = mma >>= maybe (return Nothing) k matchClause :: Env -> [Pattern] -> Expr -> [Val] -> TypeCheck (Maybe Val) matchClause env pl rhs vl = case (pl, vl) of (p:pl, v:vl) -> match env p v `bindMaybe` \ env' -> matchClause env' pl rhs vl -- done matching: eval clause body in env and apply it to remaining arsg ([], _) -> Just <$> do flip (foldM app) vl =<< whnf env rhs -- too few arguments to fire clause: give up (_, []) -> return Nothing match :: Env -> Pattern -> Val -> TypeCheck (Maybe Env) match env p v0 = --trace (show env ++ show v0) $ do -- force against constructor pattern or pair pattern v <- case p of ConP{} -> do v <- force v0; traceMatch ("matching pattern " ++ show (p,v)) $ return v PairP{} -> do v <- force v0; traceMatch ("matching pattern " ++ show (p,v)) $ return v _ -> whnfClos v0 case (p,v) of -- (ErasedP _,_) -> return $ Just env -- TOO BAD, DOES NOT WORK (eta!) (ErasedP p,_) -> match env p v (AbsurdP{},_) -> return $ Just env (DotP _, _) -> return $ Just env (VarP x, _) -> return $ Just (update env x v) (SizeP _ x,_) -> return $ Just (update env x v) (ProjP x, VProj Post y) | x == y -> return $ Just env (PairP p1 p2, VPair v1 v2) -> matchList env [p1,p2] [v1,v2] (ConP _ x [],VDef (DefId (ConK _) y)) -> failValInv v -- | x == y -> return $ Just env -- The following case is NOT IMPOSSIBLE: ( ConP _ x pl , VApp ( VDef ( DefId ( ConK _ ) y ) ) vl ) - > failValInv v (ConP _ x pl,VApp (VDef (DefId (ConK _) y)) vl) | nameInstanceOf x y -> matchList env pl vl -- If a value is a dotted record value, we do not succeed, since -- it is not sure this is the correct constructor. (ConP _ x pl,VRecord (NamedRec ri y _ dotted) rs) | nameInstanceOf x y && not (isDotted dotted) -> matchList env pl $ map snd rs (p@(ConP pi _ _), v) | coPat pi == DefPat -> do p <- expandDefPat p match env p v (SuccP p', v) -> (predSize <$> whnfClos v) `bindMaybe` match env p' (UnusableP p,_) -> throwErrorMsg ("internal error: match " ++ show (p,v)) _ -> return Nothing matchList :: Env -> [Pattern] -> [Val] -> TypeCheck (Maybe Env) matchList env [] [] = return $ Just env matchList env (p:pl) (v:vl) = match env p v `bindMaybe` \ env' -> matchList env' pl vl matchList env pl vl = throwErrorMsg $ "matchList internal error: inequal length while trying to match patterns " ++ show pl ++ " against values " ++ show vl -- * Typed Non-linear Matching ----------------------------------------- type GenToPattern = [(Int,Pattern)] type MatchState = (Env, GenToPattern) -- @nonLinMatch True@ allows also instantiation in v0 -- this is useful for finding all matching constructors -- for an erased argument in checkPattern nonLinMatch :: Bool -> Bool -> MatchState -> Pattern -> Val -> TVal -> TypeCheck (Maybe MatchState) nonLinMatch undot symm st p v0 tv = traceMatch ("matching pattern " ++ show (p,v0)) $ do -- force against constructor pattern v <- case p of ConP{} -> force v0 PairP{} -> force v0 _ -> whnfClos v0 case (p,v) of (ErasedP{}, _) -> return $ Just st (DotP{} , _) -> return $ Just st no check in case of ! (VarP x, _) -> matchVarP x v (SizeP _ x, _) -> matchVarP x v (ProjP x, VProj Post y) | x == y -> return $ Just st (ConP _ c pl, VApp (VDef (DefId (ConK _) c')) vl) | nameInstanceOf c c' -> do vc <- conLType c tv nonLinMatchList' undot symm st pl vl vc -- Here, we do accept dotted constructors, since we are abusing this for unification. (ConP _ c pl, VRecord (NamedRec _ c' _ dotted) rs) | nameInstanceOf c c' -> do when undot $ clearDotted dotted vc <- conLType c tv nonLinMatchList' undot symm st pl (map snd rs) vc -- if the match against an unconfirmed constructor -- we can succeed, but not compute a sensible environment (_, VRecord (NamedRec _ c' _ dotted) rs) | isDotted dotted && not undot -> return $ Just st (p@(ConP pi _ _), v) | coPat pi == DefPat -> do p <- expandDefPat p nonLinMatch undot symm st p v tv (PairP p1 p2, VPair v1 v2) -> do tv <- force tv case tv of VQuant Sigma x dom fv -> do nonLinMatch undot symm st p1 v1 (typ dom) `bindMaybe` \ st -> do nonLinMatch undot symm st p2 v2 =<< app fv v1 _ -> failDoc $ text "nonLinMatch: expected" <+> prettyTCM tv <+> text "to be a Sigma-type (&)" (SuccP p', v) -> (predSize <$> whnfClos v) `bindMaybe` \ v' -> nonLinMatch undot symm st p' v' tv _ -> return Nothing where -- Check that the previous solution for @x@ is equal to @v@. -- Here, we need the type! matchVarP x v = do let env = fst st case List.find ((x ==) . fst) $ envMap $ fst st of Nothing -> return $ Just $ mapFst (\ env -> update env x v) st Just (y,v') -> ifM (eqValBool tv v v') (return $ Just st) (return Nothing) nonLinMatchList symm env ps vs tv -- typed non-linear matching of patterns ps against values vs at type tv -- env is the accumulator for the solution of the matching nonLinMatchList :: Bool -> Env -> [Pattern] -> [Val] -> TVal -> TypeCheck (Maybe Env) nonLinMatchList symm env ps vs tv = fmap fst <$> nonLinMatchList' False symm (env, []) ps vs tv nonLinMatchList' :: Bool -> Bool -> MatchState -> [Pattern] -> [Val] -> TVal -> TypeCheck (Maybe MatchState) nonLinMatchList' undot symm st [] [] tv = return $ Just st nonLinMatchList' undot symm st (p:pl) (v:vl) tv = do tv <- force tv case tv of VQuant Pi x dom fv -> nonLinMatch undot symm st p v (typ dom) `bindMaybe` \ st' -> nonLinMatchList' undot symm st' pl vl =<< app fv v _ -> throwErrorMsg $ "nonLinMatchList': cannot match in absence of pi-type" nonLinMatchList' _ _ _ _ _ _ = return Nothing -- | Expand a top-level pattern synonym expandDefPat :: Pattern -> TypeCheck Pattern expandDefPat p@(ConP pi c ps) | coPat pi == DefPat = do PatSig ns pat v <- lookupSymbQ c unless (length ns == length ps) $ throwErrorMsg ("underapplied defined pattern in " ++ show p) let pat' = if dottedPat pi then dotConstructors pat else pat return $ patSubst (zip ns ps) pat' expandDefPat p = return p --------------------------------------------------------------------------- -- * Unification --------------------------------------------------------------------------- #if MIN_VERSION_base(4,11,0) From ghc 8.4 , Semigroup superinstace of Monoid instance is mandatory . instance Semigroup (TypeCheck Bool) where (<>) = andLazy instance Monoid (TypeCheck Bool) where mempty = return True mappend = (<>) mconcat = andM #else instance Monoid (TypeCheck Bool) where mempty = return True mappend = andLazy mconcat = andM #endif | Occurrence check ( used by ' SPos ' and ' ' ) . -- Checks that generic values @ks@ does not occur in value @v@. -- In the process, @tv@ is normalized. class Nocc a where nocc :: [Int] -> a -> TypeCheck Bool instance Nocc a => Nocc [a] where nocc = foldMap . nocc instance Nocc a => Nocc (Dom a) where nocc = foldMap . nocc instance Nocc a => Nocc (Measure a) where nocc = foldMap . nocc instance Nocc a => Nocc (Bound a) where nocc = foldMap . nocc instance (Nocc a, Nocc b) => Nocc (a,b) where nocc ks (a, b) = nocc ks a `andLazy` nocc ks b instance Nocc a => Nocc (Sort a) where nocc ks (Set v) = nocc ks v nocc ks (CoSet v) = nocc ks v nocc ks (SortC _) = mempty instance Nocc Val where nocc ks v = do traceM ( " nocc " + + show v ) v <- whnfClos v case v of -- neutrals VGen k -> return $ not $ k `elem` ks VApp v1 vl -> nocc ks $ v1 : vl VDef{} -> mempty VProj{} -> mempty -- Binders: -- ALT: do not evaluate under binders (just check environment). -- This is less precise but more efficient. Can give false alarms. Still sound . ( Should maybe done first , like in Agda ) . VQuant pisig x dom fv -> nocc ks dom `mappend` do underAbs x dom fv $ \ _i _xv bv -> nocc ks bv fv@(VLam x env b) -> underAbs' x fv $ \ _xv bv -> nocc ks bv fv@(VAbs x i u valu) -> underAbs' x fv $ \ _xv bv -> nocc ks bv fv@(VConst v) -> underAbs' noName fv $ \ _xv bv -> nocc ks bv -- pairs VRecord _ rs -> nocc ks $ map snd rs VPair v w -> nocc ks (v, w) -- sizes VZero -> mempty VSucc v -> nocc ks v VInfty -> mempty VMax vl -> nocc ks vl VPlus vl -> nocc ks vl VSort s -> nocc ks s VMeasured mu tv -> nocc ks (mu, tv) VGuard beta tv -> nocc ks (beta, tv) VBelow ltle v -> nocc ks v VSing v tv -> nocc ks (v, tv) VUp v tv -> nocc ks (v, tv) VIrr -> mempty VCase v tv env cls -> nocc ks $ v : tv : map snd (envMap env) -- impossible: closure (reduced away) VClos{} -> throwErrorMsg $ "internal error: nocc " ++ show (ks,v) -- heterogeneous typed equality and subtyping ------------------------ eqValBool :: TVal -> Val -> Val -> TypeCheck Bool eqValBool tv v v' = errorToBool $ eqVal tv v v' -- eqValBool tv v v' = (eqVal tv v v' >> return True) `catchError` (\ _ -> return False) eqVal :: TVal -> Val -> Val -> TypeCheck () eqVal tv = leqVal' N mixed (Just (One tv)) -- force history data Force = N | L | R -- not yet, left , right deriving (Eq,Show) class Switchable a where switch :: a -> a instance Switchable Force where switch L = R switch R = L switch N = N instance Switchable Pol where switch = polNeg instance Switchable (a,a) where switch (a,b) = (b,a) instance Switchable a => Switchable (Maybe a) where switch = fmap switch -- WONTFIX : FOR THE FOLLOWING TO BE SOUND , ONE NEEDS COERCIVE SUBTYPING ! -- the problem is that after extraction , erased arguments are gone ! -- a function which does not use its argument can be used as just a function -- [ A ] - > A < = A - > A -- A < = [ A ] leqDec : : Pol - > Dec - > Dec - > Bool leqDec SPos dec1 dec2 = erased dec2 || not ( erased dec1 ) leqDec Neg dec1 dec2 = erased dec1 || not ( erased dec2 ) leqDec mixed dec1 dec2 = erased dec1 = = erased dec2 -- WONTFIX: FOR THE FOLLOWING TO BE SOUND, ONE NEEDS COERCIVE SUBTYPING! -- the problem is that after extraction, erased arguments are gone! -- a function which does not use its argument can be used as just a function -- [A] -> A <= A -> A -- A <= [A] leqDec :: Pol -> Dec -> Dec -> Bool leqDec SPos dec1 dec2 = erased dec2 || not (erased dec1) leqDec Neg dec1 dec2 = erased dec1 || not (erased dec2) leqDec mixed dec1 dec2 = erased dec1 == erased dec2 -} -- subtyping for erasure disabled -- but subtyping for polarities! leqDec :: Pol -> Dec -> Dec -> Bool leqDec p dec1 dec2 = erased dec1 == erased dec2 && relPol p leqPol (polarity dec1) (polarity dec2) -- subtyping --------------------------------------------------------- subtype :: Val -> Val -> TypeCheck () subtype v1 v2 = -- enter ("subtype " ++ show v1 ++ " <= " ++ show v2) $ leqVal' N Pos Nothing v1 v2 -- Pol ::= Pos | Neg | mixed leqVal :: Pol -> TVal -> Val -> Val -> TypeCheck () leqVal p tv = leqVal' N p (Just (One tv)) type MT12 = Maybe (OneOrTwo TVal) -- view the shape of a type or a pair of types data TypeShape = ShQuant PiSigma (OneOrTwo Name) (OneOrTwo Domain) (OneOrTwo FVal) -- both are function types | ShSort SortShape -- sort of same shape | ShData QName (OneOrTwo TVal)-- same data, but with possibly different args | ShNe (OneOrTwo TVal) -- both neutral 1 and singleton 2 and the left is a singleton 2 and the right is a singleton | ShNone deriving (Eq, Ord) data SortShape = ShSortC Class -- same sort constant | ShSet (OneOrTwo Val) -- Set i and Set j CoSet i and CoSet j deriving (Eq, Ord) shSize :: TypeShape shSize = ShSort (ShSortC Size) -- typeView does not normalize! typeView :: TVal -> TypeShape typeView tv = case tv of VQuant pisig x dom fv -> ShQuant pisig (One x) (One dom) (One fv) VBelow{} -> shSize VSort s -> ShSort (sortView s) VSing v tv -> ShSing v tv VApp (VDef (DefId DatK n)) vs -> ShData n (One tv) VApp (VDef (DefId FunK n)) vs -> ShNe (One tv) -- stuck fun VApp (VGen i) vs -> ShNe (One tv) -- type variable VGen i -> ShNe (One tv) -- type variable VCase{} -> ShNe (One tv) -- stuck case _ -> ShNone -- error $ "typeView " ++ show tv sortView :: Sort Val -> SortShape sortView s = case s of SortC c -> ShSortC c Set v -> ShSet (One v) CoSet v -> ShCoSet (One v) typeView12 :: (Functor m, Monad m, MonadError TraceError m) => OneOrTwo TVal -> m TypeShape typeView12 : : OneOrTwo TVal - > typeView12 (One tv) = return $ typeView tv typeView12 (Two tv1 tv2) = case (tv1, tv2) of (VQuant pisig1 x1 dom1 fv1, VQuant pisig2 x2 dom2 fv2) | pisig1 == pisig2 && erased (decor dom1) == erased (decor dom2) -> return $ ShQuant pisig1 (Two x1 x2) (Two dom1 dom2) (Two fv1 fv2) (VSort s1, VSort s2) -> ShSort <$> sortView12 (Two s1 s2) (VSing v tv, _) -> return $ ShSingL v tv tv2 (_, VSing v tv) -> return $ ShSingR tv1 v tv _ -> case (typeView tv1, typeView tv2) of (ShSort s1, ShSort s2) | s1 == s2 -> return $ ShSort $ s1 (ShData n1 _, ShData n2 _) | n1 == n2 -> return $ ShData n1 (Two tv1 tv2) (ShNe{} , ShNe{} ) -> return $ ShNe (Two tv1 tv2) _ -> throwErrorMsg $ "type " ++ show tv1 ++ " has different shape than " ++ show tv2 sortView12 :: (Monad m, MonadError TraceError m) => OneOrTwo (Sort Val) -> m SortShape sortView12 (One s) = return $ sortView s sortView12 (Two s1 s2) = case (s1, s2) of (SortC c1, SortC c2) | c1 == c2 -> return $ ShSortC c1 (Set v1, Set v2) -> return $ ShSet (Two v1 v2) (CoSet v1, CoSet v2) -> return $ ShCoSet (Two v1 v2) _ -> throwErrorMsg $ "sort " ++ show s1 ++ " has different shape than " ++ show s2 whnf12 :: OneOrTwo Env -> OneOrTwo Expr -> TypeCheck (OneOrTwo Val) whnf12 env12 e12 = traverse id $ zipWith12 whnf env12 e12 app12 :: OneOrTwo Val -> OneOrTwo Val -> TypeCheck (OneOrTwo Val) app12 fv12 v12 = traverse id $ zipWith12 app fv12 v12 if = Nothing , we are checking subtyping , otherwise we are -- comparing objects or higher-kinded types if two types are given ( heterogeneous equality ) , they need to be -- of the same shape, otherwise they cannot contain common terms leqVal' :: Force -> Pol -> MT12 -> Val -> Val -> TypeCheck () leqVal' f p mt12 u1' u2' = local (\ cxt -> cxt { consistencyCheck = False }) $ do 2013 - 03 - 30 During subtyping , it is fine to add any size hypotheses . l <- getLen ren <- getRen enterDoc (case mt12 of Nothing -> -- text ("leqVal' (subtyping) " ++ show (Map.toList $ ren) ++ " |-") text "leqVal' (subtyping) " <+> prettyTCM u1' <+> text (" <=" ++ show p ++ " ") <+> prettyTCM u2' Just (One tv) -> -- text ("leqVal' " ++ show (Map.toList $ ren) ++ " |-") text "leqVal' " <+> prettyTCM u1' <+> text (" <=" ++ show p ++ " ") <+> prettyTCM u2' <+> colon <+> prettyTCM tv Just (Two tv1 tv2) -> -- text ("leqVal' " ++ show (Map.toList $ ren) ++ " |-") text "leqVal' " <+> prettyTCM u1' <+> colon <+> prettyTCM tv1 <+> text (" <=" ++ show p ++ " ") <+> prettyTCM u2' <+> colon <+> prettyTCM tv2) $ do {- ce <- ask trace (("rewrites: " +?+ show (rewrites ce)) ++ " leqVal': " ++ show ce ++ "\n |- " ++ show u1' ++ "\n <=" ++ show p ++ " " ++ show u2') $ -} mt12f <- mapM (mapM force) mt12 -- leads to LOOP, see HungryEta.ma sh12 <- case mt12f of Nothing -> return Nothing Just tv12 -> case runExcept $ typeView12 tv12 of Right sh -> return $ Just sh Left err -> (recoverFail $ show err) >> return Nothing case sh12 of -- subtyping directed by common type shape two terms are equal at singleton type ! Just (ShSingL v1 tv1' tv2) -> leqVal' f p (Just (Two tv1' tv2)) v1 u2' Just (ShSingR tv1 v2 tv2') -> leqVal' f p (Just (Two tv1 tv2')) u1' v2 Just (ShSort (ShSortC Size)) -> leqSize p u1' u2' functions are compared pointwise Gamma , : A ) |- t x : B < = Gamma ' , p'(x : A ' ) |- t ' x : B ' ---------------------------------------------------------- Gamma |- t : : A ) - > B < = Gamma ' |- t ' : p'(x : A ' ) - > B ' Gamma, p(x:A) |- t x : B <= Gamma', p'(x:A') |- t' x : B' ---------------------------------------------------------- Gamma |- t : p(x:A) -> B <= Gamma' |- t' : p'(x:A') -> B' -} Just (ShQuant Pi x12 dom12 fv12) -> do x <- do let x = name12 x12 if null (suggestion x) then do case (u1', u2') of (VLam x _ _, _) -> return x (_, VLam x _ _) -> return x _ -> return x else return x newVar x dom12 $ \ _ xv12 -> do u1' <- app u1' (first12 xv12) u2' <- app u2' (second12 xv12) tv12 <- app12 fv12 xv12 leqVal' f p (Just tv12) u1' u2' Just ( VPi x1 dom1 env1 b1 , VPi x2 dom2 env2 b2 ) - > new2 x1 ( dom1 , dom2 ) $ \ ( xv1 , xv2 ) - > do u1 ' < - app u1 ' xv1 u2 ' < - app u2 ' xv2 ' < - whnf ( update env1 x1 xv1 ) b1 tv2 ' < - whnf ( update env2 x2 xv2 ) b2 leqVal ' f p ( Just ( ' , tv2 ' ) ) u1 ' u2 ' Just (VPi x1 dom1 env1 b1, VPi x2 dom2 env2 b2) -> new2 x1 (dom1, dom2) $ \ (xv1, xv2) -> do u1' <- app u1' xv1 u2' <- app u2' xv2 tv1' <- whnf (update env1 x1 xv1) b1 tv2' <- whnf (update env2 x2 xv2) b2 leqVal' f p (Just (tv1', tv2')) u1' u2' -} -- structural subtyping (not directed by types) _ -> do u1 <- reduce =<< whnfClos u1' u2 <- reduce =<< whnfClos u2' let tryForcing fallback = do (f1,u1f) <- force' False u1 (f2,u2f) <- force' False u2 case (f1,f2) of -- (u1f /= u1,u2f /= u2) of only unroll one side enter ("forcing LHS") $ leqVal' L p mt12 u1f u2 (False,True) | f /= L -> enter ("forcing RHS") $ leqVal' R p mt12 u1 u2f _ -> -- enter ("not forcing " ++ show (f1,f2,f)) $ fallback leqCons n1 vl1 n2 vl2 = do unless (n1 == n2) $ recoverFail $ "leqVal': head mismatch " ++ show u1 ++ " != " ++ show u2 case mt12 of Nothing -> recoverFail $ "leqVal': cannot compare constructor terms without type" Just tv12 -> do ct12 <- mapM (conType n1) tv12 _ <- leqVals' f p ct12 vl1 vl2 return () {- leqStructural u1 u2 where leqStructural u1 u2 = -} case (u1,u2) of C = C ' ( proper : C ' entails C , but I do not want to implement entailment ) Gamma , C |- A < = Gamma ' , C ' |- A ' ----------------------------------------- Gamma |- C = = > A < = Gamma ' |- C ' = = > A ' C = C' (proper: C' entails C, but I do not want to implement entailment) Gamma, C |- A <= Gamma', C' |- A' ----------------------------------------- Gamma |- C ==> A <= Gamma' |- C' ==> A' -} (VGuard beta1 bv1, VGuard beta2 bv2) -> do entailsGuard (switch p) beta1 beta2 leqVal' f p Nothing bv1 bv2 (VGuard beta u1, u2) | p `elem` [Neg,Pos] -> addOrCheckGuard (switch p) beta $ leqVal' f p Nothing u1 u2 (u1, VGuard beta u2) | p `elem` [Neg,Pos] -> addOrCheckGuard p beta $ leqVal' f p Nothing u1 u2 p ' < = p Gamma ' |- A ' < = Gamma |- A Gamma , : A ) |- B < = Gamma ' , p'(x : A ' ) |- B ' --------------------------------------------------------- Gamma |- p(x : A ) - > B : s < = Gamma ' |- p'(x : A ' ) - > B ' : s ' p' <= p Gamma' |- A' <= Gamma |- A Gamma, p(x:A) |- B <= Gamma', p'(x:A') |- B' --------------------------------------------------------- Gamma |- p(x:A) -> B : s <= Gamma' |- p'(x:A') -> B' : s' -} (VQuant piSig1 x1 dom1@(Domain av1 _ dec1) fv1, VQuant piSig2 x2 dom2@(Domain av2 _ dec2) fv2) -> do let p' = if piSig1 == Pi then switch p else p if piSig1 /= piSig2 || not (leqDec p' dec1 dec2) then recoverFailDoc $ text "subtyping" <+> prettyTCM u1 <+> text (" <=" ++ show p ++ " ") <+> prettyTCM u2 <+> text "failed" else do leqVal' (switch f) p' Nothing av1 av2 -- take smaller domain let dom = if (p' == Neg) then dom2 else dom1 let x = bestName $ if p' == Neg then [x2,x1] else [x1,x2] new x dom $ \ xv -> do bv1 <- app fv1 xv bv2 <- app fv2 xv enterDoc (text "comparing codomain" <+> prettyTCM bv1 <+> text "with" <+> prettyTCM bv2) $ leqVal' f p Nothing bv1 bv2 (VSing v1 av1, VSing v2 av2) -> do leqVal' f p Nothing av1 av2 leqVal' N mixed (Just (Two av1 av2)) v1 v2 -- compare for eq. (VSing v1 av1, VBelow ltle v2) | av1 == vSize && p == Pos -> do v1 <- whnfClos v1 leSize ltle p v1 v2 2012 - 01 - 28 now vSize is VBelow Le Infty -- extra cases since vSize is not implemented as VBelow Le Infty ( u1,u2 ) | isVSize u1 & & isVSize u2 - > return ( ) ( VSort ( SortC Size ) , { } ) - > leqStructural ( VBelow Le VInfty ) u2 ( VBelow { } , VSort ( SortC Size ) ) - > leqStructural u1 ( VBelow Le VInfty ) -- extra cases since vSize is not implemented as VBelow Le Infty (u1,u2) | isVSize u1 && isVSize u2 -> return () (VSort (SortC Size), VBelow{}) -> leqStructural (VBelow Le VInfty) u2 (VBelow{}, VSort (SortC Size)) -> leqStructural u1 (VBelow Le VInfty) -} -- care needed to not make <=# a subtype of <# (VBelow ltle1 v1, VBelow ltle2 v2) -> case (p, ltle1, ltle2) of _ | ltle1 == ltle2 -> leSize Le p v1 v2 (Neg, Le, Lt) -> leSize Le p (vSucc v1) v2 (Neg, Lt, Le) -> leSize Lt p v1 v2 -- careful here (p , Lt, Le) -> leSize Le p v1 (vSucc v2) (p , Le, Lt) -> leSize Lt p v1 v2 -- careful here -- unresolved eta-expansions (e.g. at coinductive type) (VUp v1 av1, VUp v2 av2) -> do -- leqVal' f p Nothing av1 av2 -- do not compare types OR : ) ? (VUp v1 av1, u2) -> leqVal' f p mt12 v1 u2 (u1, VUp v2 av2) -> leqVal' f p mt12 u1 v2 (VRecord (NamedRec _ n1 _ _) rs1, VRecord (NamedRec _ n2 _ _) rs2) -> leqCons n1 (map snd rs1) n2 (map snd rs2) -- the following three cases should be impossible -- but are n't . I gave up on this bug -- 2012 - 01 - 25 -- FOUND IT ( ( NamedRec _ n1 _ ) rs1 , VApp v2@(VDef ( DefId ( ConK _ ) n2 ) ) vl2 ) - > leqCons n1 ( map snd rs1 ) n2 vl2 ( VApp v1@(VDef ( DefId ( ConK _ ) n1 ) ) vl1 , ( NamedRec _ n2 _ ) rs2 ) - > leqCons n1 ( map snd rs2 ) ( VApp v1@(VDef ( DefId ( ConK _ ) n1 ) ) vl1 , VApp v2@(VDef ( DefId ( ConK _ ) n2 ) ) vl2 ) - > leqCons n1 vl1 n2 vl2 -- the following three cases should be impossible -- but aren't. I gave up on this bug -- 2012-01-25 -- FOUND IT (VRecord (NamedRec _ n1 _) rs1, VApp v2@(VDef (DefId (ConK _) n2)) vl2) -> leqCons n1 (map snd rs1) n2 vl2 (VApp v1@(VDef (DefId (ConK _) n1)) vl1, VRecord (NamedRec _ n2 _) rs2) -> leqCons n1 vl1 n2 (map snd rs2) (VApp v1@(VDef (DefId (ConK _) n1)) vl1, VApp v2@(VDef (DefId (ConK _) n2)) vl2) -> leqCons n1 vl1 n2 vl2 -} -- smart equality is not transitive (VCase v1 tv1 env1 cl1, VCase v2 tv2 env2 cl2) -> do leqVal' f p (Just (Two tv1 tv2)) v1 v2 -- FIXED: do not have type here, but v1,v2 are neutral leqClauses f p mt12 v1 tv1 env1 cl1 env2 cl2 REMOVED , NOT TRANSITIVE ( VCase v env cl , v2 ) - > leqCases ( switch f ) ( switch p ) ( switch mt12 ) v2 v env cl ( v1 , v env cl ) - > leqCases f p mt12 v1 v env cl (VCase v env cl, v2) -> leqCases (switch f) (switch p) (switch mt12) v2 v env cl (v1, VCase v env cl) -> leqCases f p mt12 v1 v env cl -} (VSing v1 av1, av2) -> leqVal' f p Nothing av1 av2 -- subtyping ax (VSort s1, VSort s2) -> leqSort p s1 s2 (a1,a2) | a1 == a2 -> return () (u1,u2) -> tryForcing $ case (u1,u2) of (VApp v1 vl1, VApp v2 vl2) -> leqApp f p v1 vl1 v2 vl2 (VApp v1 vl1, u2) -> leqApp f p v1 vl1 u2 [] (u1, VApp v2 vl2) -> leqApp f p u1 [] v2 vl2 _ -> leqApp f p u1 [] u2 [] leqClauses :: Force -> Pol -> MT12 -> Val -> TVal -> Env -> [Clause] -> Env -> [Clause] -> TypeCheck () leqClauses f pol mt12 v tvp env1 cls1 env2 cls2 = loop cls1 cls2 where loop cls1 cls2 = case (cls1,cls2) of ([],[]) -> return () (Clause _ [p1] mrhs1 : cls1', Clause _ [p2] mrhs2 : cls2') -> do ns <- flip execStateT [] $ alphaPattern p1 p2 case (mrhs1, mrhs2) of (Nothing, Nothing) -> return () (Just e1, Just e2) -> do let tv = maybe vTopSort first12 mt12 let tv012 = maybe [] toList12 mt12 addPattern (tvp `arrow` tv) p2 env2 $ \ _ pv env2' -> addRewrite (Rewrite v pv) tv012 $ \ tv012 -> do let env1' = env2' { envMap = compAssoc ns (envMap env2') } v1 <- whnf (appendEnv env1' env1) e1 v2 <- whnf (appendEnv env2' env2) e2 leqVal' f pol (toMaybe12 tv012) v1 v2 loop cls1' cls2' -- naive implementation for now : : Force - > Pol - > MT12 - > Val - > TVal - > Env - > [ Clause ] - > Env - > [ Clause ] - > ( ) leqClauses f pol mt12 v tvp env1 cls1 env2 cls2 = loop cls1 cls2 where loop cls1 cls2 = case ( cls1,cls2 ) of ( [ ] , [ ] ) - > return ( ) ( Clause _ [ p1 ] : cls1 ' , Clause _ [ p2 ] mrhs2 : cls2 ' ) - > do eqPattern p1 p2 case ( mrhs1 , mrhs2 ) of ( Nothing , Nothing ) - > return ( ) ( Just e1 , Just e2 ) - > do let tv = maybe vTopSort first12 mt12 let tv012 = maybe [ ] toList12 mt12 addPattern ( tvp ` arrow ` tv ) p1 env1 $ \ _ pv env ' - > addRewrite ( Rewrite v pv ) tv012 $ \ tv012 - > do v1 < - whnf ( appendEnv env ' env1 ) e1 v2 < - whnf ( appendEnv env ' env2 ) e2 leqVal ' f pol ( toMaybe12 tv012 ) v1 v2 loop cls1 ' cls2 ' eqPattern : : Pattern - > Pattern - > TypeCheck ( ) eqPattern p1 p2 = if p1 = = p2 then return ( ) else throwErrorMsg $ " pattern " + + show p1 + + " ! = " + + show p2 -- naive implementation for now leqClauses :: Force -> Pol -> MT12 -> Val -> TVal -> Env -> [Clause] -> Env -> [Clause] -> TypeCheck () leqClauses f pol mt12 v tvp env1 cls1 env2 cls2 = loop cls1 cls2 where loop cls1 cls2 = case (cls1,cls2) of ([],[]) -> return () (Clause _ [p1] mrhs1 : cls1', Clause _ [p2] mrhs2 : cls2') -> do eqPattern p1 p2 case (mrhs1, mrhs2) of (Nothing, Nothing) -> return () (Just e1, Just e2) -> do let tv = maybe vTopSort first12 mt12 let tv012 = maybe [] toList12 mt12 addPattern (tvp `arrow` tv) p1 env1 $ \ _ pv env' -> addRewrite (Rewrite v pv) tv012 $ \ tv012 -> do v1 <- whnf (appendEnv env' env1) e1 v2 <- whnf (appendEnv env' env2) e2 leqVal' f pol (toMaybe12 tv012) v1 v2 loop cls1' cls2' eqPattern :: Pattern -> Pattern -> TypeCheck () eqPattern p1 p2 = if p1 == p2 then return () else throwErrorMsg $ "pattern " ++ show p1 ++ " != " ++ show p2 -} type NameMap = [(Name,Name)] alphaPattern :: Pattern -> Pattern -> StateT NameMap TypeCheck () alphaPattern p1 p2 = do let failure = throwErrorMsg $ "pattern " ++ show p1 ++ " != " ++ show p2 alpha x1 x2 = do ns <- get case lookup x1 ns of Nothing -> put $ (x1,x2) : ns Just x2' | x2 == x2' -> return () | otherwise -> failure case (p1,p2) of (VarP x1, VarP x2) -> alpha x1 x2 (ConP pi1 n1 ps1, ConP pi2 n2 ps2) | pi1 == pi2 && n1 == n2 -> zipWithM_ alphaPattern ps1 ps2 (SuccP p1, SuccP p2) -> alphaPattern p1 p2 (SizeP _ x1, SizeP _ x2) -> alpha x1 x2 (PairP p11 p12, PairP p21 p22) -> do alphaPattern p11 p21 alphaPattern p12 p22 (ProjP n1, ProjP n2) -> unless (n1 == n2) failure (DotP _, DotP _) -> return () (AbsurdP, AbsurdP) -> return () (ErasedP p1, ErasedP p2) -> alphaPattern p1 p2 (UnusableP p1, UnusableP p2) -> alphaPattern p1 p2 _ -> failure leqCases f p env cl checks whether v1 < = p ( VCase v tv env cl ) : leqCases :: Force -> Pol -> MT12 -> Val -> Val -> TVal -> Env -> [Clause] -> TypeCheck () leqCases f pol mt12 v1 v tvp env cl = do vcase <- evalCase v tvp env cl case vcase of (VCase v tvp env cl) -> mapM_ (leqCase f pol mt12 v1 v tvp env) cl v2 -> leqVal' f pol mt12 v1 v2 -- absurd cases need not be checked leqCase :: Force -> Pol -> MT12 -> Val -> Val -> TVal -> Env -> Clause -> TypeCheck () leqCase f pol mt12 v1 v tvp env (Clause _ [p] Nothing) = return () + + " : " + + show mt12 ) $ the dot patterns inside p are only valid in environment env let tv = case mt12 of Nothing -> vTopSort Just tv12 -> second12 tv12 addPattern (tvp `arrow` tv) p env $ \ _ pv env' -> addRewrite (Rewrite v pv) [tv,v1] $ \ [tv',v1'] -> do v2 <- whnf (appendEnv env' env) e 2010 - 09 - 10 , WHY ? let mt12' = fmap (mapSecond12 (const tv')) mt12 leqVal' f pol mt12' v1' v2' compare spines ( see rule Al - App - Ne , , MSCS 08 ) -- q ::= mixed | Pos | Neg leqVals' :: Force -> Pol -> OneOrTwo TVal -> [Val] -> [Val] -> TypeCheck (OneOrTwo TVal) leqVals' f q tv12 vl1 vl2 = do sh12 <- typeView12 =<< mapM force tv12 case (vl1, vl2, sh12) of ([], [], _) -> return tv12 (VProj Post p1 : vs1, VProj Post p2 : vs2, ShData d _) -> do unless (p1 == p2) $ recoverFailDoc $ text "projections" <+> prettyTCM p1 <+> text "and" <+> prettyTCM p2 <+> text "differ!" -- recoverFail $ "projections " ++ show p1 ++ " and " ++ show p2 ++ " differ!" tv12 <- mapM (\ tv -> projectType tv p1 VIrr) tv12 leqVals' f q tv12 vs1 vs2 (w1:vs1, w2:vs2, ShQuant Pi x12 dom12 fv12) -> do let p = oneOrTwo id polAnd (fmap (polarity . decor) dom12) let dec = Dec p -- WAS: , erased = erased $ decor $ first12 dom12 } v1 <- whnfClos w1 v2 <- whnfClos w2 tv12 <- do if erased p -- WAS: (erased dec || p == Pol.Const) we have skipped an argument , so proceed with two types ! then app12 (toTwo fv12) (Two v1 v2) else do let q' = polComp p q applyDec dec $ leqVal' f q' (Just $ fmap typ dom12) v1 v2 we have not skipped comparison , so proceed ( 1/2 ) as we came in case fv12 of Two{} -> app12 fv12 (Two v1 v2) One fv -> One <$> app fv v1 -- type is invariant, so it does not matter which one we take leqVals' f q tv12 vs1 vs2 _ -> failDoc $ text "leqVals': not (compatible) function types or mismatch number of arguments when comparing " <+> prettyTCM vl1 <+> text " to " <+> prettyTCM vl2 <+> text " at type " <+> prettyTCM tv12 _ - > throwErrorMsg $ " leqVals ' : not ( compatible ) function types or mismatch number of arguments when comparing " + + show vl1 + + " to " + + show vl2 + + " at type " + + show leqVals ' f q ( VPi x1 dom1@(Domain av1 _ dec1 ) env1 b1 , VPi x2 dom2@(Domain av2 _ dec2 ) env2 b2 ) ( w1 : vs1 ) ( w2 : ) | dec1 = = dec2 = do let p = polarity dec1 v1 < - whnfClos w1 v2 < - whnfClos w2 when ( not ( erased dec1 ) ) $ applyDec dec1 $ leqVal ' f ( polComp p q ) ( Just ( av1,av2 ) ) v1 v2 < - whnf ( update env1 x1 v1 ) b1 tv2 < - whnf ( update env2 x2 v2 ) b2 leqVals ' f q ( tv1,tv2 ) vs1 vs2 leqVals' f q (VPi x1 dom1@(Domain av1 _ dec1) env1 b1, VPi x2 dom2@(Domain av2 _ dec2) env2 b2) (w1:vs1) (w2:vs2) | dec1 == dec2 = do let p = polarity dec1 v1 <- whnfClos w1 v2 <- whnfClos w2 when (not (erased dec1)) $ applyDec dec1 $ leqVal' f (polComp p q) (Just (av1,av2)) v1 v2 tv1 <- whnf (update env1 x1 v1) b1 tv2 <- whnf (update env2 x2 v2) b2 leqVals' f q (tv1,tv2) vs1 vs2 -} {- leqNe :: Force -> Val -> Val -> TypeCheck TVal leqNe f v1 v2 = --trace ("leqNe " ++ show v1 ++ "<=" ++ show v2) $ do case (v1,v2) of (VGen k1, VGen k2) -> if k1 == k2 then do dom <- lookupGem k1 return $ typ dom else throwErrorMsg $ "gen mismatch " ++ show k1 ++ " " ++ show k2 -} leqApp f pol v1 vs1 v2 vs2 checks v1 vs1 < = pol v2 vs2 -- pol ::= Param | Pos | Neg leqApp :: Force -> Pol -> Val -> [Val] -> Val -> [Val] -> TypeCheck () leqApp f pol v1 w1 v2 w2 = {- trace ("leqApp: " -- ++ show delta ++ " |- " ++ show v1 ++ show w1 ++ " <=" ++ show pol ++ " " ++ show v2 ++ show w2) $ -} do let headMismatch = recoverFail $ " leqApp : head mismatch " + + show v1 + + " ! = " + + show v2 do let headMismatch = recoverFail $ "leqApp: head mismatch " ++ show v1 ++ " != " ++ show v2 -} do let headMismatch = recoverFailDoc $ text "leqApp: head mismatch" <+> prettyTCM v1 <+> text "!=" <+> prettyTCM v2 let emptyOrUnit u1 u2 = unlessM (isEmptyType u1) $ unlessM (isUnitType u2) $ headMismatch case (v1,v2) of IMPOSSIBLE : ( VApp v1 [ ] , v2 ) - > leqApp f pol v1 w1 v2 w2 ( v1 , VApp v2 [ ] ) - > leqApp f pol v1 w1 v2 w2 (VApp v1 [], v2) -> leqApp f pol v1 w1 v2 w2 (v1, VApp v2 []) -> leqApp f pol v1 w1 v2 w2 -} ( VApp { } , _ ) - > throwErrorMsg $ " leqApp : internal error : hit application v1 = " + + show v1 ( _ , VApp { } ) - > throwErrorMsg $ " leqApp : internal error : hit application v2 = " + + show v2 (VApp{}, _) -> throwErrorMsg $ "leqApp: internal error: hit application v1 = " ++ show v1 (_, VApp{}) -> throwErrorMsg $ "leqApp: internal error: hit application v2 = " ++ show v2 -} (VUp v1 _, v2) -> leqApp f pol v1 w1 v2 w2 (v1, VUp v2 _) -> leqApp f pol v1 w1 v2 w2 (VGen k1, VGen k2) | k1 == k2 -> do tv12 <- (fmap typ . domain) <$> lookupGen k1 _ <- leqVals' f pol tv12 w1 w2 return () ( VGen k1 , VGen k2 ) - > if k1 /= k2 then headMismatch else do ( fmap typ . domain ) < $ > lookupGen k1 leqVals ' f pol tv12 w1 w2 return ( ) (VGen k1, VGen k2) -> if k1 /= k2 then headMismatch else do tv12 <- (fmap typ . domain) <$> lookupGen k1 leqVals' f pol tv12 w1 w2 return () -} ( _ n , _ m ) - > if n /= m then throwErrorMsg $ " leqApp : head mismatch " + + show v1 + + " ! = " + + show v2 else do sige < - lookupSymb n case sige of ( ConSig tv ) - > -- constructor leqVals ' f tv ( repeat mixed ) w1 w2 > > return ( ) (VCon _ n, VCon _ m) -> if n /= m then throwErrorMsg $ "leqApp: head mismatch " ++ show v1 ++ " != " ++ show v2 else do sige <- lookupSymb n case sige of (ConSig tv) -> -- constructor leqVals' f tv (repeat mixed) w1 w2 >> return () -} (VDef n, VDef m) | n == m -> do tv <- lookupSymbTypQ (idName n) _ <- leqVals' f pol (One tv) w1 w2 return () -- check for least or greatest type (u1,u2) -> if pol == Pos then emptyOrUnit u1 u2 else if pol == Neg then emptyOrUnit u2 u1 else headMismatch -- least type ( VDef ( DefId DatK n ) , v2 ) | pol = = Pos - > ifM ( isEmptyData n ) ( return ( ) ) headMismatch ( v1 , VDef ( DefId DatK n ) ) | pol = = Neg - > ifM ( isEmptyData n ) ( return ( ) ) headMismatch -- least type (VDef (DefId DatK n), v2) | pol == Pos -> ifM (isEmptyData n) (return ()) headMismatch (v1, VDef (DefId DatK n)) | pol == Neg -> ifM (isEmptyData n) (return ()) headMismatch -} ( VDef n , VDef m ) - > if ( name n ) /= ( name m ) then do bot < - if pol==Neg then isEmptyData $ name m else if pol==Pos then isEmptyData $ name n else return False if bot then return ( ) else headMismatch else do tv < - lookupSymbTyp ( name n ) leqVals ' f pol ( One tv ) w1 w2 return ( ) (VDef n, VDef m) -> if (name n) /= (name m) then do bot <- if pol==Neg then isEmptyData $ name m else if pol==Pos then isEmptyData $ name n else return False if bot then return () else headMismatch else do tv <- lookupSymbTyp (name n) leqVals' f pol (One tv) w1 w2 return () -} sig < - gets signature case lookupSig ( name n ) sig of ( DataSig { numPars = p , positivity = pos , isSized = s , isCo = co , symbTyp = tv } ) - > -- data type let positivitySizeIndex = if s /= Sized then mixed else if co = = Ind then Pos else Neg pos ' = -- trace ( " leqApp : posOrig = " + + show ( pos + + [ positivitySizeIndex ] ) ) $ map ( polComp pol ) ( pos + + positivitySizeIndex : repeat mixed ) -- the polComp will replace all SPos by Pos in leqVals ' f tv pos ' w1 w2 > > return ( ) -- otherwise , we are dealing with a ( co ) recursive function or a constructor entry - > leqVals ' f ( symbTyp entry ) ( repeat mixed ) w1 w2 > > return ( ) sig <- gets signature case lookupSig (name n) sig of (DataSig{ numPars = p, positivity = pos, isSized = s, isCo = co, symbTyp = tv }) -> -- data type let positivitySizeIndex = if s /= Sized then mixed else if co == Ind then Pos else Neg pos' = -- trace ("leqApp: posOrig = " ++ show (pos ++ [positivitySizeIndex])) $ map (polComp pol) (pos ++ positivitySizeIndex : repeat mixed) -- the polComp will replace all SPos by Pos in leqVals' f tv pos' w1 w2 >> return () -- otherwise, we are dealing with a (co) recursive function or a constructor entry -> leqVals' f (symbTyp entry) (repeat mixed) w1 w2 >> return () -} {- _ -> headMismatch _ -> recoverFail $ "leqApp: " ++ show v1 ++ show w1 ++ " !<=" ++ show pol ++ " " ++ show v2 ++ show w2 -} isEmptyType :: TVal -> TypeCheck Bool isEmptyType (VDef (DefId DatK n)) = isEmptyData n isEmptyType _ = return False isUnitType :: TVal -> TypeCheck Bool isUnitType (VDef (DefId DatK n)) = isUnitData n isUnitType _ = return False -- comparing sorts and sizes ----------------------------------------- leqSort :: Pol -> Sort Val -> Sort Val -> TypeCheck () leqSort p = relPolM p leqSort' {- leqSort mixed s1 s2 = leqSort' s1 s2 >> leqSort' s2 s1 leqSort Neg s1 s2 = leqSort' s2 s1 leqSort Pos s1 s2 = leqSort' s1 s2 -} leqSort' :: Sort Val -> Sort Val -> TypeCheck () leqSort' s1 s2 = do -- let err = "universe test " ++ show s1 ++ " <= " ++ show s2 ++ " failed" let err = text "universe test" <+> prettyTCM s1 <+> text "<=" <+> prettyTCM s2 <+> text "failed" case (s1,s2) of (_ , Set VInfty) -> return () (SortC c , SortC c') | c == c' -> return () (Set v1 , Set v2) -> leqSize Pos v1 v2 (CoSet VInfty , Set v) -> return () (Set VZero , CoSet{}) -> return () (CoSet v1 , CoSet v2) -> leqSize Neg v1 v2 _ -> recoverFailDoc err minSize :: Val -> Val -> Maybe Val minSize v1 v2 = case (v1,v2) of (VZero,_) -> return VZero (_,VZero) -> return VZero (VInfty,_) -> return v2 (_,VInfty) -> return v1 (VMax vs,_) -> maxMins $ map (\ v -> minSize v v2) vs (_,VMax vs) -> maxMins $ map (\ v -> minSize v1 v) vs (VSucc v1', VSucc v2') -> fmap succSize $ minSize v1' v2' (VGen i, VGen j) -> if i == j then return $ VGen i else Nothing (VSucc v1', VGen j) -> minSize v1' v2 (VGen i, VSucc v2') -> minSize v1 v2' maxMins :: [Maybe Val] -> Maybe Val maxMins mvs = case compressMaybes mvs of [] -> Nothing vs' -> return $ maxSize vs' -- substaging on size values leqSize :: Pol -> Val -> Val -> TypeCheck () leqSize = leSize Le ltSize :: Val -> Val -> TypeCheck () ltSize = leSize Lt Pos leSize :: LtLe -> Pol -> Val -> Val -> TypeCheck () leSize ltle pol v1 v2 = enterDoc (text "leSize" <+> prettyTCM v1 <+> text (show ltle ++ show pol) <+> prettyTCM v2) $ enter ( " leSize " + + show v1 + + " " + + show + + show pol + + " " + + show v2 ) $ traceSize ("leSize " ++ show v1 ++ " " ++ show ltle ++ show pol ++ " " ++ show v2) $ do case (v1,v2) of _ | v1 == v2 && ltle == Le -> return () -- TODO: better handling of sums! (VSucc v1,VSucc v2) -> leSize ltle pol v1 v2 {- (VGen i1,VGen i2) -> do d <- getSizeDiff i1 i2 -- check size relation from constraints case d of Nothing -> recoverFail $ "leqSize: head mismatch: " ++ show v1 ++ " !<= " ++ show v2 Just k -> case (pol,k) of (_, 0) | pol == mixed -> return () (Pos, _) | k >= 0 -> return () (Neg, _) | k <= 0 -> return () _ -> recoverFail $ "leqSize: " ++ show v1 ++ " !<=" ++ show pol ++ " " ++ show v2 ++ " failed" -} {- if v1 == v2 then return () else throwErrorMsg $ "leqSize: head mismatch: " ++ show v1 ++ " !<= " ++ show v2 -} (VInfty,VInfty) | ltle == Le -> return () | otherwise -> recoverFail "leSize: # < # failed" (VApp h1 tl1,VApp h2 tl2) -> leqApp N pol h1 tl1 h2 tl2 _ -> relPolM pol (leSize' ltle) v1 v2 leqSize' :: Val -> Val -> TypeCheck () leqSize' = leSize' Le leSize' :: LtLe -> Val -> Val -> TypeCheck () enter ( " leSize ' " + + show v1 + + " " + + show + + " " + + show v2 ) $ enterDoc (text "leSize'" <+> prettyTCM v1 <+> text (show ltle) <+> prettyTCM v2) $ traceSize ("leSize' " ++ show v1 ++ " " ++ show ltle ++ " " ++ show v2) $ do let failure = recoverFailDoc $ text "leSize':" <+> prettyTCM v1 <+> text (show ltle) <+> prettyTCM v2 <+> text "failed" err = " leSize ' : " + + show v1 + + " " + + show + + " " + + show v2 + + " failed " case (v1,v2) of (VZero,_) | ltle == Le -> return () (VSucc{}, VZero) -> failure (VInfty, VZero) -> failure (VGen{}, VZero) -> failure (VMax vs,_) -> mapM_ (\ v -> leSize' ltle v v2) vs -- all v in vs <= v2 (_,VMax vs) -> foldr1 orM $ map (leSize' ltle v1) vs -- this produces a disjunction ( _ , ) - > addLe v1 v2 -- this produces a disjunction (_,VInfty) | ltle == Le -> return () (VZero, VInfty) -> return () (VMeta{},VZero) -> addLe ltle v1 v2 ( 0,VMeta i n ' , j m ' ) - > let ( n , m ) = if < = 0 then ( n ' , m ' - bal ) else ( n ' + bal , m ' ) in (0,VMeta i n', VMeta j m') -> let (n,m) = if bal <= 0 then (n', m' - bal) else (n' + bal, m') in -} (VMeta i rho n, VMeta j rho' m) -> addLe ltle (VMeta i rho (n - min n m)) (VMeta j rho' (m - min n m)) (VMeta i rho n, VSucc v2) | n > 0 -> leSize' ltle (VMeta i rho (n-1)) v2 (VMeta i rho n, v2) -> addLe ltle v1 v2 (VSucc v1, VMeta i rho n) | n > 0 -> leSize' ltle v1 (VMeta i rho (n-1)) (v1,VMeta i rho n) -> addLe ltle v1 v2 _ -> leSize'' ltle 0 v1 v2 HANDLED BY leSize '' ( VSucc { } , { } ) - > throwErrorMsg err ( VSucc { } , VPlus { } ) - > throwErrorMsg err (VSucc{}, VGen{}) -> throwErrorMsg err (VSucc{}, VPlus{}) -> throwErrorMsg err -} leSize '' v v ' checks whether Succ^bal v ` lt ` v ' invariant : bal is zero in cases for VMax and leSize'' :: LtLe -> Int -> Val -> Val -> TypeCheck () leSize'' ltle bal v1 v2 = traceSize ("leSize'' " ++ show v1 ++ " + " ++ show bal ++ " " ++ show ltle ++ " " ++ show v2) $ do let failure = recoverFailDoc (text "leSize'':" <+> prettyTCM v1 <+> text ("+ " ++ show bal) <+> text (show ltle) <+> prettyTCM v2 <+> text "failed") check mb = ifM mb (return ()) failure ltlez = case ltle of { Le -> 0 ; Lt -> -1 } case (v1,v2) of #ifdef STRICTINFTY -- Only cancel variables < # _ | v1 == v2 && ltle == Le && bal <= 0 -> return () (VGen i, VGen j) | i == j && bal <= -1 -> check $ isBelowInfty i #else -- Allow cancelling of all variables _ | v1 == v2 && bal <= ltlez -> return () -- TODO: better handling of sums! #endif (VGen i, VInfty) | ltle == Lt -> check $ isBelowInfty i (VZero,_) | bal <= ltlez -> return () (VZero,VInfty) -> return () (VZero,VGen _) | bal > ltlez -> recoverFailDoc $ text "0 not <" <+> prettyTCM v2 (VSucc v1, v2) -> leSize'' ltle (bal + 1) v1 v2 (v1, VSucc v2) -> leSize'' ltle (bal - 1) v1 v2 (VPlus vs1, VPlus vs2) -> leSizePlus ltle bal vs1 vs2 (VPlus vs1, VZero) -> leSizePlus ltle bal vs1 [] (VZero, VPlus vs2) -> leSizePlus ltle bal [] vs2 (VPlus vs1, _) -> leSizePlus ltle bal vs1 [v2] (_, VPlus vs2) -> leSizePlus ltle bal [v1] vs2 (VZero,_) -> leSizePlus ltle bal [] [v2] (_,VZero) -> leSizePlus ltle bal [v1] [] _ -> leSizePlus ltle bal [v1] [v2] #if (defined STRICTINFTY) 2012 - 02 - 06 this modification cancels only variables < # However , omega - instantiation is valid [ i < # ] - > F i subseteq F # because every chain has a limit at # . However, omega-instantiation is valid [i < #] -> F i subseteq F # because every chain has a limit at #. -} leSizePlus :: LtLe -> Int -> [Val] -> [Val] -> TypeCheck () leSizePlus Lt bal vs1 vs2 = do vs2' <- filterM varBelowInfty vs2 vs1' <- filterM varBelowInfty vs1 leSizePlus' Lt bal (vs1 List.\\ vs2') (vs2 List.\\ vs1') leSizePlus Le bal vs1 vs2 = leSizePlus' Le bal (vs1 List.\\ vs2) (vs2 List.\\ vs1) #else leSizePlus :: LtLe -> Int -> [Val] -> [Val] -> TypeCheck () leSizePlus ltle bal vs1 vs2 = leSizePlus' ltle bal (vs1 List.\\ vs2) (vs2 List.\\ vs1) #endif varBelowInfty :: Val -> TypeCheck Bool varBelowInfty (VGen i) = isBelowInfty i varBelowInfty _ = return False leSizePlus' :: LtLe -> Int -> [Val] -> [Val] -> TypeCheck () leSizePlus' ltle bal vs1 vs2 = do let v1 = plusSizes vs1 let v2 = plusSizes vs2 let exit True = return () exit False | bal >= 0 = recoverFailDoc (text "leSize:" <+> prettyTCM v1 <+> text ("+ " ++ show bal ++ " " ++ show ltle) <+> prettyTCM v2 <+> text "failed") | otherwise = recoverFailDoc (text "leSize:" <+> prettyTCM v1 <+> text (show ltle) <+> prettyTCM v2 <+> text ("+ " ++ show (-bal) ++ " failed")) traceSizeM ("leSizePlus' ltle " ++ show v1 ++ " + " ++ show bal ++ " " ++ show ltle ++ " " ++ show v2) let ltlez = case ltle of { Le -> 0 ; Lt -> -1 } case (vs1,vs2) of ([],_) | bal <= ltlez -> return () ([],[VGen i]) -> do n <- getMinSize i -- traceM ("getMinSize = " ++ show n) case n of height of i = = 0 Just n -> exit (bal <= n + ltlez) ([VGen i1],[VGen i2]) -> do d <- sizeVarBelow i1 i2 traceSizeM ("sizeVarBelow " ++ show (i1,i2) ++ " returns " ++ show d) case d of Nothing -> tryIrregularBound i1 i2 (ltlez - bal) recoverFail $ " leSize : head mismatch : " + + show v1 + + " " + + show + + " " + + show v2 Just k -> exit (bal <= k + ltlez) _ -> exit False -- BAD HACK! -- check (VGen i1) <= (VGen i2) + k tryIrregularBound :: Int -> Int -> Int -> TypeCheck () tryIrregularBound i1 i2 k = do betas <- asks bounds let beta = Bound Le (Measure [VGen i1]) (Measure [iterate VSucc (VGen i2) !! k]) foldl (\ result beta' -> result `orM` entailsGuard Pos beta' beta) (recoverFail "bound not entailed") betas leqSize ' : : Val - > Val - > ( ) leqSize ' v1 v2 = --trace ( " leqSize ' " + + show v1 + + show v2 ) $ do case ( v1,v2 ) of ( vs , _ ) - > mapM _ ( \ v - > leqSize ' v v2 ) vs -- all v in vs < = v2 ( _ , ) - > addLeq v1 v2 -- this produces a disjunction ( VSucc v1,VSucc v2 ) - > leqSize ' v1 v2 ( VGen v1,VGen v2 ) - > do d < - getSizeDiff v1 v2 case d of Nothing - > throwErrorMsg $ " leqSize : head mismatch : " + + show v1 + + " ! < = " + + show v2 Just k - > if k > = 0 then return ( ) else throwErrorMsg $ " leqSize : " + + show v1 + + " ! < = " + + show v2 + + " failed " ( _ , VInfty ) - > return ( ) ( VMeta i n , VSucc v2 ) | n > 0 - > leqSize ' ( i ( n-1 ) ) v2 ( i n , j m ) - > addLeq ( i ( n - min n m ) ) ( j ( m - min n m ) ) ( i n , v2 ) - > addLeq v1 v2 ( VSucc v1 , i n ) | n > 0 - > leqSize ' v1 ( i ( n-1 ) ) ( v1,VMeta i n ) - > addLeq v1 v2 ( v1,VSucc v2 ) - > leqSize ' v1 v2 _ - > throwErrorMsg $ " leqSize : " + + show v1 + + " ! < = " + + show v2 leqSize' :: Val -> Val -> TypeCheck () leqSize' v1 v2 = --trace ("leqSize' " ++ show v1 ++ show v2) $ do case (v1,v2) of (VMax vs,_) -> mapM_ (\ v -> leqSize' v v2) vs -- all v in vs <= v2 (_,VMax _) -> addLeq v1 v2 -- this produces a disjunction (VSucc v1,VSucc v2) -> leqSize' v1 v2 (VGen v1,VGen v2) -> do d <- getSizeDiff v1 v2 case d of Nothing -> throwErrorMsg $ "leqSize: head mismatch: " ++ show v1 ++ " !<= " ++ show v2 Just k -> if k >= 0 then return () else throwErrorMsg $ "leqSize: " ++ show v1 ++ " !<= " ++ show v2 ++ " failed" (_,VInfty) -> return () (VMeta i n, VSucc v2) | n > 0 -> leqSize' (VMeta i (n-1)) v2 (VMeta i n, VMeta j m) -> addLeq (VMeta i (n - min n m)) (VMeta j (m - min n m)) (VMeta i n, v2) -> addLeq v1 v2 (VSucc v1, VMeta i n) | n > 0 -> leqSize' v1 (VMeta i (n-1)) (v1,VMeta i n) -> addLeq v1 v2 (v1,VSucc v2) -> leqSize' v1 v2 _ -> throwErrorMsg $ "leqSize: " ++ show v1 ++ " !<= " ++ show v2 -} -- measures and guards ----------------------------------------------- -- compare lexicographically -- precondition : same length ltMeasure : : Measure Val - > Measure Val - > ( ) ltMeasure ( Measure mu1 ) ( Measure mu2 ) = -- enter ( " checking " + + show mu1 + + " < " + + show mu2 ) $ lexSizes Lt mu1 mu2 -- compare lexicographically -- precondition: same length ltMeasure :: Measure Val -> Measure Val -> TypeCheck () ltMeasure (Measure mu1) (Measure mu2) = -- enter ("checking " ++ show mu1 ++ " < " ++ show mu2) $ lexSizes Lt mu1 mu2 -} leqMeasure : : Pol - > Measure Val - > Measure Val - > ( ) leqMeasure mixed ( Measure mu1 ) ( Measure mu2 ) = do zipWithM ( leqSize mixed ) mu1 mu2 return ( ) leqMeasure Pos ( Measure mu1 ) ( Measure mu2 ) = lexSizes mu1 mu2 leqMeasure Neg ( Measure mu1 ) ( Measure mu2 ) = lexSizes mu2 mu1 leqMeasure :: Pol -> Measure Val -> Measure Val -> TypeCheck () leqMeasure mixed (Measure mu1) (Measure mu2) = do zipWithM (leqSize mixed) mu1 mu2 return () leqMeasure Pos (Measure mu1) (Measure mu2) = lexSizes mu1 mu2 leqMeasure Neg (Measure mu1) (Measure mu2) = lexSizes mu2 mu1 -} -- lexSizes True mu mu' checkes mu < mu' -- lexSizes False mu mu' checkes mu <= mu' lexSizes :: LtLe -> [Val] -> [Val] -> TypeCheck () lexSizes ltle mu1 mu2 = traceSize ("lexSizes " ++ show (ltle,mu1,mu2)) $ case (ltle, mu1, mu2) of (Lt, [], []) -> recoverFail $ "lexSizes: no descent detected" (Le, [], []) -> return () (lt, a1:mu1, a2:mu2) -> do b <- newAssertionHandling Failure $ errorToBool $ leSize ltle Pos a1 a2 case (lt,b) of (Le,False) -> recoverFailDoc $ text "lexSizes: expected" <+> prettyTCM a1 <+> text "<=" <+> prettyTCM a2 -- recoverFail $ "lexSizes: expected " ++ show a1 ++ " <= " ++ show a2 (Lt,True) -> return () _ -> lexSizes ltle mu1 mu2 r < - compareSize a1 a2 case r of LT - > return ( ) EQ - > lexSizes ltle mu1 mu2 GT - > recoverFail $ " lexSizes : expected " + + show a1 + + " < = " + + show a2 r <- compareSize a1 a2 case r of LT -> return () EQ -> lexSizes ltle mu1 mu2 GT -> recoverFail $ "lexSizes: expected " ++ show a1 ++ " <= " ++ show a2 -} -- TODO : reprogram leqSize in terms of a proper compareSize compareSize : : Val - > Val - > compareSize a1 a2 = do let ret o = trace ( " compareSize : " + + show a1 + + " compared to " + + show a2 + + " returns " + + show o ) $ return o le < - newAssertionHandling Failure $ errorToBool $ leqSize Pos a1 a2 ge < - newAssertionHandling Failure $ errorToBool $ leqSize Pos a2 a1 case ( le , ge ) of ( True , False ) - > ret LT -- THIS IS COMPLETE BOGUS ! ! ! ( True , True ) - > ret EQ ( False , True ) - > ret GT ( False , False ) - > throwErrorMsg $ " compareSize ( " + + show a1 + + " , " + + show a2 + + " ): sizes incomparable " -- TODO: reprogram leqSize in terms of a proper compareSize compareSize :: Val -> Val -> TypeCheck Ordering compareSize a1 a2 = do let ret o = trace ("compareSize: " ++ show a1 ++ " compared to " ++ show a2 ++ " returns " ++ show o) $ return o le <- newAssertionHandling Failure $ errorToBool $ leqSize Pos a1 a2 ge <- newAssertionHandling Failure $ errorToBool $ leqSize Pos a2 a1 case (le,ge) of (True,False) -> ret LT -- THIS IS COMPLETE BOGUS!!! (True,True) -> ret EQ (False,True) -> ret GT (False,False) -> throwErrorMsg $ "compareSize (" ++ show a1 ++ ", " ++ show a2 ++ "): sizes incomparable" -} Bound entailment 1 . ( mu1 < mu1 ' ) = = > ( mu2 < mu2 ' ) if mu2 < = mu1 and mu1 ' < = mu2 ' 2 . ( mu1 < = mu1 ' ) = = > ( mu2 < mu2 ' ) one of these < = strict ( < ) 3 . ( mu1 < mu1 ' ) = = > ( mu2 < = mu2 ' ) as 1 . 4 . ( mu1 < = mu1 ' ) = = > ( mu2 < = mu2 ' ) as 1 . 1. (mu1 < mu1') ==> (mu2 < mu2') if mu2 <= mu1 and mu1' <= mu2' 2. (mu1 <= mu1') ==> (mu2 < mu2') one of these <= strict (<) 3. (mu1 < mu1') ==> (mu2 <= mu2') as 1. 4. (mu1 <= mu1') ==> (mu2 <= mu2') as 1. -} entailsGuard :: Pol -> Bound Val -> Bound Val -> TypeCheck () entailsGuard pol beta1@(Bound ltle1 (Measure mu1) (Measure mu1')) beta2@(Bound ltle2 (Measure mu2) (Measure mu2')) = enterDoc (text ("entailsGuard:") <+> prettyTCM beta1 <+> text (show pol ++ "==>") <+> prettyTCM beta2) $ do case pol of _ | pol == mixed -> do assert (ltle1 == ltle2) $ "unequal bound types" zipWithM_ (leqSize mixed) mu1 mu2 zipWithM_ (leqSize mixed) mu1' mu2' return () Pos | ltle1 == Lt || ltle2 == Le -> do lexSizes Le mu2 mu1 -- not strictly smaller lexSizes Le mu1' mu2' return () Pos -> do (lexSizes Lt mu2 mu1 >> lexSizes Le mu1' mu2') `orM` (lexSizes Le mu2 mu1 >> lexSizes Lt mu1' mu2') Neg -> entailsGuard (switch pol) beta2 beta1 eqGuard : : Bound Val - > Bound Val - > ( ) eqGuard ( Bound ( Measure mu1 ) ( Measure mu1 ' ) ) ( Bound ( Measure mu2 ) ( Measure mu2 ' ) ) = do zipWithM ( leqSize mixed ) mu1 mu2 zipWithM ( leqSize mixed ) mu1 ' mu2 ' return ( ) eqGuard :: Bound Val -> Bound Val -> TypeCheck () eqGuard (Bound (Measure mu1) (Measure mu1')) (Bound (Measure mu2) (Measure mu2')) = do zipWithM (leqSize mixed) mu1 mu2 zipWithM (leqSize mixed) mu1' mu2' return () -} checkGuard :: Bound Val -> TypeCheck () checkGuard beta@(Bound ltle mu mu') = enterDoc (text "checkGuard" <+> prettyTCM beta) $ lexSizes ltle (measure mu) (measure mu') addOrCheckGuard :: Pol -> Bound Val -> TypeCheck a -> TypeCheck a addOrCheckGuard Neg beta cont = checkGuard beta >> cont addOrCheckGuard Pos beta cont = addBoundHyp beta cont -- comparing polarities ------------------------------------------------- leqPolM :: Pol -> PProd -> TypeCheck () leqPolM p (PProd Pol.Const _) = return () leqPolM p (PProd q m) | Map.null m && not (isPVar p) = if leqPol p q then return () else recoverFail $ "polarity check " ++ show p ++ " <= " ++ show q ++ " failed" leqPolM p q = do traceM $ "adding polarity constraint " ++ show p ++ " <= " ++ show q leqPolPoly :: Pol -> PPoly -> TypeCheck () leqPolPoly p (PPoly l) = mapM_ (leqPolM p) l -- adding an edge to the positivity graph addPosEdge :: DefId -> DefId -> PProd -> TypeCheck () addPosEdge src tgt p = unless (src == tgt && isSPos p) $ do -- traceM ("adding interesting positivity graph edge " ++ show src ++ " --[ " ++ show p ++ " ]--> " ++ show tgt) st <- get put $ st { positivityGraph = Arc (Rigid src) (ppoly p) (Rigid tgt) : positivityGraph st } checkPositivityGraph :: TypeCheck () checkPositivityGraph = enter ("checking positivity") $ do st <- get let cs = positivityGraph st let gr = buildGraph cs let n = nextNode gr let m0 = mkMatrix n (graph gr) let m = warshall m0 let isDataId i = case Map.lookup i (intMap gr) of Just (Rigid (DefId DatK _)) -> True _ -> False let dataDiag = [ m Array.! (i,i) | i <- [0..n-1], isDataId i ] mapM_ (\ x -> leqPolPoly oone x) dataDiag let solvable = all ( \ x - > leqPol oone x ) unless solvable $ recoverFail $ " positivity check failed " let solvable = all (\ x -> leqPol oone x) unless solvable $ recoverFail $ "positivity check failed" -} -- TODO: solve constraints put $ st { positivityGraph = [] } -- telescopes -------------------------------------------------------- telView :: TVal -> TypeCheck ([(Val, TBinding TVal)], TVal) telView tv = do case tv of VQuant Pi x dom fv -> underAbs_ x dom fv $ \ _ xv bv -> do (vTel, core) <- telView bv return ((xv, TBind x dom) : vTel, core) _ -> return ([], tv) -- | Turn a fully applied constructor value into a named record value. mkConVal :: Dotted -> ConK -> QName -> [Val] -> TVal -> TypeCheck Val mkConVal dotted co n vs vc = do (vTel, _) <- telView vc let fieldNames = map (boundName . snd) vTel return $ VRecord (NamedRec co n False dotted) $ zip fieldNames vs
null
https://raw.githubusercontent.com/andreasabel/miniagda/55374597238071c2c2c74acf166cf95b34281e1f/src/Eval.hs
haskell
import Debug.Trace (trace) positivity checking trace msg a traceM msg trace msg a traceM msg trace msg a traceM msg traceLoop msg a = trace msg a traceLoopM msg = traceM msg trace msg a traceM msg traceSize msg a = trace msg a traceSizeM msg = traceM msg evaluation with rewriting ------------------------------------- > pattern > p is added , b should be in -- > normal form . > true > false > true b is rewritten to nf , then the second rule > false , which can be captured by . > weak head normal form > pattern > p is added, b should be in --> normal form. > true > false > true b is rewritten to nf, then the second rule > false, which can be captured by MiniAgda. > weak head normal form | When combining valuations, the old one takes priority. @[sigma][tau]v = [[sigma]tau]v@ no rewriting in size expressions cannot rewrite projection since we only have rewrite rules at base types we do not need to reduces prefixes of w restore invariant CAN rewrite variable do not force at this point <t : Pi x:a.f> = Pi x:a <t x : f x> <t : A -> B > = Pi x:A <t x : B> <t : <t' : a>> = <t' : a> This is a bit of a hack ( finding a fresh name ) < t : Pi x : : a < t x : b > < t : Pi x : a.f > = Pi x : a < t x : f x > < t : < t ' : a > > = < t ' : a > xv ` seq ` x ' ` seq ` | otherwise = This is a bit of a hack (finding a fresh name) <t : Pi x:a.b> = Pi x:a <t x : b> <t : Pi x:a.f> = Pi x:a <t x : f x> <t : <t' : a>> = <t' : a> xv `seq` x' `seq` | otherwise = reduce the root of a value equal v v' tests values for untyped equality precond: v v' are in --> whnf includes all size expressions (VSucc v1, VSucc v2) -> equal v1 v2 -- NO REDUCING NECC. HERE (Size expr) NO RED. NECC. (Type) (VLam x1 env1 b1, VLam x2 env2 b2) -> -- PROBLEM: DOMAIN MISSING addName x1 $ \ vx -> do -- CAN'T "up" fresh variable do v1 <- whnf (update env1 x1 vx) b1 v2 <- whnf (update env2 x2 vx) b2 equal v1 v2 LEADS TO NON-TERMINATION -- equal' v1 v2 tests values for untyped equality -- v1 v2 are not necessarily in --> whnf equal' v1 v2 = do v1' <- reduce v1 v2' <- reduce v2 equal v1' v2' normalization ----------------------------------------------------- normalize to depth m default recursive call error $ "cannot reify meta-variable " ++ show v0 TODO: type directed reification forgotten the meaning of the boolean, WAS: False) TODO: properly evaluate clauses!! ----------------------------------- similar to reify VSort (CoSet v) -> (Sort . CoSet) <$> toExpr v VSort (Set v) -> (Sort . Set) <$> toExpr v VSort (SortC s) -> return $ Sort (SortC s) addBindEnv :: TBind -> Env -> (Env -> TypeCheck a) -> TypeCheck a addBindEnv (TBind x dom) rho cont = do let dom' = fmap (VClos rho) dom newWithGen x dom' $ \ k _ -> cont (update rho x (VGen k)) addNameEnv "" rho cont = cont "" rho error $ "internal error: variable " ++ show x ++ " comes without domain" \ x rho -> cont (VarP x) rho class BindClosToExpr a where bindClosToExpr :: Env -> a -> (Env -> a -> TCM b) -> TCM b instance ClosToExpr a => BindClosToExpr (TBinding a) where bindClosToExpr default : no binding Quant piSig tel tb e -> bindClosToExpr rho tel $ \ rho tel -> bindClosToExpr rho tb $ \ rho tb -> Quant piSig tel tb <$> closToExpr rho e evaluation -------------------------------------------------------- | Weak head normal form. ALT : remove erased lambdas entirely ALT: remove erased lambdas entirely a measured type evaluates to - a bounded type if measure present in environment (rhs of funs) not adding measure constraint to context! throwErrorMsg $ "panic: whnf " ++ show e ++ " : no measure in environment " ++ show env not adding measure constraint to context! coinductive and anonymous records are treated lazily: ALT : filter out all erased arguments from application ALT: filter out all erased arguments from application trace ("case head evaluates to " ++ showVal v) $ return () succ is strict max is strict plus is strict let ( LetSig _ e ) = lookupSig n sig whnf [ ] e let (LetSig _ e) = lookupSig n sig whnf [] e NEED TO KEEP because of eta - exp ! trace ("whnfClos " ++ show v) $ NO EFFECT THE PROBLEM IS that (tail (x Up Stream)) Up Stream is a whnf, because Up Stream is lazy in equality checking this is a problem when the Up is removed. evaluate in standard environment <t : <t' : a>> = <t' : a> v <- whnf rho e super ugly HACK Should work with just x since shadowing is forbidden singleton strict , is this OK ? ! super ugly HACK Should work with just x since shadowing is forbidden singleton strict, is this OK?! no rec value here | Application of arguments and projections. inductive constructors are strict! VDef n -> appDef n [v] VSing is a type! ALT : erased functions are not applied to their argument ! eta - expand w ? ? -- ALT: erased functions are not applied to their argument! v1 <- if erased dec then return v else app v [w] -- eta-expand w ?? eta-expand v ?? app u [] = return $ u app u c = do case (u,c) of (VLam x env e,(v:vl)) -> do v' <- whnf (update env x v) e app v' vl (VDef n,_) -> appDef n c {- -- ALT: erased functions are not applied to their argument! v1 <- if erased dec then return v else app v [w] -- eta-expand w ?? -} v1 <- app v [w] -- eta-expand w ?? bv <- whnf (update rho x w) b v2 <- up v1 bv app v2 wl {- ALT : VIrr consumes applications -} for singleton types, force type! force eta expansion trace ( " force " + + show v ) $ trace ("force " ++ show v) $ trace ("forcing " ++ show v) $ apply a recursive function corecursive ones are not expanded even if the arity is exceeded this is because a coinductive type needs to be destructed by pattern matching identifier might not be in signature yet, e.g. ind.-rec.def. reflection and reification --------------------------------------- TODO: eta for builtin sigma-types !? up force v tv force==True also expands at coinductive type matchingConstructors is for use in checkPattern matchingConstructors (D vs) returns all the constructors each as tuple (ci,rho) of family D whose target matches (D vs) under substitution rho matchingConstructors' d [] throwErrorMsg $ "matchingConstructors: not a data type: " ++ show v -- return [] no constructor matchingConstructors'' Arguments: symm symmetric match vl arguments to D (instance of D) dv complete type value of D cs constructors Returns a list [(ci,rho)] of matching constructors together with the environments which are solutions for the free variables in the constr.type this is also for use in upData d : the name of the data types vl : the arguments of the data type co : coinductive type? rho : the substitution for the index variables to arrive at d vl ci : the only matching constructor no constructor: empty type for each constructor, match its core against the type produces a list of maybe (c.info, environment) get list of index values from environment trace ("getMatchingConstructor: " ++ show (length l) ++ " patterns match at type " ++ show n ++ show vl) $ d : the name of the data types vl : the arguments of the data type Nothing if not a record type list of projection names and their instantiated type R ... -> C for each argument of constructor, get value lookup type sig t of destructor d pi-apply destructor type to parameters and indices apply to record arg eta expand v at data type n vl trace ("upData " ++ show v ++ " at " ++ n ++ show vl) $ lazy eta-expansion for coinductive records like streams! get list of index values from environment for each argument of constructor, get value lookup type sig t of destructor d pi-apply destructor type to parameters, indices and value v recursively eta expand (d <pars> v) OLD, defined projections: w <- foldM (app' False) w piv -- LAZY: only unfolds let, not def NEW, builtin projections: now: LAZY 2012 - 01 - 22 PARS GONE : ( pars + + vs ) more constructors or unknown situation: do not eta expand eta expand v at data type n vl trace ( " upData " + + show v + + " at " + + n + + show vl ) $ when checking a mutual data , the sig entry of the second data is not yet in place when checking the first , thus , lookup may fail no constructor : empty type for each constructor , match its core against the type produces a list of maybe ( c.info , environment ) traceM $ " Matching constructors : " + + show cenvs exactly one matching constructor : can eta expand get list of index values from environment for each argument of constructor , get value lookup type sig t of destructor d pi - apply destructor type to parameters , indices and value v recursively eta expand ( d < pars > v ) WAS : up ( VDef ( DefId Fun d ) ` VApp ` piv ) t ' now : LAZY more or less than one matching constructors : can not eta expand trace ( " Eta : " + + show ( length l ) + + " patterns match at type " + + show n + + show vl ) $ eta expand v at data type n vl trace ("upData " ++ show v ++ " at " ++ n ++ show vl) $ when checking a mutual data decl, the sig entry of the second data is not yet in place when checking the first, thus, lookup may fail no constructor: empty type for each constructor, match its core against the type produces a list of maybe (c.info, environment) traceM $ "Matching constructors: " ++ show cenvs exactly one matching constructor: can eta expand get list of index values from environment for each argument of constructor, get value lookup type sig t of destructor d pi-apply destructor type to parameters, indices and value v recursively eta expand (d <pars> v) WAS: up (VDef (DefId Fun d) `VApp` piv) t' now: LAZY more or less than one matching constructors: cannot eta expand trace ("Eta: " ++ show (length l) ++ " patterns match at type " ++ show n ++ show vl) $ TODO : now compare elements in the group NEED types for equality check trivial if groups are singletons lookup type sig t of destructor d pi - apply destructor type to parameters and value v recursively eta expand ( d < pars > v ) TODO: now compare elements in the group NEED types for equality check trivial if groups are singletons lookup type sig t of destructor d pi-apply destructor type to parameters and value v recursively eta expand (d <pars> v) refl : [A : Set] -> [a : A] -> Id A a a up{Id T t t'} x Id T t t' =?= Id A a a --> A = T, a = t, a = t' erase if n is a empty type eta expand v if n is a tuple type lookup type sig t of destructor d pi - apply destructor type to parameters and value v recursively eta expand ( d < pars > v ) ( map ( \d - > VDef d ` VApp ` ( vl + + [ v ] ) ) ds ) erase if n is a empty type eta expand v if n is a tuple type lookup type sig t of destructor d pi-apply destructor type to parameters and value v recursively eta expand (d <pars> v) (map (\d -> VDef d `VApp` (vl ++ [v])) ds) pattern matching --------------------------------------------------- no need to try absurd clauses done matching: eval clause body in env and apply it to remaining arsg too few arguments to fire clause: give up trace (show env ++ show v0) $ force against constructor pattern or pair pattern (ErasedP _,_) -> return $ Just env -- TOO BAD, DOES NOT WORK (eta!) | x == y -> return $ Just env The following case is NOT IMPOSSIBLE: If a value is a dotted record value, we do not succeed, since it is not sure this is the correct constructor. * Typed Non-linear Matching ----------------------------------------- @nonLinMatch True@ allows also instantiation in v0 this is useful for finding all matching constructors for an erased argument in checkPattern force against constructor pattern Here, we do accept dotted constructors, since we are abusing this for unification. if the match against an unconfirmed constructor we can succeed, but not compute a sensible environment Check that the previous solution for @x@ is equal to @v@. Here, we need the type! typed non-linear matching of patterns ps against values vs at type tv env is the accumulator for the solution of the matching | Expand a top-level pattern synonym ------------------------------------------------------------------------- * Unification ------------------------------------------------------------------------- Checks that generic values @ks@ does not occur in value @v@. In the process, @tv@ is normalized. neutrals Binders: ALT: do not evaluate under binders (just check environment). This is less precise but more efficient. Can give false alarms. pairs sizes impossible: closure (reduced away) heterogeneous typed equality and subtyping ------------------------ eqValBool tv v v' = (eqVal tv v v' >> return True) `catchError` (\ _ -> return False) force history not yet, left , right WONTFIX : FOR THE FOLLOWING TO BE SOUND , ONE NEEDS COERCIVE SUBTYPING ! the problem is that after extraction , erased arguments are gone ! a function which does not use its argument can be used as just a function [ A ] - > A < = A - > A A < = [ A ] WONTFIX: FOR THE FOLLOWING TO BE SOUND, ONE NEEDS COERCIVE SUBTYPING! the problem is that after extraction, erased arguments are gone! a function which does not use its argument can be used as just a function [A] -> A <= A -> A A <= [A] subtyping for erasure disabled but subtyping for polarities! subtyping --------------------------------------------------------- enter ("subtype " ++ show v1 ++ " <= " ++ show v2) $ Pol ::= Pos | Neg | mixed view the shape of a type or a pair of types both are function types sort of same shape same data, but with possibly different args both neutral same sort constant Set i and Set j typeView does not normalize! stuck fun type variable type variable stuck case error $ "typeView " ++ show tv comparing objects or higher-kinded types of the same shape, otherwise they cannot contain common terms text ("leqVal' (subtyping) " ++ show (Map.toList $ ren) ++ " |-") text ("leqVal' " ++ show (Map.toList $ ren) ++ " |-") text ("leqVal' " ++ show (Map.toList $ ren) ++ " |-") ce <- ask trace (("rewrites: " +?+ show (rewrites ce)) ++ " leqVal': " ++ show ce ++ "\n |- " ++ show u1' ++ "\n <=" ++ show p ++ " " ++ show u2') $ leads to LOOP, see HungryEta.ma subtyping directed by common type shape -------------------------------------------------------- -------------------------------------------------------- structural subtyping (not directed by types) (u1f /= u1,u2f /= u2) of enter ("not forcing " ++ show (f1,f2,f)) $ leqStructural u1 u2 where leqStructural u1 u2 = --------------------------------------- --------------------------------------- ------------------------------------------------------- ------------------------------------------------------- take smaller domain compare for eq. extra cases since vSize is not implemented as VBelow Le Infty extra cases since vSize is not implemented as VBelow Le Infty care needed to not make <=# a subtype of <# careful here careful here unresolved eta-expansions (e.g. at coinductive type) leqVal' f p Nothing av1 av2 -- do not compare types the following three cases should be impossible but are n't . I gave up on this bug -- 2012 - 01 - 25 FOUND IT the following three cases should be impossible but aren't. I gave up on this bug -- 2012-01-25 FOUND IT smart equality is not transitive FIXED: do not have type here, but v1,v2 are neutral subtyping ax naive implementation for now naive implementation for now absurd cases need not be checked q ::= mixed | Pos | Neg recoverFail $ "projections " ++ show p1 ++ " and " ++ show p2 ++ " differ!" WAS: , erased = erased $ decor $ first12 dom12 } WAS: (erased dec || p == Pol.Const) type is invariant, so it does not matter which one we take leqNe :: Force -> Val -> Val -> TypeCheck TVal leqNe f v1 v2 = --trace ("leqNe " ++ show v1 ++ "<=" ++ show v2) $ do case (v1,v2) of (VGen k1, VGen k2) -> if k1 == k2 then do dom <- lookupGem k1 return $ typ dom else throwErrorMsg $ "gen mismatch " ++ show k1 ++ " " ++ show k2 pol ::= Param | Pos | Neg trace ("leqApp: " -- ++ show delta ++ " |- " ++ show v1 ++ show w1 ++ " <=" ++ show pol ++ " " ++ show v2 ++ show w2) $ constructor constructor check for least or greatest type least type least type data type trace ( " leqApp : posOrig = " + + show ( pos + + [ positivitySizeIndex ] ) ) $ the polComp will replace all SPos by Pos otherwise , we are dealing with a ( co ) recursive function or a constructor data type trace ("leqApp: posOrig = " ++ show (pos ++ [positivitySizeIndex])) $ the polComp will replace all SPos by Pos otherwise, we are dealing with a (co) recursive function or a constructor _ -> headMismatch _ -> recoverFail $ "leqApp: " ++ show v1 ++ show w1 ++ " !<=" ++ show pol ++ " " ++ show v2 ++ show w2 comparing sorts and sizes ----------------------------------------- leqSort mixed s1 s2 = leqSort' s1 s2 >> leqSort' s2 s1 leqSort Neg s1 s2 = leqSort' s2 s1 leqSort Pos s1 s2 = leqSort' s1 s2 let err = "universe test " ++ show s1 ++ " <= " ++ show s2 ++ " failed" substaging on size values TODO: better handling of sums! (VGen i1,VGen i2) -> do d <- getSizeDiff i1 i2 -- check size relation from constraints case d of Nothing -> recoverFail $ "leqSize: head mismatch: " ++ show v1 ++ " !<= " ++ show v2 Just k -> case (pol,k) of (_, 0) | pol == mixed -> return () (Pos, _) | k >= 0 -> return () (Neg, _) | k <= 0 -> return () _ -> recoverFail $ "leqSize: " ++ show v1 ++ " !<=" ++ show pol ++ " " ++ show v2 ++ " failed" if v1 == v2 then return () else throwErrorMsg $ "leqSize: head mismatch: " ++ show v1 ++ " !<= " ++ show v2 all v in vs <= v2 this produces a disjunction this produces a disjunction Only cancel variables < # Allow cancelling of all variables TODO: better handling of sums! traceM ("getMinSize = " ++ show n) BAD HACK! check (VGen i1) <= (VGen i2) + k trace ( " leqSize ' " + + show v1 + + show v2 ) $ all v in vs < = v2 this produces a disjunction trace ("leqSize' " ++ show v1 ++ show v2) $ all v in vs <= v2 this produces a disjunction measures and guards ----------------------------------------------- compare lexicographically precondition : same length enter ( " checking " + + show mu1 + + " < " + + show mu2 ) $ compare lexicographically precondition: same length enter ("checking " ++ show mu1 ++ " < " ++ show mu2) $ lexSizes True mu mu' checkes mu < mu' lexSizes False mu mu' checkes mu <= mu' recoverFail $ "lexSizes: expected " ++ show a1 ++ " <= " ++ show a2 TODO : reprogram leqSize in terms of a proper compareSize THIS IS COMPLETE BOGUS ! ! ! TODO: reprogram leqSize in terms of a proper compareSize THIS IS COMPLETE BOGUS!!! not strictly smaller comparing polarities ------------------------------------------------- adding an edge to the positivity graph traceM ("adding interesting positivity graph edge " ++ show src ++ " --[ " ++ show p ++ " ]--> " ++ show tgt) TODO: solve constraints telescopes -------------------------------------------------------- | Turn a fully applied constructor value into a named record value.
# LANGUAGE TupleSections , FlexibleInstances , FlexibleContexts , NamedFieldPuns # # LANGUAGE NoImplicitPrelude # # LANGUAGE CPP # # OPTIONS_GHC -fno - warn - orphans # Activate this flag if i < $ i should only hold for i < # . # define module Eval where import Prelude hiding (mapM, null, pi) #if !MIN_VERSION_base(4,8,0) import Control.Applicative #endif import Control.Monad hiding (mapM) import Control.Monad.State (StateT, execStateT, get, gets, put) import Control.Monad.Except (runExcept, MonadError) import Control.Monad.Reader (asks, local) import qualified Data.Array as Array import qualified Data.List as List import qualified Data.Map as Map #if !MIN_VERSION_base(4,8,0) import Data.Foldable (foldMap) import Data.Monoid import Data.Traversable (traverse) #endif import Data.Traversable (mapM) import Abstract import Polarity as Pol import Value import TCM import PrettyTCM hiding ((<>)) import qualified PrettyTCM as P import TraceError import Util traceEta, traceRecord, traceMatch, traceLoop, traceSize :: String -> a -> a traceEtaM, traceRecordM, traceMatchM, traceLoopM, traceSizeM :: Monad m => String -> m () traceEta msg a = trace msg a traceEtaM msg = traceM msg traceEta msg a = trace msg a traceEtaM msg = traceM msg -} traceRecord msg a = a traceRecordM msg = return () traceMatch msg a = trace msg a traceMatchM msg = traceM msg traceMatch msg a = trace msg a traceMatchM msg = traceM msg -} failValInv :: (MonadError TraceError m) => Val -> m a failValInv v = throwErrorMsg $ "internal error: value " ++ show v ++ " violates representation invariant" Rewriting rules have the form this means that at the root , at most one rewriting step is possible . Rewriting rules are considered computational , since they trigger new ( symbolic ) computations . At least they have to be applied in - pattern matching - equality checking Otherwise there could be inconsistencies , like adding both rules Also , after adding a new rule , it could be used to rewrite the old rules . Implementation : - add a set of local rewriting rules to the context ( not to the state ) - untyped equality test between values Rewriting rules have the form this means that at the root, at most one rewriting step is possible. Rewriting rules are considered computational, since they trigger new (symbolic) computations. At least they have to be applied in - pattern matching - equality checking Otherwise there could be inconsistencies, like adding both rules Also, after adding a new rule, it could be used to rewrite the old rules. Implementation: - add a set of local rewriting rules to the context (not to the state) - untyped equality test between values -} class Reval a where reval' :: Valuation -> a -> TypeCheck a reval :: a -> TypeCheck a reval = reval' emptyVal instance Reval a => Reval (Maybe a) where reval' valu ma = traverse (reval' valu) ma instance Reval b => Reval (a,b) where reval' valu (x,v) = (x,) <$> reval' valu v instance Reval a => Reval [a] where reval' valu vs = mapM (reval' valu) vs instance Reval Env where reval' valu (Environ rho mmeas) = flip Environ mmeas <$> reval' valu rho no need to reevaluate , since only sizes instance Reval Valuation where reval' valu (Valuation valu') = Valuation . (++ valuation valu) <$> reval' valu valu' instance Reval a => Reval (Measure a) where reval' valu beta = traverse (reval' valu) beta instance Reval a => Reval (Bound a) where reval' valu beta = traverse (reval' valu) beta instance Reval Val where reval' valu u = traceLoop ("reval " ++ show u) $ do let reval v = reval' valu v reEnv rho = reval' valu rho reFun fv = reval' valu fv case u of VSort (CoSet v) -> VSort . CoSet <$> reval v VSort{} -> return u VInfty -> return u VZero -> return u VMax{} -> return u VPlus{} -> return u VPair v1 v2 -> VPair <$> reval v1 <*> reval v2 VRecord ri rho -> VRecord ri <$> mapAssocM reval rho VApp v vl -> do v' <- reval v vl' <- mapM reval vl w <- foldM app v' vl' CAN'T rewrite defined fun / data VCase v tv env cl -> do v' <- reval v tv' <- reval tv env' <- reEnv env evalCase v' tv' env' cl VBelow ltle v -> VBelow ltle <$> reval v VGuard beta v -> VGuard <$> reval beta <*> reval v VQuant pisig x dom fv -> VQuant pisig x <$> mapM reval dom <*> reFun fv > do dom ' < - mapM reval dom env ' < - reEnv env return $ VQuant pisig x dom ' env ' b VQuant pisig x dom env b -> do dom' <- mapM reval dom env' <- reEnv env return $ VQuant pisig x dom' env' b -} VConst v -> VConst <$> reval' valu v VLam x env e -> flip (VLam x) e <$> reval' valu env VAbs x i v valu' -> VAbs x i v <$> reval' valu valu' VClos env e -> do env' <- reEnv env return $ VClos env' e VMeta i env k -> do env' <- reEnv env return $ VMeta i env' k VSing v tv -> vSing ==<< (reval v, reval tv) VIrr -> return u v -> throwErrorMsg $ "NYI : reval " ++ show v TODO : singleton Sigma types vSing :: Val -> TVal -> TypeCheck TVal vSing v (VQuant Pi x' dom fv) = do let x = fresh $ if emptyName x' then "xSing#" else suggestion x' VQuant Pi x dom <$> do underAbs_ x dom fv $ \ i xv bv -> do v <- app v xv vAbs x i <$> vSing v bv vSing _ tv@(VSing{}) = return $ tv vSing v tv = return $ VSing v tv vSing : : Val - > TVal - > TVal vSing v ( VQuant Pi x dom env b ) ( VQuant Pi x dom ( update env xv v ) $ Sing ( App ( ) ( Var x ) ) b ) where xv = fresh ( " vSing # " + + suggestion x ) vSing v ( VQuant Pi x dom env b ) = ( VQuant Pi x ' dom ( update env xv v ) $ Sing ( App ( ) ( Var x ' ) ) b ' ) where xv = fresh ( " vSing # " + + suggestion x ) x ' = fresh $ if emptyName x then " xSing # " else suggestion x b ' = parSubst ( \ y - > Var $ if y = = x then x ' else y ) b vSing _ tv@(VSing { } ) = tv vSing v tv = VSing v tv vSing :: Val -> TVal -> TVal vSing v (VQuant Pi x dom env b) (VQuant Pi x dom (update env xv v) $ Sing (App (Var xv) (Var x)) b) where xv = fresh ("vSing#" ++ suggestion x) vSing v (VQuant Pi x dom env b) = (VQuant Pi x' dom (update env xv v) $ Sing (App (Var xv) (Var x')) b') where xv = fresh ("vSing#" ++ suggestion x) x' = fresh $ if emptyName x then "xSing#" else suggestion x b' = parSubst (\ y -> Var $ if y == x then x' else y) b vSing _ tv@(VSing{}) = tv vSing v tv = VSing v tv -} reduce :: Val -> TypeCheck Val reduce v = traceLoop ("reduce " ++ show v) $ do rewrules <- asks rewrites mr <- findM (\ rr -> equal v (lhs rr)) rewrules case mr of Nothing -> return v Just rr -> traceRew ("firing " ++ show rr) $ return (rhs rr) equal :: Val -> Val -> TypeCheck Bool equal u1 u2 = traceLoop ("equal " ++ show u1 ++ " =?= " ++ show u2) $ case (u1,u2) of (VApp v1 vl1, VApp v2 vl2) -> (equal v1 v2) `andLazy` (equals' vl1 vl2) (VQuant pisig1 x1 dom1 fv1, VQuant pisig2 x2 dom2 fv2) | pisig1 == pisig2 -> new x1 dom1 $ \ vx -> equal ==<< (app fv1 vx, app fv2 vx) (VProj _ p, VProj _ q) -> return $ p == q (VPair v1 w1, VPair v2 w2) -> (equal v1 v2) `andLazy` (equal w1 w2) (VBelow ltle1 v1, VBelow ltle2 v2) | ltle1 == ltle2 -> equal v1 v2 (VSing v1 tv1, VSing v2 tv2) -> (equal v1 v2) `andLazy` (equal tv1 tv2) PROBLEM : DOM . MISSING , CAN'T " up " fresh variable addName (bestName [absName fv1, absName fv2]) $ \ vx -> equal ==<< (app fv1 vx, app fv2 vx) (VRecord ri1 rho1, VRecord ri2 rho2) | notDifferentNames ri1 ri2 -> and <$> zipWithM (\ (n1,v1) (n2,v2) -> ((n1 == n2) &&) <$> equal' v1 v2) rho1 rho2 _ -> return False notDifferentNames :: RecInfo -> RecInfo -> Bool notDifferentNames (NamedRec _ n _ _) (NamedRec _ n' _ _) = n == n' notDifferentNames _ _ = True equals' :: [Val] -> [Val] -> TypeCheck Bool equals' [] [] = return True equals' (w1:vs1) (w2:vs2) = (equal' w1 w2) `andLazy` (equals' vs1 vs2) equals' vl1 vl2 = return False equal' :: Val -> Val -> TypeCheck Bool equal' w1 w2 = whnfClos w1 >>= \ v1 -> equal v1 =<< whnfClos w2 reify :: Val -> TypeCheck Expr reify v = reify' (5, True) v reify' :: (Int, Bool) -> Val -> TypeCheck Expr reify' m v0 = do case v0 of (VClos rho e) -> whnf rho e >>= reify (VZero) -> return $ Zero (VInfty) -> return $ Infty (VSucc v) -> Succ <$> reify v (VMax vs) -> maxE <$> mapM reify vs (VPlus vs) -> Plus <$> mapM reify vs return $ iterate Succ (Meta x) !! n (VSort (CoSet v)) -> Sort . CoSet <$> reify v (VSort s) -> return $ Sort $ vSortToSort s (VBelow ltle v) -> Below ltle <$> reify v (VQuant pisig x dom fv) -> do dom' <- mapM reify dom underAbs_ x dom fv $ \ k xv vb -> do let x' = unsafeName (suggestion x ++ "~" ++ show k) piSig pisig (TBind x' dom') <$> reify vb (VSing v tv) -> liftM2 Sing (reify v) (reify tv) fv | isFun fv -> do let x = absName fv addName x $ \ xv@(VGen k) -> do vb <- app fv xv let x' = unsafeName (suggestion x ++ "~" ++ show k) TODO : dec ! ? (VGen k) -> return $ Var $ unsafeName $ "~" ++ show k (VDef d) -> return $ Def d (VProj fx n) -> return $ Proj fx n (VPair v1 v2) -> Pair <$> reify v1 <*> reify v2 (VRecord ri rho) -> Record ri <$> mapAssocM reify rho (VApp v vl) -> if fst m > 0 && snd m else let m' = (fst m, True) in liftM2 (foldl App) (reify' m' v) (mapM (reify' m') vl) (VCase v tv rho cls) -> do e <- reify v t <- reify tv (VIrr) -> return $ Irr v -> failDoc (text "Eval.reify" <+> prettyTCM v <+> text "not implemented") toExpr :: Val -> TypeCheck Expr toExpr v = case v of VClos rho e -> closToExpr rho e VZero -> return $ Zero VInfty -> return $ Infty (VSucc v) -> Succ <$> toExpr v VMax vs -> maxE <$> mapM toExpr vs VPlus vs -> Plus <$> mapM toExpr vs VMeta x rho n -> metaToExpr x rho n VSort s -> Sort <$> mapM toExpr s VMeasured mu bv -> pi <$> (TMeasure <$> mapM toExpr mu) <*> toExpr bv VGuard beta bv -> pi <$> (TBound <$> mapM toExpr beta) <*> toExpr bv VBelow Le VInfty -> return $ Sort $ SortC Size VBelow ltle bv -> Below ltle <$> toExpr bv VQuant pisig x dom fv -> underAbs' x fv $ \ xv bv -> piSig pisig <$> (TBind x <$> mapM toExpr dom) <*> toExpr bv VSing v tv -> Sing <$> toExpr v <*> toExpr tv fv | isFun fv -> addName (absName fv) $ \ xv -> toExpr =<< app fv xv VLam x rho e - > addNameEnv x rho $ \ x rho - > defaultDec x < $ > closToExpr rho e VLam x rho e -> addNameEnv x rho $ \ x rho -> Lam defaultDec x <$> closToExpr rho e -} VUp v tv -> toExpr v VGen k -> Var <$> nameOfGen k VDef d -> return $ Def d VProj fx n -> return $ Proj fx n VPair v1 v2 -> Pair <$> toExpr v1 <*> toExpr v2 VRecord ri rho -> Record ri <$> mapAssocM toExpr rho VApp v vl -> liftM2 (foldl App) (toExpr v) (mapM toExpr vl) VCase v tv rho cls -> Case <$> toExpr v <*> (Just <$> toExpr tv) <*> mapM (clauseToExpr rho) cls VIrr -> return $ Irr addNameEnv :: Name -> Env -> (Name -> Env -> TypeCheck a) -> TypeCheck a addNameEnv x rho cont = do newWithGen x dom' $ \ k _ -> do x' <- nameOfGen k cont x' (update rho x (VGen k)) addPatternEnv :: Pattern -> Env -> (Pattern -> Env -> TypeCheck a) -> TypeCheck a addPatternEnv p rho cont = case p of SizeP e x -> addNameEnv x rho $ cont . VarP PairP p1 p2 -> addPatternEnv p1 rho $ \ p1 rho -> addPatternEnv p2 rho $ \ p2 rho -> cont (PairP p1 p2) rho \ ps rho - > cont ( ConP pi n ps ) rho SuccP p -> addPatternEnv p rho $ cont . SuccP UnusableP p -> addPatternEnv p rho $ cont . UnusableP DotP e -> do { e <- closToExpr rho e ; cont (DotP e) rho } AbsurdP -> cont AbsurdP rho ErasedP p -> addPatternEnv p rho $ cont . ErasedP addPatternsEnv :: [Pattern] -> Env -> ([Pattern] -> Env -> TypeCheck a) -> TypeCheck a addPatternsEnv [] rho cont = cont [] rho addPatternsEnv (p:ps) rho cont = addPatternEnv p rho $ \ p rho -> addPatternsEnv ps rho $ \ ps rho -> cont (p:ps) rho class ClosToExpr a where closToExpr :: Env -> a -> TypeCheck a bindClosToExpr :: Env -> a -> (Env -> a -> TypeCheck b) -> TypeCheck b closToExpr rho a = bindClosToExpr rho a $ \ rho a -> return a bindClosToExpr rho a cont = cont rho =<< closToExpr rho a instance ClosToExpr a => ClosToExpr [a] where closToExpr = traverse . closToExpr instance ClosToExpr a => ClosToExpr (Maybe a) where closToExpr = traverse . closToExpr instance ClosToExpr a => ClosToExpr (Dom a) where closToExpr = traverse . closToExpr instance ClosToExpr a => ClosToExpr (Sort a) where closToExpr = traverse . closToExpr instance ClosToExpr a => ClosToExpr (Measure a) where closToExpr = traverse . closToExpr instance ClosToExpr a => ClosToExpr (Bound a) where closToExpr = traverse . closToExpr instance ClosToExpr a => ClosToExpr (Tagged a) where closToExpr = traverse . closToExpr instance ClosToExpr a => ClosToExpr (TBinding a) where bindClosToExpr rho (TBind x a) cont = do a <- closToExpr rho a addNameEnv x rho $ \ x rho -> cont rho $ TBind x a bindClosToExpr rho (TMeasure mu) cont = cont rho . TMeasure =<< closToExpr rho mu bindClosToExpr rho (TBound beta) cont = cont rho . TBound =<< closToExpr rho beta instance ClosToExpr Telescope where bindClosToExpr rho (Telescope tel) cont = loop rho tel $ \ rho -> cont rho . Telescope where loop rho [] cont = cont rho [] loop rho (tb : tel) cont = bindClosToExpr rho tb $ \ rho tb -> loop rho tel $ \ rho tel -> cont rho $ tb : tel instance ClosToExpr Expr where closToExpr rho e = case e of Sort s -> Sort <$> closToExpr rho s Zero -> return e Succ e -> Succ <$> closToExpr rho e Infty -> return e Max es -> Max <$> closToExpr rho es Plus es -> Plus <$> closToExpr rho es Meta x -> return e Var x -> toExpr =<< whnf rho e Def d -> return e Case e mt cls -> Case <$> closToExpr rho e <*> closToExpr rho mt <*> mapM (clauseToExpr rho) cls LLet tb tel e1 e2 | null tel -> do e1 <- closToExpr rho e1 bindClosToExpr rho tb $ \ rho tb -> LLet tb tel e1 <$> closToExpr rho e2 Proj fx n -> return e Record ri rs -> Record ri <$> mapAssocM (closToExpr rho) rs Pair e1 e2 -> Pair <$> closToExpr rho e1 <*> closToExpr rho e2 App e1 e2 -> App <$> closToExpr rho e1 <*> closToExpr rho e2 Lam dec x e -> addNameEnv x rho $ \ x rho -> Lam dec x <$> closToExpr rho e Below ltle e -> Below ltle <$> closToExpr rho e { } e | null tel - > pi < $ > closToExpr rho mu < * > closToExpr rho e { } e | null tel - > pi < $ > closToExpr rho beta < * > closToExpr rho e Quant Pi tel mu@TMeasure{} e | null tel -> pi <$> closToExpr rho mu <*> closToExpr rho e Quant Pi tel beta@TBound{} e | null tel -> pi <$> closToExpr rho beta <*> closToExpr rho e -} Quant piSig tb e -> bindClosToExpr rho tb $ \ rho tb -> Quant piSig tb <$> closToExpr rho e Sing e1 e2 -> Sing <$> closToExpr rho e1 <*> closToExpr rho e2 Ann taggedE -> Ann <$> closToExpr rho taggedE Irr -> return e metaToExpr :: Int -> Env -> Int -> TypeCheck Expr metaToExpr x rho k = return $ iterate Succ (Meta x) !! k clauseToExpr :: Env -> Clause -> TypeCheck Clause clauseToExpr rho (Clause vtel ps me) = addPatternsEnv ps rho $ \ ps rho -> Clause vtel ps <$> mapM (closToExpr rho) me , since it reads the globally defined constants from the signature . are expanded away . whnf :: Env -> Expr -> TypeCheck Val whnf env e = enter ("whnf " ++ show e) $ case e of Meta i -> do let v = VMeta i env 0 traceMetaM $ "whnf meta " ++ show v return v LLet (TBind x dom) tel e1 e2 | null tel -> do let v1 = mkClos env e1 whnf (update env x v1) e2 e1 | erased dec - > whnf env e1 | otherwise - > return $ VLam x env e1 Lam dec x e1 | erased dec -> whnf env e1 | otherwise -> return $ VLam x env e1 -} Lam dec x e1 -> return $ vLam x env e1 Below ltle e -> VBelow ltle <$> whnf env e Quant pisig (TBind x dom) b -> do Pi is strict in its first argument return $ VQuant pisig x dom' $ vLam x env b - otherwise to a measured type ( lhs of funs ) Quant Pi (TMeasure mu) b -> do muv <- whnfMeasure env mu case (envBound env) of Nothing -> return $ VMeasured muv bv Just muv' -> return $ VGuard (Bound Lt muv muv') bv Quant Pi (TBound (Bound ltle mu mu')) b -> do muv <- whnfMeasure env mu muv' <- whnfMeasure env mu' return $ VGuard (Bound ltle muv muv') bv Sing e t -> do tv <- whnf env t sing env e tv Pair e1 e2 -> VPair <$> whnf env e1 <*> whnf env e2 Proj fx n -> return $ VProj fx n Record ri@(NamedRec Cons _ _ _) rs -> VRecord ri <$> mapAssocM (whnf env) rs Record ri rs -> return $ VRecord ri $ mapAssoc (mkClos env) rs App e1 el - > do v1 < - whnf env e1 vl < - liftM ( filter ( /= VIrr ) ) $ mapM ( whnf env ) el app v1 vl App e1 el -> do v1 <- whnf env e1 vl <- liftM (filter (/= VIrr)) $ mapM (whnf env) el app v1 vl -} App f e -> do vf <- whnf env f let ve = mkClos env e app vf ve App e1 el - > do v1 < - whnf env e1 vl < - mapM ( whnf env ) el app v1 vl App e1 el -> do v1 <- whnf env e1 vl <- mapM (whnf env) el app v1 vl -} Case e (Just t) cs -> do v <- whnf env e vt <- whnf env t evalCase v vt env cs Sort s -> whnfSort env s >>= return . vSort Infty -> return VInfty Zero -> return VZero return $ succSize v return $ maxSize vs return $ plusSizes vs Def (DefId LetK n) -> do item <- lookupSymbQ n whnfClos (definingVal item) Def (DefId (ConK DefPat) n) -> whnfClos . definingVal =<< lookupSymbQ n ( DefId ( ConK DefPat ) n ) - > throwErrorMsg $ " internal error : whnf of defined pattern " + + show n Def id -> return $ vDef id Con co n - > return $ VCon co n Def n - > return $ VDef n Let n - > do sig < - gets signature let ( LetSig _ v ) = lookupSig n sig return v Con co n -> return $ VCon co n Def n -> return $ VDef n Let n -> do sig <- gets signature let (LetSig _ v) = lookupSig n sig return v -} Var y -> lookupEnv env y >>= whnfClos Irr -> return VIrr e -> throwErrorMsg $ "NYI whnf " ++ show e whnfMeasure :: Env -> Measure Expr -> TypeCheck (Measure Val) whnfMeasure rho (Measure mu) = mapM (whnf rho) mu >>= return . Measure whnfSort :: Env -> Sort Expr -> TypeCheck (Sort Val) whnfSort rho (SortC c) = return $ SortC c whnfSort rho (CoSet e) = whnf rho e >>= return . CoSet whnfSort rho (Set e) = whnf rho e >>= return . Set whnfClos :: Clos -> TypeCheck Val case v of (VClos e rho) -> whnf e rho THIS IS TO SOLVE A PROBLEM v -> return v whnf' :: Expr -> TypeCheck Val whnf' e = do env <- getEnv whnf env e < t : Pi x : : a < t x : b > sing :: Env -> Expr -> TVal -> TypeCheck TVal sing rho e tv = do vSing v tv sing env ' e ( VPi dec x av env b ) = do return $ VPi dec x ' av env '' ( Sing ( App e ( Var x ' ) ) b ) x ' = if x = = " " then fresh env '' else x sing _ _ tv@(VSing { } ) = return $ tv return $ VSing v tv sing env' e (VPi dec x av env b) = do return $ VPi dec x' av env'' (Sing (App e (Var x')) b) x' = if x == "" then fresh env'' else x sing _ _ tv@(VSing{}) = return $ tv return $ VSing v tv -} sing' :: Expr -> TVal -> TypeCheck TVal sing' e tv = do env <- getEnv sing env e tv evalCase :: Val -> TVal -> Env -> [Clause] -> TypeCheck Val evalCase v tv env cs = do m <- matchClauses env cs [v] case m of Nothing -> return $ VCase v tv env cs Just v' -> return $ v' piApp :: TVal -> Clos -> TypeCheck TVal piApp (VGuard beta bv) w = piApp bv w piApp (VQuant Pi x dom fv) w = app fv w piApp tv w = failDoc (text "piApp: IMPOSSIBLE to instantiate" <+> prettyTCM tv <+> text "to argument" <+> prettyTCM w) piApps :: TVal -> [Clos] -> TypeCheck TVal piApps tv [] = return tv piApps tv (v:vs) = do tv' <- piApp tv v piApps tv' vs updateValu :: Valuation -> Int -> Val -> TypeCheck Valuation updateValu valu i v = reval' (sgVal i v) valu in app u v , u might be a VDef ( e.g. when coming from reval ) app :: Val -> Clos -> TypeCheck Val app = app' True app' :: Bool -> Val -> Clos -> TypeCheck Val app' expandDefs u v = do let app = app' expandDefs appDef' True f vs = appDef f vs appDef' False f vs = return $ VDef (DefId FunK f) `VApp` vs appDef_ = appDef' expandDefs case u of VProj Pre n -> flip (app' expandDefs) (VProj Post n) =<< whnfClos v VRecord ri rho -> do let VProj Post n = v maybe (throwErrorMsg $ "app: projection " ++ show n ++ " not found in " ++ show u) whnfClos (lookup n rho) VDef (DefId FunK n) -> appDef_ n [v] VApp (VDef (DefId FunK n)) vl -> appDef_ n (vl ++ [v]) VApp h@(VDef (DefId (ConK Cons) n)) vl -> do return $ VApp h (vl ++ [v]) VApp ( VDef i d ) vl - > VApp ( VDef i d ) ( vl + + [ v ] ) VApp v1 vl -> return $ VApp v1 (vl ++ [v]) VSing u ( ) - > vSing < $ > app u v < * > app fu v VLam x env e -> whnf (update env x v) e VConst u -> whnfClos u VAbs x i u valu -> flip reval' u =<< updateValu valu i v VUp u (VQuant Pi x dom fu) -> up False ==<< (app u v, app fu v) VUp u1 ( b ) - > do { - VUp u1 (VQuant Pi x dom rho b) -> do bv <- whnf (update rho x v) b up False v1 bv -} VUp u1 (VApp (VDef (DefId DatK n)) vl) -> do u' <- force u app u' v VIrr -> return VIrr 2010 - 11 - 01 this breaks extraction for System U example VIrr - > throwErrorMsg $ " app internal error : " + + show ( VApp u [ v ] ) VIrr -> throwErrorMsg $ "app internal error: " ++ show (VApp u [v]) -} _ -> return $ VApp u [v] app : : Val - > [ Val ] - > ( VApp u2 c2 , _ ) - > app u2 ( c2 + + c ) ( VUp v ( VPi dec x av rho b ) , w : wl ) - > do ( VIrr , _ ) - > return VIrr ( VIrr , _ ) - > throwErrorMsg $ " app internal error : " + + show ( VApp u c ) _ - > return $ VApp u c unroll a corecursive definition one time ( until constructor appears ) force' :: Bool -> Val -> TypeCheck (Bool, Val) (b',tv') <- force' b tv return (b', VSing v tv') force' b (VClos rho e) = do v <- whnf rho e force' b v force' b v@(VDef (DefId FunK n)) = failValInv v do sig < - gets signature case lookupSig n sig of ( FunSig CoInd t cl True ) - > do m < - matchClauses [ ] cl [ ] case m of Just v ' - > force v ' Nothing - > return v _ - > return v do sig <- gets signature case lookupSig n sig of (FunSig CoInd t cl True) -> do m <- matchClauses [] cl [] case m of Just v' -> force v' Nothing -> return v _ -> return v -} force' b v@(VApp (VDef (DefId FunK n)) vl) = enterDoc (text "force" <+> prettyTCM v) $ do sig <- gets signature case Map.lookup n sig of Just (FunSig isCo t ki ar cl True _) -> traceMatch ("forcing " ++ show v) $ do m <- matchClauses emptyEnv cl vl case m of Just v' -> traceMatch ("forcing " ++ show n ++ " succeeded") $ force' True v' Nothing -> traceMatch ("forcing " ++ show n ++ " failed") $ return (b, v) _ -> return (b, v) force' b v = return (b, v) force :: Val -> TypeCheck Val liftM snd $ force' False v appDef :: QName -> [Val] -> TypeCheck Val trace ( " appDef " + + n ) $ do sig <- gets signature case (Map.lookup n sig) of Just (FunSig { isCo = Ind, arity = ar, clauses = cl, isTypeChecked = True }) | length vl >= fullArity ar -> do m <- matchClauses emptyEnv cl vl case m of Nothing -> return $ VApp (VDef (DefId FunK n)) vl Just v2 -> return v2 _ -> return $ VApp (VDef (DefId FunK n)) vl up :: Bool -> Val -> TVal -> TypeCheck Val up f (VUp v tv') tv = up f v tv up f v tv@VQuant{ vqPiSig = Pi } = return $ VUp v tv up f _ (VSing v vt) = up f v vt up f v (VDef d) = failValInv $ VDef d up f v (VApp (VDef (DefId DatK d)) vl) = upData f v d vl up f v _ = return v Most of the code to eta expand on data types is in TypeChecker.hs " typeCheckDeclaration " Currently , eta expansion only happens at data * types * with exactly one constructor . In a first step , this will be extended to non - recursive pattern inductive families . The strategy is : match type value with result type for all the constructors 0 . if there are no matches , eta expand to * ( VIrr ) 1 . if there is exactly one match , eta expand accordingly using destructors 2 . if there are more matches , do not eta - expand up{Vec A ( suc n ) } x = ( head A n x ) ( tail A n x ) up{Vec ( suc zero ) } x = vcons Bool zero ( head ) ( tail Bool zero x ) For patterns of : ( A : Set ) - > Nat - > Set are [ A , suc n ] - matching Bool , suc zero against A , suc n yields A = Bool , n = zero - this means we can eta expand to through the fields of vcons - if Index use value obtained by matching - if Field destr , use destr < all pars > < all indices > x TypeChecker.hs "typeCheckDeclaration" Currently, eta expansion only happens at data *types* with exactly one constructor. In a first step, this will be extended to non-recursive pattern inductive families. The strategy is: match type value with result type for all the constructors 0. if there are no matches, eta expand to * (VIrr) 1. if there is exactly one match, eta expand accordingly using destructors 2. if there are more matches, do not eta-expand up{Vec A (suc n)} x = vcons A n (head A n x) (tail A n x) up{Vec Bool (suc zero)} x = vcons Bool zero (head Bool zero x) (tail Bool zero x) For vcons - the patterns of Vec : (A : Set) -> Nat -> Set are [A,suc n] - matching Bool,suc zero against A,suc n yields A=Bool,n=zero - this means we can eta expand to vcons - go through the fields of vcons - if Index use value obtained by matching - if Field destr, use destr <all pars> <all indices> x -} matchingConstructors :: Val -> TypeCheck (Maybe [(ConstructorInfo,Env)]) matchingConstructors (VApp (VDef (DefId DatK d)) vl) = matchingConstructors' d vl >>= return . Just matchingConstructors v = return Nothing matchingConstructors' :: QName -> [Val] -> TypeCheck [(ConstructorInfo,Env)] matchingConstructors' n vl = do sige <- lookupSymbQ n case sige of matchingConstructors'' True vl dv cs matchingConstructors'' :: Bool -> [Val] -> Val -> [ConstructorInfo] -> TypeCheck [(ConstructorInfo,Env)] matchingConstructors'' symm vl dv cs = do vl <- mapM whnfClos vl compressMaybes <$> do forM cs $ \ ci -> do let ps = snd (cPatFam ci) list of patterns ps where D ps is the constructor target fmap (ci,) <$> nonLinMatchList symm emptyEnv ps vl dv data MatchingConstructors a = NoConstructor | OneConstructor a | ManyConstructors | UnknownConstructors deriving (Eq,Show) getMatchingConstructor eta : must the field be set of the data type -> TypeCheck (MatchingConstructors parvs : the parameter half of the arguments indvs : the index values of the constructor )) getMatchingConstructor eta n vl = traceRecord ("getMatchingConstructor " ++ show (n, vl)) $ do when checking a mutual data , the sig entry of the second data is not yet in place when checking the first , thus , lookup may fail sig <- gets signature case Map.lookup n sig of Just (DataSig {symbTyp = dv, numPars = npars, isCo = co, constructors = cs, etaExpand}) | eta `implies` etaExpand -> cenvs <- matchingConstructors'' False vl dv cs traceRecordM $ "Matching constructors: " ++ show cenvs case cenvs of exactly one matching constructor : can eta expand [ ( ci , env ) ] - > if not ( eta ` implies ` cEtaExp ci ) then return UnknownConstructors else do [(ci,env)] -> if eta && not (cEtaExp ci) then return UnknownConstructors else do let fis = cFields ci let indices = filter (\ fi -> fClass fi == Index) fis let indvs = map (\ fi -> lookupPure env (fName fi)) indices let (pars, _) = splitAt npars vl return $ OneConstructor (co, pars, env, indvs, ci) more or less than one matching constructors : can not eta expand return ManyConstructors _ -> traceRecord ("no eta expandable type") $ return UnknownConstructors getFieldsAtType -> TypeCheck getFieldsAtType n vl = do mc <- getMatchingConstructor False n vl case mc of OneConstructor (_, pars, _, indvs, ci) -> do let pi = pars ++ indvs let arg (FieldInfo { fName = x, fClass = Index }) = return [] arg (FieldInfo { fName = d, fClass = Field _ }) = do t <- lookupSymbTyp d t' <- piApps t pi return [(d,t')] Just . concat <$> mapM arg (cFields ci) _ -> return Nothing similar to piApp , but for record types and projections projectType :: TVal -> Name -> Val -> TypeCheck TVal projectType tv p rv = do let fail1 = failDoc (text "expected record type when taking the projection" <+> prettyTCM (Proj Post p) P.<> comma <+> text "but found type" <+> prettyTCM tv) let fail2 = failDoc (text "record type" <+> prettyTCM tv <+> text "does not have field" <+> prettyTCM p) case tv of VApp (VDef (DefId DatK d)) vl -> do mfs <- getFieldsAtType d vl case mfs of Nothing -> fail1 Just ptvs -> case lookup p ptvs of Nothing -> fail2 _ -> fail1 upData :: Bool -> Val -> QName -> [Val] -> TypeCheck Val do let ret v' = traceEta ("Eta-expanding: " ++ show v ++ " --> " ++ show v' ++ " at type " ++ show n ++ show vl) $ return v' mc <- getMatchingConstructor True n vl case mc of NoConstructor -> ret VIrr OneConstructor (co, pars, env, indvs, ci) -> if (co==CoInd && not force) then return $ VUp v (VApp (VDef $ DefId DatK n) vl) else do let fis = cFields ci let piv = pars ++ indvs ++ [v] let arg (FieldInfo { fName = x, fClass = Index }) = lookupEnv env x arg (FieldInfo { fName = d, fClass = Field _ }) = do LetSig {symbTyp = t, definingVal = w} <- lookupSymb d t' <- piApps t piv w <- app' False v (VProj Post d) vs <- mapM arg fis let fs = map fName fis v' = VRecord (NamedRec (coToConK co) (cName ci) False notDotted) $ zip fs vs ret v' _ -> return v do let ret v ' = traceEta ( " Eta - expanding : " + + show v + + " -- > " + + show v ' + + " at type " + + n + + show vl ) $ return v ' sig < - gets signature case Map.lookup n sig of let ( pars , inds ) = splitAt npars vl False vl dv cs case cenvs of [ ( ci , env ) ] - > if not ( cEtaExp ci ) then return v else if ( co==CoInd & & not force ) then return $ VUp v ( VApp ( VDef $ DefId Dat n ) vl ) else do let cFields ci let indices = filter ( \ fi - > fClass fi = = Index ) fis let indvs = map ( \ fi - > lookupPure env ( fName fi ) ) indices let piv = pars + + indvs + + [ v ] let arg ( FieldInfo { fName = x , = Index } ) = lookupEnv env x arg ( FieldInfo { fName = d , fClass = Field _ } ) = do t < - lookupSymbTyp d t ' < - piApps t piv vs < - mapM arg fis v ' < - foldM app ( vCon co ( cName ci ) ) ( pars + + vs ) ret v ' return v _ - > return v upData :: Bool -> Val -> Name -> [Val] -> TypeCheck Val do let ret v' = traceEta ("Eta-expanding: " ++ show v ++ " --> " ++ show v' ++ " at type " ++ n ++ show vl) $ return v' sig <- gets signature case Map.lookup n sig of let (pars, inds) = splitAt npars vl cenvs <- matchingConstructors'' False vl dv cs case cenvs of [(ci,env)] -> if not (cEtaExp ci) then return v else if (co==CoInd && not force) then return $ VUp v (VApp (VDef $ DefId Dat n) vl) else do let fis = cFields ci let indices = filter (\ fi -> fClass fi == Index) fis let indvs = map (\ fi -> lookupPure env (fName fi)) indices let piv = pars ++ indvs ++ [v] let arg (FieldInfo { fName = x, fClass = Index }) = lookupEnv env x arg (FieldInfo { fName = d, fClass = Field _ }) = do t <- lookupSymbTyp d t' <- piApps t piv vs <- mapM arg fis v' <- foldM app (vCon co (cName ci)) (pars ++ vs) ret v' return v _ -> return v -} let matchC ( c , ps , ds ) = do [ ] ps inds dv case of Nothing - > return False Just env - > do let grps = groupBy ( \ ( x , _ ) ( y , _ ) - > x = = y ) env return $ all ( \ l - > length l < = 1 ) grps cs ' < - filterM matchC cs case cs ' of [ ] - > return $ VIrr [ ( c,_,ds ) ] - > do let parsv = pars + + [ v ] let aux d = do let FunSig { symbTyp = t } = lookupSig d sig t ' < - piApps t parsv up ( VDef d ` VApp ` parsv ) t ' vs < - mapM aux ds app ( VCon co c ) ( pars + + vs ) _ - > return v _ - > return v let matchC (c, ps, ds) = do menv <- nonLinMatchList [] ps inds dv case menv of Nothing -> return False Just env -> do let grps = groupBy (\ (x,_) (y,_) -> x == y) env return $ all (\ l -> length l <= 1) grps cs' <- filterM matchC cs case cs' of [] -> return $ VIrr [(c,_,ds)] -> do let parsv = pars ++ [v] let aux d = do let FunSig { symbTyp = t } = lookupSig d sig t' <- piApps t parsv up (VDef d `VApp` parsv) t' vs <- mapM aux ds app (VCon co c) (pars ++ vs) _ -> return v _ -> return v -} OLD CODE FOR NON - DEPENDENT RECORDS ONLY ( DataSig { constructors = [ ] } ) - > return $ VIrr ( DataSig { isCo = co , constructors = [ c ] , destructors = Just ds } ) - > do let vlv = vl + + [ v ] let FunSig { symbTyp = t } = lookupSig d sig t ' < - piApps t vlv up ( VDef d ` VApp ` vlv ) t ' vs < - mapM aux ds _ - > return v END OLD CODE (DataSig {constructors = []}) -> return $ VIrr (DataSig {isCo = co, constructors = [c], destructors = Just ds}) -> do let vlv = vl ++ [v] let FunSig { symbTyp = t } = lookupSig d sig t' <- piApps t vlv up (VDef d `VApp` vlv) t' vs <- mapM aux ds _ -> return v END OLD CODE -} matchClauses :: Env -> [Clause] -> [Val] -> TypeCheck (Maybe Val) matchClauses env cl vl0 = do REWRITE before matching ( 2010 - 07 - 12 dysfunctional because of lazy ? ) loop cl vl where loop [] vl = return Nothing loop (Clause _ pl (Just rhs) : cl2) vl = do x <- matchClause env pl rhs vl case x of Nothing -> loop cl2 vl Just v -> return $ Just v bindMaybe :: Monad m => m (Maybe a) -> (a -> m (Maybe b)) -> m (Maybe b) bindMaybe mma k = mma >>= maybe (return Nothing) k matchClause :: Env -> [Pattern] -> Expr -> [Val] -> TypeCheck (Maybe Val) matchClause env pl rhs vl = case (pl, vl) of (p:pl, v:vl) -> match env p v `bindMaybe` \ env' -> matchClause env' pl rhs vl ([], _) -> Just <$> do flip (foldM app) vl =<< whnf env rhs (_, []) -> return Nothing match :: Env -> Pattern -> Val -> TypeCheck (Maybe Env) do v <- case p of ConP{} -> do v <- force v0; traceMatch ("matching pattern " ++ show (p,v)) $ return v PairP{} -> do v <- force v0; traceMatch ("matching pattern " ++ show (p,v)) $ return v _ -> whnfClos v0 case (p,v) of (ErasedP p,_) -> match env p v (AbsurdP{},_) -> return $ Just env (DotP _, _) -> return $ Just env (VarP x, _) -> return $ Just (update env x v) (SizeP _ x,_) -> return $ Just (update env x v) (ProjP x, VProj Post y) | x == y -> return $ Just env (PairP p1 p2, VPair v1 v2) -> matchList env [p1,p2] [v1,v2] ( ConP _ x pl , VApp ( VDef ( DefId ( ConK _ ) y ) ) vl ) - > failValInv v (ConP _ x pl,VApp (VDef (DefId (ConK _) y)) vl) | nameInstanceOf x y -> matchList env pl vl (ConP _ x pl,VRecord (NamedRec ri y _ dotted) rs) | nameInstanceOf x y && not (isDotted dotted) -> matchList env pl $ map snd rs (p@(ConP pi _ _), v) | coPat pi == DefPat -> do p <- expandDefPat p match env p v (SuccP p', v) -> (predSize <$> whnfClos v) `bindMaybe` match env p' (UnusableP p,_) -> throwErrorMsg ("internal error: match " ++ show (p,v)) _ -> return Nothing matchList :: Env -> [Pattern] -> [Val] -> TypeCheck (Maybe Env) matchList env [] [] = return $ Just env matchList env (p:pl) (v:vl) = match env p v `bindMaybe` \ env' -> matchList env' pl vl matchList env pl vl = throwErrorMsg $ "matchList internal error: inequal length while trying to match patterns " ++ show pl ++ " against values " ++ show vl type GenToPattern = [(Int,Pattern)] type MatchState = (Env, GenToPattern) nonLinMatch :: Bool -> Bool -> MatchState -> Pattern -> Val -> TVal -> TypeCheck (Maybe MatchState) nonLinMatch undot symm st p v0 tv = traceMatch ("matching pattern " ++ show (p,v0)) $ do v <- case p of ConP{} -> force v0 PairP{} -> force v0 _ -> whnfClos v0 case (p,v) of (ErasedP{}, _) -> return $ Just st (DotP{} , _) -> return $ Just st no check in case of ! (VarP x, _) -> matchVarP x v (SizeP _ x, _) -> matchVarP x v (ProjP x, VProj Post y) | x == y -> return $ Just st (ConP _ c pl, VApp (VDef (DefId (ConK _) c')) vl) | nameInstanceOf c c' -> do vc <- conLType c tv nonLinMatchList' undot symm st pl vl vc (ConP _ c pl, VRecord (NamedRec _ c' _ dotted) rs) | nameInstanceOf c c' -> do when undot $ clearDotted dotted vc <- conLType c tv nonLinMatchList' undot symm st pl (map snd rs) vc (_, VRecord (NamedRec _ c' _ dotted) rs) | isDotted dotted && not undot -> return $ Just st (p@(ConP pi _ _), v) | coPat pi == DefPat -> do p <- expandDefPat p nonLinMatch undot symm st p v tv (PairP p1 p2, VPair v1 v2) -> do tv <- force tv case tv of VQuant Sigma x dom fv -> do nonLinMatch undot symm st p1 v1 (typ dom) `bindMaybe` \ st -> do nonLinMatch undot symm st p2 v2 =<< app fv v1 _ -> failDoc $ text "nonLinMatch: expected" <+> prettyTCM tv <+> text "to be a Sigma-type (&)" (SuccP p', v) -> (predSize <$> whnfClos v) `bindMaybe` \ v' -> nonLinMatch undot symm st p' v' tv _ -> return Nothing where matchVarP x v = do let env = fst st case List.find ((x ==) . fst) $ envMap $ fst st of Nothing -> return $ Just $ mapFst (\ env -> update env x v) st Just (y,v') -> ifM (eqValBool tv v v') (return $ Just st) (return Nothing) nonLinMatchList symm env ps vs tv nonLinMatchList :: Bool -> Env -> [Pattern] -> [Val] -> TVal -> TypeCheck (Maybe Env) nonLinMatchList symm env ps vs tv = fmap fst <$> nonLinMatchList' False symm (env, []) ps vs tv nonLinMatchList' :: Bool -> Bool -> MatchState -> [Pattern] -> [Val] -> TVal -> TypeCheck (Maybe MatchState) nonLinMatchList' undot symm st [] [] tv = return $ Just st nonLinMatchList' undot symm st (p:pl) (v:vl) tv = do tv <- force tv case tv of VQuant Pi x dom fv -> nonLinMatch undot symm st p v (typ dom) `bindMaybe` \ st' -> nonLinMatchList' undot symm st' pl vl =<< app fv v _ -> throwErrorMsg $ "nonLinMatchList': cannot match in absence of pi-type" nonLinMatchList' _ _ _ _ _ _ = return Nothing expandDefPat :: Pattern -> TypeCheck Pattern expandDefPat p@(ConP pi c ps) | coPat pi == DefPat = do PatSig ns pat v <- lookupSymbQ c unless (length ns == length ps) $ throwErrorMsg ("underapplied defined pattern in " ++ show p) let pat' = if dottedPat pi then dotConstructors pat else pat return $ patSubst (zip ns ps) pat' expandDefPat p = return p #if MIN_VERSION_base(4,11,0) From ghc 8.4 , Semigroup superinstace of Monoid instance is mandatory . instance Semigroup (TypeCheck Bool) where (<>) = andLazy instance Monoid (TypeCheck Bool) where mempty = return True mappend = (<>) mconcat = andM #else instance Monoid (TypeCheck Bool) where mempty = return True mappend = andLazy mconcat = andM #endif | Occurrence check ( used by ' SPos ' and ' ' ) . class Nocc a where nocc :: [Int] -> a -> TypeCheck Bool instance Nocc a => Nocc [a] where nocc = foldMap . nocc instance Nocc a => Nocc (Dom a) where nocc = foldMap . nocc instance Nocc a => Nocc (Measure a) where nocc = foldMap . nocc instance Nocc a => Nocc (Bound a) where nocc = foldMap . nocc instance (Nocc a, Nocc b) => Nocc (a,b) where nocc ks (a, b) = nocc ks a `andLazy` nocc ks b instance Nocc a => Nocc (Sort a) where nocc ks (Set v) = nocc ks v nocc ks (CoSet v) = nocc ks v nocc ks (SortC _) = mempty instance Nocc Val where nocc ks v = do traceM ( " nocc " + + show v ) v <- whnfClos v case v of VGen k -> return $ not $ k `elem` ks VApp v1 vl -> nocc ks $ v1 : vl VDef{} -> mempty VProj{} -> mempty Still sound . ( Should maybe done first , like in Agda ) . VQuant pisig x dom fv -> nocc ks dom `mappend` do underAbs x dom fv $ \ _i _xv bv -> nocc ks bv fv@(VLam x env b) -> underAbs' x fv $ \ _xv bv -> nocc ks bv fv@(VAbs x i u valu) -> underAbs' x fv $ \ _xv bv -> nocc ks bv fv@(VConst v) -> underAbs' noName fv $ \ _xv bv -> nocc ks bv VRecord _ rs -> nocc ks $ map snd rs VPair v w -> nocc ks (v, w) VZero -> mempty VSucc v -> nocc ks v VInfty -> mempty VMax vl -> nocc ks vl VPlus vl -> nocc ks vl VSort s -> nocc ks s VMeasured mu tv -> nocc ks (mu, tv) VGuard beta tv -> nocc ks (beta, tv) VBelow ltle v -> nocc ks v VSing v tv -> nocc ks (v, tv) VUp v tv -> nocc ks (v, tv) VIrr -> mempty VCase v tv env cls -> nocc ks $ v : tv : map snd (envMap env) VClos{} -> throwErrorMsg $ "internal error: nocc " ++ show (ks,v) eqValBool :: TVal -> Val -> Val -> TypeCheck Bool eqValBool tv v v' = errorToBool $ eqVal tv v v' eqVal :: TVal -> Val -> Val -> TypeCheck () eqVal tv = leqVal' N mixed (Just (One tv)) deriving (Eq,Show) class Switchable a where switch :: a -> a instance Switchable Force where switch L = R switch R = L switch N = N instance Switchable Pol where switch = polNeg instance Switchable (a,a) where switch (a,b) = (b,a) instance Switchable a => Switchable (Maybe a) where switch = fmap switch leqDec : : Pol - > Dec - > Dec - > Bool leqDec SPos dec1 dec2 = erased dec2 || not ( erased dec1 ) leqDec Neg dec1 dec2 = erased dec1 || not ( erased dec2 ) leqDec mixed dec1 dec2 = erased dec1 = = erased dec2 leqDec :: Pol -> Dec -> Dec -> Bool leqDec SPos dec1 dec2 = erased dec2 || not (erased dec1) leqDec Neg dec1 dec2 = erased dec1 || not (erased dec2) leqDec mixed dec1 dec2 = erased dec1 == erased dec2 -} leqDec :: Pol -> Dec -> Dec -> Bool leqDec p dec1 dec2 = erased dec1 == erased dec2 && relPol p leqPol (polarity dec1) (polarity dec2) subtype :: Val -> Val -> TypeCheck () leqVal' N Pos Nothing v1 v2 leqVal :: Pol -> TVal -> Val -> Val -> TypeCheck () leqVal p tv = leqVal' N p (Just (One tv)) type MT12 = Maybe (OneOrTwo TVal) data TypeShape = ShQuant PiSigma (OneOrTwo Name) (OneOrTwo Domain) 1 and singleton 2 and the left is a singleton 2 and the right is a singleton | ShNone deriving (Eq, Ord) data SortShape CoSet i and CoSet j deriving (Eq, Ord) shSize :: TypeShape shSize = ShSort (ShSortC Size) typeView :: TVal -> TypeShape typeView tv = case tv of VQuant pisig x dom fv -> ShQuant pisig (One x) (One dom) (One fv) VBelow{} -> shSize VSort s -> ShSort (sortView s) VSing v tv -> ShSing v tv VApp (VDef (DefId DatK n)) vs -> ShData n (One tv) sortView :: Sort Val -> SortShape sortView s = case s of SortC c -> ShSortC c Set v -> ShSet (One v) CoSet v -> ShCoSet (One v) typeView12 :: (Functor m, Monad m, MonadError TraceError m) => OneOrTwo TVal -> m TypeShape typeView12 : : OneOrTwo TVal - > typeView12 (One tv) = return $ typeView tv typeView12 (Two tv1 tv2) = case (tv1, tv2) of (VQuant pisig1 x1 dom1 fv1, VQuant pisig2 x2 dom2 fv2) | pisig1 == pisig2 && erased (decor dom1) == erased (decor dom2) -> return $ ShQuant pisig1 (Two x1 x2) (Two dom1 dom2) (Two fv1 fv2) (VSort s1, VSort s2) -> ShSort <$> sortView12 (Two s1 s2) (VSing v tv, _) -> return $ ShSingL v tv tv2 (_, VSing v tv) -> return $ ShSingR tv1 v tv _ -> case (typeView tv1, typeView tv2) of (ShSort s1, ShSort s2) | s1 == s2 -> return $ ShSort $ s1 (ShData n1 _, ShData n2 _) | n1 == n2 -> return $ ShData n1 (Two tv1 tv2) (ShNe{} , ShNe{} ) -> return $ ShNe (Two tv1 tv2) _ -> throwErrorMsg $ "type " ++ show tv1 ++ " has different shape than " ++ show tv2 sortView12 :: (Monad m, MonadError TraceError m) => OneOrTwo (Sort Val) -> m SortShape sortView12 (One s) = return $ sortView s sortView12 (Two s1 s2) = case (s1, s2) of (SortC c1, SortC c2) | c1 == c2 -> return $ ShSortC c1 (Set v1, Set v2) -> return $ ShSet (Two v1 v2) (CoSet v1, CoSet v2) -> return $ ShCoSet (Two v1 v2) _ -> throwErrorMsg $ "sort " ++ show s1 ++ " has different shape than " ++ show s2 whnf12 :: OneOrTwo Env -> OneOrTwo Expr -> TypeCheck (OneOrTwo Val) whnf12 env12 e12 = traverse id $ zipWith12 whnf env12 e12 app12 :: OneOrTwo Val -> OneOrTwo Val -> TypeCheck (OneOrTwo Val) app12 fv12 v12 = traverse id $ zipWith12 app fv12 v12 if = Nothing , we are checking subtyping , otherwise we are if two types are given ( heterogeneous equality ) , they need to be leqVal' :: Force -> Pol -> MT12 -> Val -> Val -> TypeCheck () leqVal' f p mt12 u1' u2' = local (\ cxt -> cxt { consistencyCheck = False }) $ do 2013 - 03 - 30 During subtyping , it is fine to add any size hypotheses . l <- getLen ren <- getRen enterDoc (case mt12 of text "leqVal' (subtyping) " <+> prettyTCM u1' <+> text (" <=" ++ show p ++ " ") <+> prettyTCM u2' text "leqVal' " <+> prettyTCM u1' <+> text (" <=" ++ show p ++ " ") <+> prettyTCM u2' <+> colon <+> prettyTCM tv text "leqVal' " <+> prettyTCM u1' <+> colon <+> prettyTCM tv1 <+> text (" <=" ++ show p ++ " ") <+> prettyTCM u2' <+> colon <+> prettyTCM tv2) $ do sh12 <- case mt12f of Nothing -> return Nothing Just tv12 -> case runExcept $ typeView12 tv12 of Right sh -> return $ Just sh Left err -> (recoverFail $ show err) >> return Nothing case sh12 of two terms are equal at singleton type ! Just (ShSingL v1 tv1' tv2) -> leqVal' f p (Just (Two tv1' tv2)) v1 u2' Just (ShSingR tv1 v2 tv2') -> leqVal' f p (Just (Two tv1 tv2')) u1' v2 Just (ShSort (ShSortC Size)) -> leqSize p u1' u2' functions are compared pointwise Gamma , : A ) |- t x : B < = Gamma ' , p'(x : A ' ) |- t ' x : B ' Gamma |- t : : A ) - > B < = Gamma ' |- t ' : p'(x : A ' ) - > B ' Gamma, p(x:A) |- t x : B <= Gamma', p'(x:A') |- t' x : B' Gamma |- t : p(x:A) -> B <= Gamma' |- t' : p'(x:A') -> B' -} Just (ShQuant Pi x12 dom12 fv12) -> do x <- do let x = name12 x12 if null (suggestion x) then do case (u1', u2') of (VLam x _ _, _) -> return x (_, VLam x _ _) -> return x _ -> return x else return x newVar x dom12 $ \ _ xv12 -> do u1' <- app u1' (first12 xv12) u2' <- app u2' (second12 xv12) tv12 <- app12 fv12 xv12 leqVal' f p (Just tv12) u1' u2' Just ( VPi x1 dom1 env1 b1 , VPi x2 dom2 env2 b2 ) - > new2 x1 ( dom1 , dom2 ) $ \ ( xv1 , xv2 ) - > do u1 ' < - app u1 ' xv1 u2 ' < - app u2 ' xv2 ' < - whnf ( update env1 x1 xv1 ) b1 tv2 ' < - whnf ( update env2 x2 xv2 ) b2 leqVal ' f p ( Just ( ' , tv2 ' ) ) u1 ' u2 ' Just (VPi x1 dom1 env1 b1, VPi x2 dom2 env2 b2) -> new2 x1 (dom1, dom2) $ \ (xv1, xv2) -> do u1' <- app u1' xv1 u2' <- app u2' xv2 tv1' <- whnf (update env1 x1 xv1) b1 tv2' <- whnf (update env2 x2 xv2) b2 leqVal' f p (Just (tv1', tv2')) u1' u2' -} _ -> do u1 <- reduce =<< whnfClos u1' u2 <- reduce =<< whnfClos u2' let tryForcing fallback = do (f1,u1f) <- force' False u1 (f2,u2f) <- force' False u2 only unroll one side enter ("forcing LHS") $ leqVal' L p mt12 u1f u2 (False,True) | f /= L -> enter ("forcing RHS") $ leqVal' R p mt12 u1 u2f fallback leqCons n1 vl1 n2 vl2 = do unless (n1 == n2) $ recoverFail $ "leqVal': head mismatch " ++ show u1 ++ " != " ++ show u2 case mt12 of Nothing -> recoverFail $ "leqVal': cannot compare constructor terms without type" Just tv12 -> do ct12 <- mapM (conType n1) tv12 _ <- leqVals' f p ct12 vl1 vl2 return () case (u1,u2) of C = C ' ( proper : C ' entails C , but I do not want to implement entailment ) Gamma , C |- A < = Gamma ' , C ' |- A ' Gamma |- C = = > A < = Gamma ' |- C ' = = > A ' C = C' (proper: C' entails C, but I do not want to implement entailment) Gamma, C |- A <= Gamma', C' |- A' Gamma |- C ==> A <= Gamma' |- C' ==> A' -} (VGuard beta1 bv1, VGuard beta2 bv2) -> do entailsGuard (switch p) beta1 beta2 leqVal' f p Nothing bv1 bv2 (VGuard beta u1, u2) | p `elem` [Neg,Pos] -> addOrCheckGuard (switch p) beta $ leqVal' f p Nothing u1 u2 (u1, VGuard beta u2) | p `elem` [Neg,Pos] -> addOrCheckGuard p beta $ leqVal' f p Nothing u1 u2 p ' < = p Gamma ' |- A ' < = Gamma |- A Gamma , : A ) |- B < = Gamma ' , p'(x : A ' ) |- B ' Gamma |- p(x : A ) - > B : s < = Gamma ' |- p'(x : A ' ) - > B ' : s ' p' <= p Gamma' |- A' <= Gamma |- A Gamma, p(x:A) |- B <= Gamma', p'(x:A') |- B' Gamma |- p(x:A) -> B : s <= Gamma' |- p'(x:A') -> B' : s' -} (VQuant piSig1 x1 dom1@(Domain av1 _ dec1) fv1, VQuant piSig2 x2 dom2@(Domain av2 _ dec2) fv2) -> do let p' = if piSig1 == Pi then switch p else p if piSig1 /= piSig2 || not (leqDec p' dec1 dec2) then recoverFailDoc $ text "subtyping" <+> prettyTCM u1 <+> text (" <=" ++ show p ++ " ") <+> prettyTCM u2 <+> text "failed" else do leqVal' (switch f) p' Nothing av1 av2 let dom = if (p' == Neg) then dom2 else dom1 let x = bestName $ if p' == Neg then [x2,x1] else [x1,x2] new x dom $ \ xv -> do bv1 <- app fv1 xv bv2 <- app fv2 xv enterDoc (text "comparing codomain" <+> prettyTCM bv1 <+> text "with" <+> prettyTCM bv2) $ leqVal' f p Nothing bv1 bv2 (VSing v1 av1, VSing v2 av2) -> do leqVal' f p Nothing av1 av2 (VSing v1 av1, VBelow ltle v2) | av1 == vSize && p == Pos -> do v1 <- whnfClos v1 leSize ltle p v1 v2 2012 - 01 - 28 now vSize is VBelow Le Infty ( u1,u2 ) | isVSize u1 & & isVSize u2 - > return ( ) ( VSort ( SortC Size ) , { } ) - > leqStructural ( VBelow Le VInfty ) u2 ( VBelow { } , VSort ( SortC Size ) ) - > leqStructural u1 ( VBelow Le VInfty ) (u1,u2) | isVSize u1 && isVSize u2 -> return () (VSort (SortC Size), VBelow{}) -> leqStructural (VBelow Le VInfty) u2 (VBelow{}, VSort (SortC Size)) -> leqStructural u1 (VBelow Le VInfty) -} (VBelow ltle1 v1, VBelow ltle2 v2) -> case (p, ltle1, ltle2) of _ | ltle1 == ltle2 -> leSize Le p v1 v2 (Neg, Le, Lt) -> leSize Le p (vSucc v1) v2 (p , Lt, Le) -> leSize Le p v1 (vSucc v2) (VUp v1 av1, VUp v2 av2) -> do OR : ) ? (VUp v1 av1, u2) -> leqVal' f p mt12 v1 u2 (u1, VUp v2 av2) -> leqVal' f p mt12 u1 v2 (VRecord (NamedRec _ n1 _ _) rs1, VRecord (NamedRec _ n2 _ _) rs2) -> leqCons n1 (map snd rs1) n2 (map snd rs2) ( ( NamedRec _ n1 _ ) rs1 , VApp v2@(VDef ( DefId ( ConK _ ) n2 ) ) vl2 ) - > leqCons n1 ( map snd rs1 ) n2 vl2 ( VApp v1@(VDef ( DefId ( ConK _ ) n1 ) ) vl1 , ( NamedRec _ n2 _ ) rs2 ) - > leqCons n1 ( map snd rs2 ) ( VApp v1@(VDef ( DefId ( ConK _ ) n1 ) ) vl1 , VApp v2@(VDef ( DefId ( ConK _ ) n2 ) ) vl2 ) - > leqCons n1 vl1 n2 vl2 (VRecord (NamedRec _ n1 _) rs1, VApp v2@(VDef (DefId (ConK _) n2)) vl2) -> leqCons n1 (map snd rs1) n2 vl2 (VApp v1@(VDef (DefId (ConK _) n1)) vl1, VRecord (NamedRec _ n2 _) rs2) -> leqCons n1 vl1 n2 (map snd rs2) (VApp v1@(VDef (DefId (ConK _) n1)) vl1, VApp v2@(VDef (DefId (ConK _) n2)) vl2) -> leqCons n1 vl1 n2 vl2 -} (VCase v1 tv1 env1 cl1, VCase v2 tv2 env2 cl2) -> do leqClauses f p mt12 v1 tv1 env1 cl1 env2 cl2 REMOVED , NOT TRANSITIVE ( VCase v env cl , v2 ) - > leqCases ( switch f ) ( switch p ) ( switch mt12 ) v2 v env cl ( v1 , v env cl ) - > leqCases f p mt12 v1 v env cl (VCase v env cl, v2) -> leqCases (switch f) (switch p) (switch mt12) v2 v env cl (v1, VCase v env cl) -> leqCases f p mt12 v1 v env cl -} (VSort s1, VSort s2) -> leqSort p s1 s2 (a1,a2) | a1 == a2 -> return () (u1,u2) -> tryForcing $ case (u1,u2) of (VApp v1 vl1, VApp v2 vl2) -> leqApp f p v1 vl1 v2 vl2 (VApp v1 vl1, u2) -> leqApp f p v1 vl1 u2 [] (u1, VApp v2 vl2) -> leqApp f p u1 [] v2 vl2 _ -> leqApp f p u1 [] u2 [] leqClauses :: Force -> Pol -> MT12 -> Val -> TVal -> Env -> [Clause] -> Env -> [Clause] -> TypeCheck () leqClauses f pol mt12 v tvp env1 cls1 env2 cls2 = loop cls1 cls2 where loop cls1 cls2 = case (cls1,cls2) of ([],[]) -> return () (Clause _ [p1] mrhs1 : cls1', Clause _ [p2] mrhs2 : cls2') -> do ns <- flip execStateT [] $ alphaPattern p1 p2 case (mrhs1, mrhs2) of (Nothing, Nothing) -> return () (Just e1, Just e2) -> do let tv = maybe vTopSort first12 mt12 let tv012 = maybe [] toList12 mt12 addPattern (tvp `arrow` tv) p2 env2 $ \ _ pv env2' -> addRewrite (Rewrite v pv) tv012 $ \ tv012 -> do let env1' = env2' { envMap = compAssoc ns (envMap env2') } v1 <- whnf (appendEnv env1' env1) e1 v2 <- whnf (appendEnv env2' env2) e2 leqVal' f pol (toMaybe12 tv012) v1 v2 loop cls1' cls2' : : Force - > Pol - > MT12 - > Val - > TVal - > Env - > [ Clause ] - > Env - > [ Clause ] - > ( ) leqClauses f pol mt12 v tvp env1 cls1 env2 cls2 = loop cls1 cls2 where loop cls1 cls2 = case ( cls1,cls2 ) of ( [ ] , [ ] ) - > return ( ) ( Clause _ [ p1 ] : cls1 ' , Clause _ [ p2 ] mrhs2 : cls2 ' ) - > do eqPattern p1 p2 case ( mrhs1 , mrhs2 ) of ( Nothing , Nothing ) - > return ( ) ( Just e1 , Just e2 ) - > do let tv = maybe vTopSort first12 mt12 let tv012 = maybe [ ] toList12 mt12 addPattern ( tvp ` arrow ` tv ) p1 env1 $ \ _ pv env ' - > addRewrite ( Rewrite v pv ) tv012 $ \ tv012 - > do v1 < - whnf ( appendEnv env ' env1 ) e1 v2 < - whnf ( appendEnv env ' env2 ) e2 leqVal ' f pol ( toMaybe12 tv012 ) v1 v2 loop cls1 ' cls2 ' eqPattern : : Pattern - > Pattern - > TypeCheck ( ) eqPattern p1 p2 = if p1 = = p2 then return ( ) else throwErrorMsg $ " pattern " + + show p1 + + " ! = " + + show p2 leqClauses :: Force -> Pol -> MT12 -> Val -> TVal -> Env -> [Clause] -> Env -> [Clause] -> TypeCheck () leqClauses f pol mt12 v tvp env1 cls1 env2 cls2 = loop cls1 cls2 where loop cls1 cls2 = case (cls1,cls2) of ([],[]) -> return () (Clause _ [p1] mrhs1 : cls1', Clause _ [p2] mrhs2 : cls2') -> do eqPattern p1 p2 case (mrhs1, mrhs2) of (Nothing, Nothing) -> return () (Just e1, Just e2) -> do let tv = maybe vTopSort first12 mt12 let tv012 = maybe [] toList12 mt12 addPattern (tvp `arrow` tv) p1 env1 $ \ _ pv env' -> addRewrite (Rewrite v pv) tv012 $ \ tv012 -> do v1 <- whnf (appendEnv env' env1) e1 v2 <- whnf (appendEnv env' env2) e2 leqVal' f pol (toMaybe12 tv012) v1 v2 loop cls1' cls2' eqPattern :: Pattern -> Pattern -> TypeCheck () eqPattern p1 p2 = if p1 == p2 then return () else throwErrorMsg $ "pattern " ++ show p1 ++ " != " ++ show p2 -} type NameMap = [(Name,Name)] alphaPattern :: Pattern -> Pattern -> StateT NameMap TypeCheck () alphaPattern p1 p2 = do let failure = throwErrorMsg $ "pattern " ++ show p1 ++ " != " ++ show p2 alpha x1 x2 = do ns <- get case lookup x1 ns of Nothing -> put $ (x1,x2) : ns Just x2' | x2 == x2' -> return () | otherwise -> failure case (p1,p2) of (VarP x1, VarP x2) -> alpha x1 x2 (ConP pi1 n1 ps1, ConP pi2 n2 ps2) | pi1 == pi2 && n1 == n2 -> zipWithM_ alphaPattern ps1 ps2 (SuccP p1, SuccP p2) -> alphaPattern p1 p2 (SizeP _ x1, SizeP _ x2) -> alpha x1 x2 (PairP p11 p12, PairP p21 p22) -> do alphaPattern p11 p21 alphaPattern p12 p22 (ProjP n1, ProjP n2) -> unless (n1 == n2) failure (DotP _, DotP _) -> return () (AbsurdP, AbsurdP) -> return () (ErasedP p1, ErasedP p2) -> alphaPattern p1 p2 (UnusableP p1, UnusableP p2) -> alphaPattern p1 p2 _ -> failure leqCases f p env cl checks whether v1 < = p ( VCase v tv env cl ) : leqCases :: Force -> Pol -> MT12 -> Val -> Val -> TVal -> Env -> [Clause] -> TypeCheck () leqCases f pol mt12 v1 v tvp env cl = do vcase <- evalCase v tvp env cl case vcase of (VCase v tvp env cl) -> mapM_ (leqCase f pol mt12 v1 v tvp env) cl v2 -> leqVal' f pol mt12 v1 v2 leqCase :: Force -> Pol -> MT12 -> Val -> Val -> TVal -> Env -> Clause -> TypeCheck () leqCase f pol mt12 v1 v tvp env (Clause _ [p] Nothing) = return () + + " : " + + show mt12 ) $ the dot patterns inside p are only valid in environment env let tv = case mt12 of Nothing -> vTopSort Just tv12 -> second12 tv12 addPattern (tvp `arrow` tv) p env $ \ _ pv env' -> addRewrite (Rewrite v pv) [tv,v1] $ \ [tv',v1'] -> do v2 <- whnf (appendEnv env' env) e 2010 - 09 - 10 , WHY ? let mt12' = fmap (mapSecond12 (const tv')) mt12 leqVal' f pol mt12' v1' v2' compare spines ( see rule Al - App - Ne , , MSCS 08 ) leqVals' :: Force -> Pol -> OneOrTwo TVal -> [Val] -> [Val] -> TypeCheck (OneOrTwo TVal) leqVals' f q tv12 vl1 vl2 = do sh12 <- typeView12 =<< mapM force tv12 case (vl1, vl2, sh12) of ([], [], _) -> return tv12 (VProj Post p1 : vs1, VProj Post p2 : vs2, ShData d _) -> do unless (p1 == p2) $ recoverFailDoc $ text "projections" <+> prettyTCM p1 <+> text "and" <+> prettyTCM p2 <+> text "differ!" tv12 <- mapM (\ tv -> projectType tv p1 VIrr) tv12 leqVals' f q tv12 vs1 vs2 (w1:vs1, w2:vs2, ShQuant Pi x12 dom12 fv12) -> do let p = oneOrTwo id polAnd (fmap (polarity . decor) dom12) v1 <- whnfClos w1 v2 <- whnfClos w2 tv12 <- do we have skipped an argument , so proceed with two types ! then app12 (toTwo fv12) (Two v1 v2) else do let q' = polComp p q applyDec dec $ leqVal' f q' (Just $ fmap typ dom12) v1 v2 we have not skipped comparison , so proceed ( 1/2 ) as we came in case fv12 of Two{} -> app12 fv12 (Two v1 v2) One fv -> One <$> app fv v1 leqVals' f q tv12 vs1 vs2 _ -> failDoc $ text "leqVals': not (compatible) function types or mismatch number of arguments when comparing " <+> prettyTCM vl1 <+> text " to " <+> prettyTCM vl2 <+> text " at type " <+> prettyTCM tv12 _ - > throwErrorMsg $ " leqVals ' : not ( compatible ) function types or mismatch number of arguments when comparing " + + show vl1 + + " to " + + show vl2 + + " at type " + + show leqVals ' f q ( VPi x1 dom1@(Domain av1 _ dec1 ) env1 b1 , VPi x2 dom2@(Domain av2 _ dec2 ) env2 b2 ) ( w1 : vs1 ) ( w2 : ) | dec1 = = dec2 = do let p = polarity dec1 v1 < - whnfClos w1 v2 < - whnfClos w2 when ( not ( erased dec1 ) ) $ applyDec dec1 $ leqVal ' f ( polComp p q ) ( Just ( av1,av2 ) ) v1 v2 < - whnf ( update env1 x1 v1 ) b1 tv2 < - whnf ( update env2 x2 v2 ) b2 leqVals ' f q ( tv1,tv2 ) vs1 vs2 leqVals' f q (VPi x1 dom1@(Domain av1 _ dec1) env1 b1, VPi x2 dom2@(Domain av2 _ dec2) env2 b2) (w1:vs1) (w2:vs2) | dec1 == dec2 = do let p = polarity dec1 v1 <- whnfClos w1 v2 <- whnfClos w2 when (not (erased dec1)) $ applyDec dec1 $ leqVal' f (polComp p q) (Just (av1,av2)) v1 v2 tv1 <- whnf (update env1 x1 v1) b1 tv2 <- whnf (update env2 x2 v2) b2 leqVals' f q (tv1,tv2) vs1 vs2 -} leqApp f pol v1 vs1 v2 vs2 checks v1 vs1 < = pol v2 vs2 leqApp :: Force -> Pol -> Val -> [Val] -> Val -> [Val] -> TypeCheck () do let headMismatch = recoverFail $ " leqApp : head mismatch " + + show v1 + + " ! = " + + show v2 do let headMismatch = recoverFail $ "leqApp: head mismatch " ++ show v1 ++ " != " ++ show v2 -} do let headMismatch = recoverFailDoc $ text "leqApp: head mismatch" <+> prettyTCM v1 <+> text "!=" <+> prettyTCM v2 let emptyOrUnit u1 u2 = unlessM (isEmptyType u1) $ unlessM (isUnitType u2) $ headMismatch case (v1,v2) of IMPOSSIBLE : ( VApp v1 [ ] , v2 ) - > leqApp f pol v1 w1 v2 w2 ( v1 , VApp v2 [ ] ) - > leqApp f pol v1 w1 v2 w2 (VApp v1 [], v2) -> leqApp f pol v1 w1 v2 w2 (v1, VApp v2 []) -> leqApp f pol v1 w1 v2 w2 -} ( VApp { } , _ ) - > throwErrorMsg $ " leqApp : internal error : hit application v1 = " + + show v1 ( _ , VApp { } ) - > throwErrorMsg $ " leqApp : internal error : hit application v2 = " + + show v2 (VApp{}, _) -> throwErrorMsg $ "leqApp: internal error: hit application v1 = " ++ show v1 (_, VApp{}) -> throwErrorMsg $ "leqApp: internal error: hit application v2 = " ++ show v2 -} (VUp v1 _, v2) -> leqApp f pol v1 w1 v2 w2 (v1, VUp v2 _) -> leqApp f pol v1 w1 v2 w2 (VGen k1, VGen k2) | k1 == k2 -> do tv12 <- (fmap typ . domain) <$> lookupGen k1 _ <- leqVals' f pol tv12 w1 w2 return () ( VGen k1 , VGen k2 ) - > if k1 /= k2 then headMismatch else do ( fmap typ . domain ) < $ > lookupGen k1 leqVals ' f pol tv12 w1 w2 return ( ) (VGen k1, VGen k2) -> if k1 /= k2 then headMismatch else do tv12 <- (fmap typ . domain) <$> lookupGen k1 leqVals' f pol tv12 w1 w2 return () -} ( _ n , _ m ) - > if n /= m then throwErrorMsg $ " leqApp : head mismatch " + + show v1 + + " ! = " + + show v2 else do sige < - lookupSymb n case sige of leqVals ' f tv ( repeat mixed ) w1 w2 > > return ( ) (VCon _ n, VCon _ m) -> if n /= m then throwErrorMsg $ "leqApp: head mismatch " ++ show v1 ++ " != " ++ show v2 else do sige <- lookupSymb n case sige of leqVals' f tv (repeat mixed) w1 w2 >> return () -} (VDef n, VDef m) | n == m -> do tv <- lookupSymbTypQ (idName n) _ <- leqVals' f pol (One tv) w1 w2 return () (u1,u2) -> if pol == Pos then emptyOrUnit u1 u2 else if pol == Neg then emptyOrUnit u2 u1 else headMismatch ( VDef ( DefId DatK n ) , v2 ) | pol = = Pos - > ifM ( isEmptyData n ) ( return ( ) ) headMismatch ( v1 , VDef ( DefId DatK n ) ) | pol = = Neg - > ifM ( isEmptyData n ) ( return ( ) ) headMismatch (VDef (DefId DatK n), v2) | pol == Pos -> ifM (isEmptyData n) (return ()) headMismatch (v1, VDef (DefId DatK n)) | pol == Neg -> ifM (isEmptyData n) (return ()) headMismatch -} ( VDef n , VDef m ) - > if ( name n ) /= ( name m ) then do bot < - if pol==Neg then isEmptyData $ name m else if pol==Pos then isEmptyData $ name n else return False if bot then return ( ) else headMismatch else do tv < - lookupSymbTyp ( name n ) leqVals ' f pol ( One tv ) w1 w2 return ( ) (VDef n, VDef m) -> if (name n) /= (name m) then do bot <- if pol==Neg then isEmptyData $ name m else if pol==Pos then isEmptyData $ name n else return False if bot then return () else headMismatch else do tv <- lookupSymbTyp (name n) leqVals' f pol (One tv) w1 w2 return () -} sig < - gets signature case lookupSig ( name n ) sig of let positivitySizeIndex = if s /= Sized then mixed else if co = = Ind then Pos else Neg in leqVals ' f tv pos ' w1 w2 > > return ( ) entry - > leqVals ' f ( symbTyp entry ) ( repeat mixed ) w1 w2 > > return ( ) sig <- gets signature case lookupSig (name n) sig of let positivitySizeIndex = if s /= Sized then mixed else if co == Ind then Pos else Neg in leqVals' f tv pos' w1 w2 >> return () entry -> leqVals' f (symbTyp entry) (repeat mixed) w1 w2 >> return () -} isEmptyType :: TVal -> TypeCheck Bool isEmptyType (VDef (DefId DatK n)) = isEmptyData n isEmptyType _ = return False isUnitType :: TVal -> TypeCheck Bool isUnitType (VDef (DefId DatK n)) = isUnitData n isUnitType _ = return False leqSort :: Pol -> Sort Val -> Sort Val -> TypeCheck () leqSort p = relPolM p leqSort' leqSort' :: Sort Val -> Sort Val -> TypeCheck () leqSort' s1 s2 = do let err = text "universe test" <+> prettyTCM s1 <+> text "<=" <+> prettyTCM s2 <+> text "failed" case (s1,s2) of (_ , Set VInfty) -> return () (SortC c , SortC c') | c == c' -> return () (Set v1 , Set v2) -> leqSize Pos v1 v2 (CoSet VInfty , Set v) -> return () (Set VZero , CoSet{}) -> return () (CoSet v1 , CoSet v2) -> leqSize Neg v1 v2 _ -> recoverFailDoc err minSize :: Val -> Val -> Maybe Val minSize v1 v2 = case (v1,v2) of (VZero,_) -> return VZero (_,VZero) -> return VZero (VInfty,_) -> return v2 (_,VInfty) -> return v1 (VMax vs,_) -> maxMins $ map (\ v -> minSize v v2) vs (_,VMax vs) -> maxMins $ map (\ v -> minSize v1 v) vs (VSucc v1', VSucc v2') -> fmap succSize $ minSize v1' v2' (VGen i, VGen j) -> if i == j then return $ VGen i else Nothing (VSucc v1', VGen j) -> minSize v1' v2 (VGen i, VSucc v2') -> minSize v1 v2' maxMins :: [Maybe Val] -> Maybe Val maxMins mvs = case compressMaybes mvs of [] -> Nothing vs' -> return $ maxSize vs' leqSize :: Pol -> Val -> Val -> TypeCheck () leqSize = leSize Le ltSize :: Val -> Val -> TypeCheck () ltSize = leSize Lt Pos leSize :: LtLe -> Pol -> Val -> Val -> TypeCheck () leSize ltle pol v1 v2 = enterDoc (text "leSize" <+> prettyTCM v1 <+> text (show ltle ++ show pol) <+> prettyTCM v2) $ enter ( " leSize " + + show v1 + + " " + + show + + show pol + + " " + + show v2 ) $ traceSize ("leSize " ++ show v1 ++ " " ++ show ltle ++ show pol ++ " " ++ show v2) $ do case (v1,v2) of (VSucc v1,VSucc v2) -> leSize ltle pol v1 v2 (VInfty,VInfty) | ltle == Le -> return () | otherwise -> recoverFail "leSize: # < # failed" (VApp h1 tl1,VApp h2 tl2) -> leqApp N pol h1 tl1 h2 tl2 _ -> relPolM pol (leSize' ltle) v1 v2 leqSize' :: Val -> Val -> TypeCheck () leqSize' = leSize' Le leSize' :: LtLe -> Val -> Val -> TypeCheck () enter ( " leSize ' " + + show v1 + + " " + + show + + " " + + show v2 ) $ enterDoc (text "leSize'" <+> prettyTCM v1 <+> text (show ltle) <+> prettyTCM v2) $ traceSize ("leSize' " ++ show v1 ++ " " ++ show ltle ++ " " ++ show v2) $ do let failure = recoverFailDoc $ text "leSize':" <+> prettyTCM v1 <+> text (show ltle) <+> prettyTCM v2 <+> text "failed" err = " leSize ' : " + + show v1 + + " " + + show + + " " + + show v2 + + " failed " case (v1,v2) of (VZero,_) | ltle == Le -> return () (VSucc{}, VZero) -> failure (VInfty, VZero) -> failure (VGen{}, VZero) -> failure (_,VInfty) | ltle == Le -> return () (VZero, VInfty) -> return () (VMeta{},VZero) -> addLe ltle v1 v2 ( 0,VMeta i n ' , j m ' ) - > let ( n , m ) = if < = 0 then ( n ' , m ' - bal ) else ( n ' + bal , m ' ) in (0,VMeta i n', VMeta j m') -> let (n,m) = if bal <= 0 then (n', m' - bal) else (n' + bal, m') in -} (VMeta i rho n, VMeta j rho' m) -> addLe ltle (VMeta i rho (n - min n m)) (VMeta j rho' (m - min n m)) (VMeta i rho n, VSucc v2) | n > 0 -> leSize' ltle (VMeta i rho (n-1)) v2 (VMeta i rho n, v2) -> addLe ltle v1 v2 (VSucc v1, VMeta i rho n) | n > 0 -> leSize' ltle v1 (VMeta i rho (n-1)) (v1,VMeta i rho n) -> addLe ltle v1 v2 _ -> leSize'' ltle 0 v1 v2 HANDLED BY leSize '' ( VSucc { } , { } ) - > throwErrorMsg err ( VSucc { } , VPlus { } ) - > throwErrorMsg err (VSucc{}, VGen{}) -> throwErrorMsg err (VSucc{}, VPlus{}) -> throwErrorMsg err -} leSize '' v v ' checks whether Succ^bal v ` lt ` v ' invariant : bal is zero in cases for VMax and leSize'' :: LtLe -> Int -> Val -> Val -> TypeCheck () leSize'' ltle bal v1 v2 = traceSize ("leSize'' " ++ show v1 ++ " + " ++ show bal ++ " " ++ show ltle ++ " " ++ show v2) $ do let failure = recoverFailDoc (text "leSize'':" <+> prettyTCM v1 <+> text ("+ " ++ show bal) <+> text (show ltle) <+> prettyTCM v2 <+> text "failed") check mb = ifM mb (return ()) failure ltlez = case ltle of { Le -> 0 ; Lt -> -1 } case (v1,v2) of #ifdef STRICTINFTY _ | v1 == v2 && ltle == Le && bal <= 0 -> return () (VGen i, VGen j) | i == j && bal <= -1 -> check $ isBelowInfty i #else #endif (VGen i, VInfty) | ltle == Lt -> check $ isBelowInfty i (VZero,_) | bal <= ltlez -> return () (VZero,VInfty) -> return () (VZero,VGen _) | bal > ltlez -> recoverFailDoc $ text "0 not <" <+> prettyTCM v2 (VSucc v1, v2) -> leSize'' ltle (bal + 1) v1 v2 (v1, VSucc v2) -> leSize'' ltle (bal - 1) v1 v2 (VPlus vs1, VPlus vs2) -> leSizePlus ltle bal vs1 vs2 (VPlus vs1, VZero) -> leSizePlus ltle bal vs1 [] (VZero, VPlus vs2) -> leSizePlus ltle bal [] vs2 (VPlus vs1, _) -> leSizePlus ltle bal vs1 [v2] (_, VPlus vs2) -> leSizePlus ltle bal [v1] vs2 (VZero,_) -> leSizePlus ltle bal [] [v2] (_,VZero) -> leSizePlus ltle bal [v1] [] _ -> leSizePlus ltle bal [v1] [v2] #if (defined STRICTINFTY) 2012 - 02 - 06 this modification cancels only variables < # However , omega - instantiation is valid [ i < # ] - > F i subseteq F # because every chain has a limit at # . However, omega-instantiation is valid [i < #] -> F i subseteq F # because every chain has a limit at #. -} leSizePlus :: LtLe -> Int -> [Val] -> [Val] -> TypeCheck () leSizePlus Lt bal vs1 vs2 = do vs2' <- filterM varBelowInfty vs2 vs1' <- filterM varBelowInfty vs1 leSizePlus' Lt bal (vs1 List.\\ vs2') (vs2 List.\\ vs1') leSizePlus Le bal vs1 vs2 = leSizePlus' Le bal (vs1 List.\\ vs2) (vs2 List.\\ vs1) #else leSizePlus :: LtLe -> Int -> [Val] -> [Val] -> TypeCheck () leSizePlus ltle bal vs1 vs2 = leSizePlus' ltle bal (vs1 List.\\ vs2) (vs2 List.\\ vs1) #endif varBelowInfty :: Val -> TypeCheck Bool varBelowInfty (VGen i) = isBelowInfty i varBelowInfty _ = return False leSizePlus' :: LtLe -> Int -> [Val] -> [Val] -> TypeCheck () leSizePlus' ltle bal vs1 vs2 = do let v1 = plusSizes vs1 let v2 = plusSizes vs2 let exit True = return () exit False | bal >= 0 = recoverFailDoc (text "leSize:" <+> prettyTCM v1 <+> text ("+ " ++ show bal ++ " " ++ show ltle) <+> prettyTCM v2 <+> text "failed") | otherwise = recoverFailDoc (text "leSize:" <+> prettyTCM v1 <+> text (show ltle) <+> prettyTCM v2 <+> text ("+ " ++ show (-bal) ++ " failed")) traceSizeM ("leSizePlus' ltle " ++ show v1 ++ " + " ++ show bal ++ " " ++ show ltle ++ " " ++ show v2) let ltlez = case ltle of { Le -> 0 ; Lt -> -1 } case (vs1,vs2) of ([],_) | bal <= ltlez -> return () ([],[VGen i]) -> do n <- getMinSize i case n of height of i = = 0 Just n -> exit (bal <= n + ltlez) ([VGen i1],[VGen i2]) -> do d <- sizeVarBelow i1 i2 traceSizeM ("sizeVarBelow " ++ show (i1,i2) ++ " returns " ++ show d) case d of Nothing -> tryIrregularBound i1 i2 (ltlez - bal) recoverFail $ " leSize : head mismatch : " + + show v1 + + " " + + show + + " " + + show v2 Just k -> exit (bal <= k + ltlez) _ -> exit False tryIrregularBound :: Int -> Int -> Int -> TypeCheck () tryIrregularBound i1 i2 k = do betas <- asks bounds let beta = Bound Le (Measure [VGen i1]) (Measure [iterate VSucc (VGen i2) !! k]) foldl (\ result beta' -> result `orM` entailsGuard Pos beta' beta) (recoverFail "bound not entailed") betas leqSize ' : : Val - > Val - > ( ) do case ( v1,v2 ) of ( VSucc v1,VSucc v2 ) - > leqSize ' v1 v2 ( VGen v1,VGen v2 ) - > do d < - getSizeDiff v1 v2 case d of Nothing - > throwErrorMsg $ " leqSize : head mismatch : " + + show v1 + + " ! < = " + + show v2 Just k - > if k > = 0 then return ( ) else throwErrorMsg $ " leqSize : " + + show v1 + + " ! < = " + + show v2 + + " failed " ( _ , VInfty ) - > return ( ) ( VMeta i n , VSucc v2 ) | n > 0 - > leqSize ' ( i ( n-1 ) ) v2 ( i n , j m ) - > addLeq ( i ( n - min n m ) ) ( j ( m - min n m ) ) ( i n , v2 ) - > addLeq v1 v2 ( VSucc v1 , i n ) | n > 0 - > leqSize ' v1 ( i ( n-1 ) ) ( v1,VMeta i n ) - > addLeq v1 v2 ( v1,VSucc v2 ) - > leqSize ' v1 v2 _ - > throwErrorMsg $ " leqSize : " + + show v1 + + " ! < = " + + show v2 leqSize' :: Val -> Val -> TypeCheck () do case (v1,v2) of (VSucc v1,VSucc v2) -> leqSize' v1 v2 (VGen v1,VGen v2) -> do d <- getSizeDiff v1 v2 case d of Nothing -> throwErrorMsg $ "leqSize: head mismatch: " ++ show v1 ++ " !<= " ++ show v2 Just k -> if k >= 0 then return () else throwErrorMsg $ "leqSize: " ++ show v1 ++ " !<= " ++ show v2 ++ " failed" (_,VInfty) -> return () (VMeta i n, VSucc v2) | n > 0 -> leqSize' (VMeta i (n-1)) v2 (VMeta i n, VMeta j m) -> addLeq (VMeta i (n - min n m)) (VMeta j (m - min n m)) (VMeta i n, v2) -> addLeq v1 v2 (VSucc v1, VMeta i n) | n > 0 -> leqSize' v1 (VMeta i (n-1)) (v1,VMeta i n) -> addLeq v1 v2 (v1,VSucc v2) -> leqSize' v1 v2 _ -> throwErrorMsg $ "leqSize: " ++ show v1 ++ " !<= " ++ show v2 -} ltMeasure : : Measure Val - > Measure Val - > ( ) ltMeasure ( Measure mu1 ) ( Measure mu2 ) = lexSizes Lt mu1 mu2 ltMeasure :: Measure Val -> Measure Val -> TypeCheck () ltMeasure (Measure mu1) (Measure mu2) = lexSizes Lt mu1 mu2 -} leqMeasure : : Pol - > Measure Val - > Measure Val - > ( ) leqMeasure mixed ( Measure mu1 ) ( Measure mu2 ) = do zipWithM ( leqSize mixed ) mu1 mu2 return ( ) leqMeasure Pos ( Measure mu1 ) ( Measure mu2 ) = lexSizes mu1 mu2 leqMeasure Neg ( Measure mu1 ) ( Measure mu2 ) = lexSizes mu2 mu1 leqMeasure :: Pol -> Measure Val -> Measure Val -> TypeCheck () leqMeasure mixed (Measure mu1) (Measure mu2) = do zipWithM (leqSize mixed) mu1 mu2 return () leqMeasure Pos (Measure mu1) (Measure mu2) = lexSizes mu1 mu2 leqMeasure Neg (Measure mu1) (Measure mu2) = lexSizes mu2 mu1 -} lexSizes :: LtLe -> [Val] -> [Val] -> TypeCheck () lexSizes ltle mu1 mu2 = traceSize ("lexSizes " ++ show (ltle,mu1,mu2)) $ case (ltle, mu1, mu2) of (Lt, [], []) -> recoverFail $ "lexSizes: no descent detected" (Le, [], []) -> return () (lt, a1:mu1, a2:mu2) -> do b <- newAssertionHandling Failure $ errorToBool $ leSize ltle Pos a1 a2 case (lt,b) of (Le,False) -> recoverFailDoc $ text "lexSizes: expected" <+> prettyTCM a1 <+> text "<=" <+> prettyTCM a2 (Lt,True) -> return () _ -> lexSizes ltle mu1 mu2 r < - compareSize a1 a2 case r of LT - > return ( ) EQ - > lexSizes ltle mu1 mu2 GT - > recoverFail $ " lexSizes : expected " + + show a1 + + " < = " + + show a2 r <- compareSize a1 a2 case r of LT -> return () EQ -> lexSizes ltle mu1 mu2 GT -> recoverFail $ "lexSizes: expected " ++ show a1 ++ " <= " ++ show a2 -} compareSize : : Val - > Val - > compareSize a1 a2 = do let ret o = trace ( " compareSize : " + + show a1 + + " compared to " + + show a2 + + " returns " + + show o ) $ return o le < - newAssertionHandling Failure $ errorToBool $ leqSize Pos a1 a2 ge < - newAssertionHandling Failure $ errorToBool $ leqSize Pos a2 a1 case ( le , ge ) of ( True , True ) - > ret EQ ( False , True ) - > ret GT ( False , False ) - > throwErrorMsg $ " compareSize ( " + + show a1 + + " , " + + show a2 + + " ): sizes incomparable " compareSize :: Val -> Val -> TypeCheck Ordering compareSize a1 a2 = do let ret o = trace ("compareSize: " ++ show a1 ++ " compared to " ++ show a2 ++ " returns " ++ show o) $ return o le <- newAssertionHandling Failure $ errorToBool $ leqSize Pos a1 a2 ge <- newAssertionHandling Failure $ errorToBool $ leqSize Pos a2 a1 case (le,ge) of (True,True) -> ret EQ (False,True) -> ret GT (False,False) -> throwErrorMsg $ "compareSize (" ++ show a1 ++ ", " ++ show a2 ++ "): sizes incomparable" -} Bound entailment 1 . ( mu1 < mu1 ' ) = = > ( mu2 < mu2 ' ) if mu2 < = mu1 and mu1 ' < = mu2 ' 2 . ( mu1 < = mu1 ' ) = = > ( mu2 < mu2 ' ) one of these < = strict ( < ) 3 . ( mu1 < mu1 ' ) = = > ( mu2 < = mu2 ' ) as 1 . 4 . ( mu1 < = mu1 ' ) = = > ( mu2 < = mu2 ' ) as 1 . 1. (mu1 < mu1') ==> (mu2 < mu2') if mu2 <= mu1 and mu1' <= mu2' 2. (mu1 <= mu1') ==> (mu2 < mu2') one of these <= strict (<) 3. (mu1 < mu1') ==> (mu2 <= mu2') as 1. 4. (mu1 <= mu1') ==> (mu2 <= mu2') as 1. -} entailsGuard :: Pol -> Bound Val -> Bound Val -> TypeCheck () entailsGuard pol beta1@(Bound ltle1 (Measure mu1) (Measure mu1')) beta2@(Bound ltle2 (Measure mu2) (Measure mu2')) = enterDoc (text ("entailsGuard:") <+> prettyTCM beta1 <+> text (show pol ++ "==>") <+> prettyTCM beta2) $ do case pol of _ | pol == mixed -> do assert (ltle1 == ltle2) $ "unequal bound types" zipWithM_ (leqSize mixed) mu1 mu2 zipWithM_ (leqSize mixed) mu1' mu2' return () Pos | ltle1 == Lt || ltle2 == Le -> do lexSizes Le mu1' mu2' return () Pos -> do (lexSizes Lt mu2 mu1 >> lexSizes Le mu1' mu2') `orM` (lexSizes Le mu2 mu1 >> lexSizes Lt mu1' mu2') Neg -> entailsGuard (switch pol) beta2 beta1 eqGuard : : Bound Val - > Bound Val - > ( ) eqGuard ( Bound ( Measure mu1 ) ( Measure mu1 ' ) ) ( Bound ( Measure mu2 ) ( Measure mu2 ' ) ) = do zipWithM ( leqSize mixed ) mu1 mu2 zipWithM ( leqSize mixed ) mu1 ' mu2 ' return ( ) eqGuard :: Bound Val -> Bound Val -> TypeCheck () eqGuard (Bound (Measure mu1) (Measure mu1')) (Bound (Measure mu2) (Measure mu2')) = do zipWithM (leqSize mixed) mu1 mu2 zipWithM (leqSize mixed) mu1' mu2' return () -} checkGuard :: Bound Val -> TypeCheck () checkGuard beta@(Bound ltle mu mu') = enterDoc (text "checkGuard" <+> prettyTCM beta) $ lexSizes ltle (measure mu) (measure mu') addOrCheckGuard :: Pol -> Bound Val -> TypeCheck a -> TypeCheck a addOrCheckGuard Neg beta cont = checkGuard beta >> cont addOrCheckGuard Pos beta cont = addBoundHyp beta cont leqPolM :: Pol -> PProd -> TypeCheck () leqPolM p (PProd Pol.Const _) = return () leqPolM p (PProd q m) | Map.null m && not (isPVar p) = if leqPol p q then return () else recoverFail $ "polarity check " ++ show p ++ " <= " ++ show q ++ " failed" leqPolM p q = do traceM $ "adding polarity constraint " ++ show p ++ " <= " ++ show q leqPolPoly :: Pol -> PPoly -> TypeCheck () leqPolPoly p (PPoly l) = mapM_ (leqPolM p) l addPosEdge :: DefId -> DefId -> PProd -> TypeCheck () addPosEdge src tgt p = unless (src == tgt && isSPos p) $ do st <- get put $ st { positivityGraph = Arc (Rigid src) (ppoly p) (Rigid tgt) : positivityGraph st } checkPositivityGraph :: TypeCheck () checkPositivityGraph = enter ("checking positivity") $ do st <- get let cs = positivityGraph st let gr = buildGraph cs let n = nextNode gr let m0 = mkMatrix n (graph gr) let m = warshall m0 let isDataId i = case Map.lookup i (intMap gr) of Just (Rigid (DefId DatK _)) -> True _ -> False let dataDiag = [ m Array.! (i,i) | i <- [0..n-1], isDataId i ] mapM_ (\ x -> leqPolPoly oone x) dataDiag let solvable = all ( \ x - > leqPol oone x ) unless solvable $ recoverFail $ " positivity check failed " let solvable = all (\ x -> leqPol oone x) unless solvable $ recoverFail $ "positivity check failed" -} put $ st { positivityGraph = [] } telView :: TVal -> TypeCheck ([(Val, TBinding TVal)], TVal) telView tv = do case tv of VQuant Pi x dom fv -> underAbs_ x dom fv $ \ _ xv bv -> do (vTel, core) <- telView bv return ((xv, TBind x dom) : vTel, core) _ -> return ([], tv) mkConVal :: Dotted -> ConK -> QName -> [Val] -> TVal -> TypeCheck Val mkConVal dotted co n vs vc = do (vTel, _) <- telView vc let fieldNames = map (boundName . snd) vTel return $ VRecord (NamedRec co n False dotted) $ zip fieldNames vs
1f55cea580568826416d966d75c976fac64916b978e664e278b1ab9f4e393a66
v-kolesnikov/sicp
1_11_test.clj
(ns sicp.chapter01.1-11-test (:require [clojure.test :refer :all] [sicp.test-helper :refer :all] [sicp.chapter01.1-11 :refer :all])) (deftest test-f-recursive (assert-equal 1 (f-recursive 1)) (assert-equal 2 (f-recursive 2)) (assert-equal 3 (f-recursive 3)) (assert-equal 6 (f-recursive 4)) (assert-equal 101902 (f-recursive 20))) (deftest test-f-iterative (assert-equal 1 (f-iteraive 1)) (assert-equal 2 (f-iteraive 2)) (assert-equal 3 (f-iteraive 3)) (assert-equal 6 (f-iteraive 4)) (assert-equal 101902 (f-iteraive 20)))
null
https://raw.githubusercontent.com/v-kolesnikov/sicp/4298de6083440a75898e97aad658025a8cecb631/test/sicp/chapter01/1_11_test.clj
clojure
(ns sicp.chapter01.1-11-test (:require [clojure.test :refer :all] [sicp.test-helper :refer :all] [sicp.chapter01.1-11 :refer :all])) (deftest test-f-recursive (assert-equal 1 (f-recursive 1)) (assert-equal 2 (f-recursive 2)) (assert-equal 3 (f-recursive 3)) (assert-equal 6 (f-recursive 4)) (assert-equal 101902 (f-recursive 20))) (deftest test-f-iterative (assert-equal 1 (f-iteraive 1)) (assert-equal 2 (f-iteraive 2)) (assert-equal 3 (f-iteraive 3)) (assert-equal 6 (f-iteraive 4)) (assert-equal 101902 (f-iteraive 20)))
b829a661547b1068764997a6505e4aa3963459c53d5f10fb7164cdfbfa7fc621
rcherrueau/APE
web08.rkt
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; Web Applications in Racket ;; -lang.org/continue/ ;; 8 . Extending the Model ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; #lang web-server/insta ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Blog Structure ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;; ;; Posts ;;;;;;;;;;;;;;;;;;;;; ; Blog post data-structure ; A blog post is title, a body (content) and a list of comments. (struct post(title body comments) #:mutable) ; post-add-comment! : post comment -> void ; Consumes a post and a comment, adds the comment at the end of the post. (define (post-add-comment! post comment) (set-post-comments! (append (post-comments post) (list comment)))) ;;;;;;;;;;;;;;;;;;;;; ;; Blog ;;;;;;;;;;;;;;;;;;;;; A blog is a ( blog posts ) where posts is a ( listof post ) ; Mutable structure provide mutators to change their fields. So blog struct provide function set - blog - posts ! : blog ( post ) - > void ; to set the posts value (struct blog (posts) #:mutable) ; blog-insert-post!: blog post -> void ; Consumes a blog and a post, adds the pot at the top of the blog. (define (blog-insert-post! a-blog a-post) (set-blog-posts! a-blog (cons a-post (blog-posts a-blog)))) ; BLOG: blog ; The initial BLOG. (define BLOG (blog (list (post "Second Post" "This is another post" (list "Comment1" "Comment2")) (post "First Post" "This is my first post" (list "Comment1" "Comment2"))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; Blog Bindings & Params ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; can-parse-post?: bindings -> boolean ; Test if bindings for a blog post are provided ; When creating a blog post, the list of comment is obviously empty ; so there is no test on comments argument. (define (can-parse-post? bindings) (and (exists-binding? 'title bindings) (> (string-length (extract-binding/single 'title bindings)) 0) (exists-binding? 'body bindings) (> (string-length (extract-binding/single 'body bindings)) 0))) ; parse-post: bindings -> post ; Consumes a bindings and produce a blog post out of the bindings ; When you create a blog-post, list of comments is obviously empty. (define (parse-post bindings) (post (extract-binding/single 'title bindings) (extract-binding/single 'body bindings) (list))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Blog Render Function ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; render-comment: comment -> xexpr Consumes a post comment and produce an xexpr fragment (define (render-comment comment) `(div ((class "comment")) (p ,comment))) render - comments : ( listof comment ) - > xexpr Consume a list of post comment and produce an xexpr fragment (define (render-comments comments) render - as - itemized - list : ( ) - > xexpr ; Consumes a list of items, and produces a rendering ; as an unordered list. (define (render-as-itemized-list fragments) `(ul ,@(map render-as-item fragments))) render - as - item : xexpr - > xexpr ; Consumes an xexpr, and produces a rendering ; as a list item. (define (render-as-item a-fragment) `(li ,a-fragment)) `(div ((class "comments")) ,(render-as-itemized-list (map render-comment comments)))) ; render-post: post -> xexpr Consumes a blog post and produce an xexpr fragment (define (render-post post) `(div ((class "post")) ,(post-title post) (p ,(post-body post)) ,(render-comments (post-comments post)))) render - posts : ( listof post ) - > xexpr Consume a list of post and produce an xexpr fragment (define (render-posts posts) render - as - itemized - list : ( ) - > xexpr ; Consumes a list of items, and produces a rendering ; as an unordered list. (define (render-as-itemized-list fragments) `(ul ,@(map render-as-item fragments))) render - as - item : xexpr - > xexpr ; Consumes an xexpr, and produces a rendering ; as a list item. (define (render-as-item a-fragment) `(li ,a-fragment)) `(div ((class "posts")) ,(render-as-itemized-list (map render-post posts)))) ; render-blog-page: blog request -> doesn't return ; Consumes a blog request and produces an HTML page of the content of the blog (define (render-blog-page a-blog request) (local [(define (response-generator embed/url) (response/xexpr `(html (head (title "My Blog")) (body (h1 "My Blog") ,(render-posts (blog-posts a-blog)) (form ((action ,(embed/url insert-post-handler))) (input ((name "title"))) (input ((name "body"))) (input ((type "submit")))))))) (define (insert-post-handler request) ((let ([bindings (request-bindings request)]) (cond [(can-parse-post? bindings) (blog-insert-post! a-blog (parse-post bindings))])) (render-blog-page a-blog request)))] (send/suspend/dispatch response-generator))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Entry Point ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; start: request -> response ; Consumes a requets and produces a page that displays all the web content (define (start request) (render-blog-page BLOG request))
null
https://raw.githubusercontent.com/rcherrueau/APE/8b5302709000bd043b64d46d55642acb34ce5ba7/racket/webAppInRacket/web08.rkt
racket
-lang.org/continue/ Blog Structure Posts Blog post data-structure A blog post is title, a body (content) and a list of comments. post-add-comment! : post comment -> void Consumes a post and a comment, adds the comment at the end of the post. Blog Mutable structure provide mutators to change their fields. to set the posts value blog-insert-post!: blog post -> void Consumes a blog and a post, adds the pot at the top of the blog. BLOG: blog The initial BLOG. can-parse-post?: bindings -> boolean Test if bindings for a blog post are provided When creating a blog post, the list of comment is obviously empty so there is no test on comments argument. parse-post: bindings -> post Consumes a bindings and produce a blog post out of the bindings When you create a blog-post, list of comments is obviously empty. Blog Render Function render-comment: comment -> xexpr Consumes a list of items, and produces a rendering as an unordered list. Consumes an xexpr, and produces a rendering as a list item. render-post: post -> xexpr Consumes a list of items, and produces a rendering as an unordered list. Consumes an xexpr, and produces a rendering as a list item. render-blog-page: blog request -> doesn't return Consumes a blog request and produces an HTML page of the content of the blog Entry Point start: request -> response Consumes a requets and produces a page that displays all the web content
Web Applications in Racket 8 . Extending the Model #lang web-server/insta (struct post(title body comments) #:mutable) (define (post-add-comment! post comment) (set-post-comments! (append (post-comments post) (list comment)))) A blog is a ( blog posts ) where posts is a ( listof post ) So blog struct provide function set - blog - posts ! : blog ( post ) - > void (struct blog (posts) #:mutable) (define (blog-insert-post! a-blog a-post) (set-blog-posts! a-blog (cons a-post (blog-posts a-blog)))) (define BLOG (blog (list (post "Second Post" "This is another post" (list "Comment1" "Comment2")) (post "First Post" "This is my first post" (list "Comment1" "Comment2"))))) Blog Bindings & Params (define (can-parse-post? bindings) (and (exists-binding? 'title bindings) (> (string-length (extract-binding/single 'title bindings)) 0) (exists-binding? 'body bindings) (> (string-length (extract-binding/single 'body bindings)) 0))) (define (parse-post bindings) (post (extract-binding/single 'title bindings) (extract-binding/single 'body bindings) (list))) Consumes a post comment and produce an xexpr fragment (define (render-comment comment) `(div ((class "comment")) (p ,comment))) render - comments : ( listof comment ) - > xexpr Consume a list of post comment and produce an xexpr fragment (define (render-comments comments) render - as - itemized - list : ( ) - > xexpr (define (render-as-itemized-list fragments) `(ul ,@(map render-as-item fragments))) render - as - item : xexpr - > xexpr (define (render-as-item a-fragment) `(li ,a-fragment)) `(div ((class "comments")) ,(render-as-itemized-list (map render-comment comments)))) Consumes a blog post and produce an xexpr fragment (define (render-post post) `(div ((class "post")) ,(post-title post) (p ,(post-body post)) ,(render-comments (post-comments post)))) render - posts : ( listof post ) - > xexpr Consume a list of post and produce an xexpr fragment (define (render-posts posts) render - as - itemized - list : ( ) - > xexpr (define (render-as-itemized-list fragments) `(ul ,@(map render-as-item fragments))) render - as - item : xexpr - > xexpr (define (render-as-item a-fragment) `(li ,a-fragment)) `(div ((class "posts")) ,(render-as-itemized-list (map render-post posts)))) (define (render-blog-page a-blog request) (local [(define (response-generator embed/url) (response/xexpr `(html (head (title "My Blog")) (body (h1 "My Blog") ,(render-posts (blog-posts a-blog)) (form ((action ,(embed/url insert-post-handler))) (input ((name "title"))) (input ((name "body"))) (input ((type "submit")))))))) (define (insert-post-handler request) ((let ([bindings (request-bindings request)]) (cond [(can-parse-post? bindings) (blog-insert-post! a-blog (parse-post bindings))])) (render-blog-page a-blog request)))] (send/suspend/dispatch response-generator))) (define (start request) (render-blog-page BLOG request))
2da7207458fda04e9153fb7e9dfe0a55069044509a01b7378e013f752e0e42c2
abcdw/rde
fonts.scm
;;; rde --- Reproducible development environment. ;;; Copyright © 2022 < > ;;; ;;; This file is part of rde. ;;; ;;; rde is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation ; either version 3 of the License , or ( at ;;; your option) any later version. ;;; ;;; rde is distributed in the hope that it will be useful, but ;;; WITHOUT ANY WARRANTY; without even the implied warranty of ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;;; GNU General Public License for more details. ;;; You should have received a copy of the GNU General Public License ;;; along with rde. If not, see </>. (define-module (rde packages fonts) #:use-module (guix build-system trivial) #:use-module (guix build-system font) #:use-module (guix download) #:use-module (guix gexp) #:use-module (guix git-download) #:use-module ((guix licenses) #:prefix license:) #:use-module (guix packages) #:use-module (guix utils)) (define-public font-noto-color-emoji (package (name "font-noto-color-emoji") (version "2.034") (source (origin (method git-fetch) (uri (git-reference (url "-emoji") (commit (string-append "v" version)))) (file-name (git-file-name name version)) (sha256 (base32 "1d6zzk0ii43iqfnjbldwp8sasyx99lbjp1nfgqjla7ixld6yp98l")))) (build-system trivial-build-system) (arguments (list #:modules `((guix build utils)) #:builder #~(begin (use-modules (guix build utils)) (let* ((out #$output) (font-dir (string-append out "/share/fonts")) (truetype-dir (string-append font-dir "/truetype"))) (chdir (assoc-ref %build-inputs "source")) (install-file "fonts/NotoColorEmoji.ttf" truetype-dir))))) (home-page "-emoji") (synopsis "Noto Color Emoji fonts") (description "Noto Color Emoji fonts.") (license license:silofl1.1))) (define-public font-noto-emoji (package (name "font-noto-emoji") (version "0.1") (source (origin (method url-fetch/zipbomb) Everytime zip archive is downloaded from fonts.google.com it have a ;; different hash, so I mirrored it. (uri "") (sha256 (base32 "14y936dw1l6h2v7ygfwyzjf0bg5f8ii42s34n1xaf7sczv3g15cv")))) (build-system font-build-system) (home-page "+Emoji") (synopsis "Noto Emoji fonts") (description "Monochrome version of Noto Color Emoji fonts.") (license license:silofl1.1)))
null
https://raw.githubusercontent.com/abcdw/rde/5b8605f421d0b8a9569e43cb6f7e651e7a8f7218/src/rde/packages/fonts.scm
scheme
rde --- Reproducible development environment. This file is part of rde. rde is free software; you can redistribute it and/or modify it either version 3 of the License , or ( at your option) any later version. rde is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. along with rde. If not, see </>. different hash, so I mirrored it.
Copyright © 2022 < > under the terms of the GNU General Public License as published by You should have received a copy of the GNU General Public License (define-module (rde packages fonts) #:use-module (guix build-system trivial) #:use-module (guix build-system font) #:use-module (guix download) #:use-module (guix gexp) #:use-module (guix git-download) #:use-module ((guix licenses) #:prefix license:) #:use-module (guix packages) #:use-module (guix utils)) (define-public font-noto-color-emoji (package (name "font-noto-color-emoji") (version "2.034") (source (origin (method git-fetch) (uri (git-reference (url "-emoji") (commit (string-append "v" version)))) (file-name (git-file-name name version)) (sha256 (base32 "1d6zzk0ii43iqfnjbldwp8sasyx99lbjp1nfgqjla7ixld6yp98l")))) (build-system trivial-build-system) (arguments (list #:modules `((guix build utils)) #:builder #~(begin (use-modules (guix build utils)) (let* ((out #$output) (font-dir (string-append out "/share/fonts")) (truetype-dir (string-append font-dir "/truetype"))) (chdir (assoc-ref %build-inputs "source")) (install-file "fonts/NotoColorEmoji.ttf" truetype-dir))))) (home-page "-emoji") (synopsis "Noto Color Emoji fonts") (description "Noto Color Emoji fonts.") (license license:silofl1.1))) (define-public font-noto-emoji (package (name "font-noto-emoji") (version "0.1") (source (origin (method url-fetch/zipbomb) Everytime zip archive is downloaded from fonts.google.com it have a (uri "") (sha256 (base32 "14y936dw1l6h2v7ygfwyzjf0bg5f8ii42s34n1xaf7sczv3g15cv")))) (build-system font-build-system) (home-page "+Emoji") (synopsis "Noto Emoji fonts") (description "Monochrome version of Noto Color Emoji fonts.") (license license:silofl1.1)))
8cf32f589a3b272ac3d3e6dd1a74192476c9e65587313b879a548e5ee1be0b75
ftovagliari/ocamleditor
project_xml.ml
OCamlEditor Copyright ( C ) 2010 - 2014 This file is part of OCamlEditor . OCamlEditor is free software : you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation , either version 3 of the License , or ( at your option ) any later version . OCamlEditor is distributed in the hope that it will be useful , but WITHOUT ANY WARRANTY ; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the GNU General Public License for more details . You should have received a copy of the GNU General Public License along with this program . If not , see < / > . OCamlEditor Copyright (C) 2010-2014 Francesco Tovagliari This file is part of OCamlEditor. OCamlEditor is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. OCamlEditor is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see </>. *) open Project open Printf open Miscellanea open Oe (** write *) let write proj = let open Prj in Xml.Element ("project", [], [ Xml.Element ("ocaml_home", [], [Xml.PCData proj.ocaml_home]); Xml.Element ("ocamllib", [], [Xml.PCData (if proj.ocamllib_from_env then proj.ocamllib else "")]); Xml.Element ("encoding", [], [Xml.PCData (match proj.encoding with None -> "" | Some x -> x)]); Xml.Element ("name", [], [Xml.PCData proj.name]); Xml.Element ("author", [], [Xml.PCData proj.author]); (*Xml.Element ("description", [], [Xml.PCData proj.description]);*) Xml.Element ("description", [], (List.map (fun x -> Xml.Element ("line", [], [Xml.PCData x])) (Miscellanea.split "\n" proj.description))); Xml.Element ("version", [], [Xml.PCData proj.version]); Xml.Element ("autocomp", [ "enabled", string_of_bool proj.autocomp_enabled; "delay", string_of_float proj.autocomp_delay; "cflags", proj.autocomp_cflags], []); Xml.Element ("targets", [], List.map begin fun t -> Xml.Element ("target", [ "name", t.Target.name; "default", string_of_bool t.Target.default; "id", string_of_int t.Target.id; "sub_targets", (String.concat "," (List.map (fun tg -> string_of_int tg.Target.id) t.Target.sub_targets)); "is_fl_package", string_of_bool t.Target.is_fl_package; "subsystem", (match t.Target.subsystem with Some x -> Target.string_of_subsystem x | _ -> ""); "readonly", string_of_bool t.Target.readonly; "visible", string_of_bool t.Target.visible; "node_collapsed", string_of_bool t.Target.node_collapsed; ], [ Xml.Element ("descr", [], [Xml.PCData (t.Target.descr)]); Xml.Element ("byt", [], [Xml.PCData (string_of_bool t.Target.byt)]); Xml.Element ("opt", [], [Xml.PCData (string_of_bool t.Target.opt)]); Xml.Element ("libs", [], [Xml.PCData t.Target.libs]); Xml.Element ("other_objects", [], [Xml.PCData t.Target.other_objects]); Xml.Element ("files", [], [Xml.PCData t.Target.files]); Xml.Element ("package", [], [Xml.PCData t.Target.package]); Xml.Element ("includes", [], [Xml.PCData t.Target.includes]); Xml.Element ("thread", [], [Xml.PCData (string_of_bool t.Target.thread)]); Xml.Element ("vmthread", [], [Xml.PCData (string_of_bool t.Target.vmthread)]); Xml.Element ("pp", [], [Xml.PCData t.Target.pp]); Xml.Element ("inline", [], [Xml.PCData (match t.Target.inline with Some num -> string_of_int num | _ -> "")]); Xml.Element ("nodep", [], [Xml.PCData (string_of_bool t.Target.nodep)]); Xml.Element ("dontlinkdep", [], [Xml.PCData (string_of_bool t.Target.dontlinkdep)]); Xml.Element ("dontaddopt", [], [Xml.PCData (string_of_bool t.Target.dontaddopt)]); Xml.Element ("cflags", [], [Xml.PCData t.Target.cflags]); Xml.Element ("lflags", [], [Xml.PCData t.Target.lflags]); Xml.Element ("target_type", [], [Xml.PCData (Target.string_of_target_type t.Target.target_type)]); Xml.Element ("outname", [], [Xml.PCData t.Target.outname]); Xml.Element ("lib_install_path", [], [Xml.PCData t.Target.lib_install_path]); Xml.Element ("external_tasks", [], List.map begin fun task -> Xml.Element ("task", ["name", task.Task.et_name], [ Xml.Element ("always_run_in_project", [], [Xml.PCData (string_of_bool task.Task.et_always_run_in_project)]); Xml.Element ("always_run_in_script", [], [Xml.PCData (string_of_bool task.Task.et_always_run_in_script)]); Xml.Element ("readonly", [], [Xml.PCData (string_of_bool task.Task.et_readonly)]); Xml.Element ("visible", [], [Xml.PCData (string_of_bool task.Task.et_visible)]); Xml.Element ("env", ["replace", string_of_bool task.Task.et_env_replace], List.map (fun (e, v) -> Xml.Element ("var", ["enabled", string_of_bool e], [Xml.PCData v])) task.Task.et_env); Xml.Element ("dir", [], [Xml.PCData (task.Task.et_dir)]); Xml.Element ("cmd", [], [Xml.PCData (task.Task.et_cmd)]); Xml.Element ("args", [], List.map (fun (e, v) -> Xml.Element ("arg", ["enabled", string_of_bool e], [Xml.PCData v])) task.Task.et_args); Xml.Element ("phase", [], [Xml.PCData (match task.Task.et_phase with Some x -> Task.string_of_phase x | _ -> "")]); ]) end t.Target.external_tasks); Xml.Element ("restrictions", [], [Xml.PCData (String.concat "&" t.Target.restrictions)]); Xml.Element ("dependencies", [], [Xml.PCData (String.concat "," (List.map string_of_int t.Target.dependencies))]); ] @ (match t.Target.resource_file with | None -> [] | Some rc -> [ Xml.Element ("resource_file", [], let open Resource_file in [ Xml.Element ("filename", [], [Xml.PCData rc.rc_filename]); Xml.Element ("title", [], [Xml.PCData rc.rc_title]); Xml.Element ("company", [], [Xml.PCData rc.rc_company]); Xml.Element ("product", [], [Xml.PCData rc.rc_product]); Xml.Element ("copyright", [], [Xml.PCData rc.rc_copyright]); Xml.Element ("file_version", [], [Xml.PCData (match rc.rc_file_version with a,b,c,d -> sprintf "%d.%d.%d.%d" a b c d)]); Xml.Element ("icons", [], List.map (fun (fn(*, _*)) -> Xml.Element ("icon", [], [Xml.PCData fn])) rc.rc_icons(*_data*)); ])]) ) end proj.targets); Xml.Element ("executables", [], List.map begin fun t -> Xml.Element ("executable", [ "name", t.Rconf.name; "default", string_of_bool t.Rconf.default; "target_id", string_of_int t.Rconf.target_id; "id", string_of_int t.Rconf.id], [ Xml.Element ("build_task", [], [Xml.PCData (Target.string_of_task t.Rconf.build_task)]); Xml.Element ("env", ["replace", string_of_bool t.Rconf.env_replace], List.map (fun (e, v) -> Xml.Element ("var", ["enabled", string_of_bool e], [Xml.PCData v])) t.Rconf.env ); Xml.Element ("args", [], List.map (fun (e, v) -> Xml.Element ("arg", ["enabled", string_of_bool e], [Xml.PCData v])) t.Rconf.args); ]) end proj.executables); Xml.Element ("build_script", ["filename", proj.build_script.Build_script.bs_filename], let targets = List.map begin fun target -> Xml.Element ("target", [ "target_id", (string_of_int target.Build_script.bst_target.Target.id); "show", (string_of_bool target.Build_script.bst_show); ], []) end proj.build_script.Build_script.bs_targets in let args = List.map begin fun arg -> Xml.Element ("arg", [ "id", (string_of_int arg.Build_script_args.bsa_id); "type", (Build_script_args.string_of_type arg.Build_script_args.bsa_type); "key", arg.Build_script_args.bsa_key; "pass", (Build_script_args.string_of_pass arg.Build_script_args.bsa_pass); "command", (Build_script_command.string_of_command arg.Build_script_args.bsa_cmd); ], [ Xml.Element ("task", (match arg.Build_script_args.bsa_task with Some (bc, et) -> [ "target_id", string_of_int bc.Target.id; "task_name", et.Task.et_name; ] | None -> []), []); Xml.Element ("mode", [], [Xml.PCData (match arg.Build_script_args.bsa_mode with `add -> Build_script_args.string_of_add | `replace x -> x)]); Xml.Element ("default", [ "type", (match arg.Build_script_args.bsa_default with `flag _ -> "flag" | `bool _ -> "bool" | `string _ -> "string"); "override", (string_of_bool arg.Build_script_args.bsa_default_override); ], [Xml.PCData (match arg.Build_script_args.bsa_default with `flag x -> string_of_bool x | `bool x -> string_of_bool x | `string x -> x)]); Xml.Element ("doc", [], [Xml.PCData arg.Build_script_args.bsa_doc]); ]) end proj.build_script.Build_script.bs_args in let commands = List.map begin fun cmd -> Xml.Element ("command", [ "name", (Build_script.string_of_command cmd.Build_script.bsc_name); "descr", cmd.Build_script.bsc_descr; "target_id", string_of_int cmd.Build_script.bsc_target.Target.id; "task_name", (cmd.Build_script.bsc_task.Task.et_name); ], []) end proj.build_script.Build_script.bs_commands in [ Xml.Element ("targets", [], targets); Xml.Element ("args", [], args); Xml.Element ("commands", [], commands); ]) ]);; let value xml = try String.concat "\n" (List.map Xml.pcdata (Xml.children xml)) with Xml.Not_element _ -> "";; let fold node tag f init = Xml.fold begin fun acc node -> if Xml.tag node = tag then f node else acc end init node;; let attrib node name f default = match List_opt.assoc name (Xml.attribs node) with Some v -> f v | _ -> default;; let fattrib node name f default = match List_opt.assoc name (Xml.attribs node) with Some v -> f v | _ -> (default ());; (** xml_bs_targets *) let xml_bs_targets proj node = let open Prj in List.rev (Xml.fold begin fun acc target_node -> try {Build_script. bst_target = (match fattrib target_node "target_id" (find_target_string proj) (fun _ -> None) with Some x -> x | _ -> raise Exit); bst_show = fattrib target_node "show" bool_of_string (fun () -> true); } :: acc with Exit -> acc end [] node);; (** xml_bs_args *) let xml_bs_args proj node = let open Prj in let count_bsa_id = ref 0 in Xml.map begin fun arg -> let bsa_doc = ref "" in let bsa_mode = ref `add in let bsa_default_override = ref true in let bsa_default = ref (`flag false) in let bsa_task = ref (None, None) in Xml.iter begin fun tp -> match Xml.tag tp with | "doc" -> bsa_doc := value tp | "mode" -> bsa_mode := begin match value tp with | x when x = Build_script_args.string_of_add -> `add | x -> `replace x end | "default" -> bsa_default_override := attrib tp "override" bool_of_string !bsa_default_override; bsa_default := begin match fattrib tp "type" (fun x -> x) (fun () -> "string") with | "flag" -> `flag (bool_of_string (value tp)) | "bool" -> `bool (bool_of_string (value tp)) | "string" -> `string (value tp) | _ -> !bsa_default end | "task" -> bsa_task := begin let target = fattrib tp "target_id" (find_target_string proj) (fun _ -> None) in let task = fattrib tp "task_name" (find_task proj) (fun _ -> None) in target, task end | _ -> () end arg; {Build_script_args. bsa_id = fattrib arg "id" int_of_string (fun () -> incr count_bsa_id; !count_bsa_id); bsa_type = fattrib arg "type" Build_script_args.type_of_string (fun _ -> Build_script_args.String); bsa_key = attrib arg "key" (fun x -> x) ""; bsa_doc = !bsa_doc; bsa_mode = !bsa_mode; bsa_default_override = !bsa_default_override; bsa_default = !bsa_default; bsa_task = begin match !bsa_task with | Some bc, Some et -> Some (bc, et) | _ -> None end; bsa_pass = fattrib arg "pass" Build_script_args.pass_of_string (fun _ -> `key_value); bsa_cmd = fattrib arg "command" Build_script_command.command_of_string (fun _ -> `Show); } end node;; (** xml_commands *) let xml_commands proj node = let open Prj in List.rev (Xml.fold begin fun acc target_node -> try {Build_script. bsc_name = (fattrib target_node "name" Build_script.command_of_string (fun _ -> raise Exit)); bsc_descr = (attrib target_node "descr" (fun x -> x) ""); bsc_target = (match fattrib target_node "target_id" (find_target_string proj) (fun _ -> None) with Some x -> x | _ -> raise Exit); bsc_task = fattrib target_node "task_name" (fun y -> match find_task proj y with Some x -> x | _ -> raise Exit) (fun _ -> raise Exit) } :: acc with Exit -> acc end [] node);; (** read *) let read filename = let open Prj in let proj = create ~filename () in let parser = XmlParser.make () in let xml = XmlParser.parse parser (XmlParser.SFile filename) in let get_offset xml = try int_of_string (Xml.attrib xml "offset") with Xml.No_attribute _ -> 0 in let get_active xml = try bool_of_string (Xml.attrib xml "active") with Xml.No_attribute _ -> false in let task_map = ref [] in Xml.iter begin fun node -> match Xml.tag node with | "ocaml_home" -> proj.ocaml_home <- value node | "ocamllib" -> proj.ocamllib <- value node | "encoding" -> proj.encoding <- (match value node with "" -> None | x -> Some x) | "name" -> proj.name <- value node | "author" -> proj.author <- value node | "description" -> proj.description <- String.concat "\n" (Xml.map value node) | "version" -> proj.version <- value node | "autocomp" -> proj.autocomp_enabled <- (attrib node "enabled" bool_of_string true); proj.autocomp_delay <- (float_of_string (Xml.attrib node "delay")); proj.autocomp_cflags <- (Xml.attrib node "cflags"); backward compatibility with 1.7.2 let files = Xml.fold (fun acc x -> ((value x), 0, (get_offset x), (get_active x)) :: acc) [] node in proj.open_files <- List.rev files; | "executables" | "runtime" (* Backward compatibility with 1.7.5 *) -> let runtime = Xml.fold begin fun acc tnode -> let config = { Rconf.id = (attrib tnode "id" int_of_string 0); target_id = (try (attrib tnode "target_id" int_of_string 0) with Xml.No_attribute _ -> attrib tnode "id_build" int_of_string 0); (* Backward compatibility with 1.7.5 *) name = (attrib tnode "name" (fun x -> x) ""); default = (attrib tnode "default" bool_of_string false); build_task = `NONE; env = []; env_replace = false; args = [] } in Xml.iter begin fun tp -> match Xml.tag tp with Backward compatibility with 1.7.0 Backward compatibility with 1.7.0 Backward compatibility with 1.7.0 Backward compatibility with 1.7.0 | "build_task" -> config.Rconf.build_task <- `NONE; task_map := (config, (value tp)) :: !task_map | "env" -> config.Rconf.env <- List.rev (Xml.fold (fun acc var -> (attrib var "enabled" bool_of_string true, value var) :: acc) [] tp); config.Rconf.env_replace <- (try bool_of_string (Xml.attrib tp "replace") with Xml.No_attribute _ -> false) | "args" -> begin try config.Rconf.args <- List.rev (Xml.fold (fun acc arg -> (attrib arg "enabled" bool_of_string true, value arg) :: acc) [] tp); with Xml.Not_element _ -> (config.Rconf.args <- [true, (value tp)]) end; | _ -> () end tnode; config :: acc end [] node in proj.executables <- List.rev runtime; | "targets" | "build" (* Backward compatibility with 1.7.5 *) -> let i = ref 0 in let sub_targets = ref [] in let open Target in let targets = Xml.fold begin fun acc tnode -> let target = Target.create ~id:0 ~name:(sprintf "Config_%d" !i) in let runtime_build_task = ref "" in let runtime_env = ref (false, "") in let runtime_args = ref (false, "") in let create_default_runtime = ref false in target.id <- attrib tnode "id" int_of_string 0; target.Target.name <- attrib tnode "name" (fun x -> x) ""; target.default <- attrib tnode "default" bool_of_string false; sub_targets := (target.id, List.map int_of_string (attrib tnode "sub_targets" (Str.split (Str.regexp "[;, ]+")) [])) :: !sub_targets; target.is_fl_package <- attrib tnode "is_fl_package" bool_of_string false; target.subsystem <- (try attrib tnode "subsystem" (fun x -> Some (Target.subsystem_of_string x)) None with Failure _ -> None); target.readonly <- attrib tnode "readonly" bool_of_string false; target.visible <- attrib tnode "visible" bool_of_string true; target.node_collapsed <- attrib tnode "node_collapsed" bool_of_string false; Xml.iter begin fun tp -> match Xml.tag tp with | "descr" -> target.descr <- value tp Backward compatibility with 1.7.0 Backward compatibility with 1.7.0 Backward compatibility with 1.7.0 | "byt" -> target.byt <- bool_of_string (value tp) | "opt" -> target.opt <- bool_of_string (value tp) | "libs" -> target.libs <- value tp | "other_objects" -> target.other_objects <- value tp | "mods" -> target.other_objects <- value tp (* *) | "files" -> target.Target.files <- value tp | "package" -> target.package <- value tp | "includes" -> target.includes <- value tp | "thread" -> target.thread <- bool_of_string (value tp) | "vmthread" -> target.vmthread <- bool_of_string (value tp) | "pp" -> target.pp <- value tp | "inline" -> target.inline <- (let x = value tp in if x = "" then None else Some (int_of_string x)) | "nodep" -> target.nodep <- bool_of_string (value tp) | "dontlinkdep" -> target.dontlinkdep <- bool_of_string (value tp) | "dontaddopt" -> target.dontaddopt <- bool_of_string (value tp) | "cflags" -> target.cflags <- value tp | "lflags" -> target.lflags <- value tp | "is_library" -> target.target_type <- (if bool_of_string (value tp) then Target.Library else Target.Executable) | "target_type" | "outkind" -> target.target_type <- target_type_of_string (value tp) | "outname" -> target.outname <- value tp | "runtime_build_task" -> runtime_build_task := (value tp); create_default_runtime := true; | "runtime_env" | "env" -> runtime_env := (attrib tp "enabed" bool_of_string true, value tp); | "runtime_args" | "run" -> runtime_args := (attrib tp "enabed" bool_of_string true, value tp); | "lib_install_path" -> target.lib_install_path <- value tp | "resource_file" -> let rc = Resource_file.create () in Xml.iter begin fun nrc -> let open Resource_file in match Xml.tag nrc with | "filename" -> target.resource_file <- Some rc; rc.rc_filename <- value nrc | "title" -> rc.rc_title <- value nrc | "company" -> rc.rc_company <- value nrc | "product" -> rc.rc_product <- value nrc | "file_version" -> rc.rc_file_version <- (match Str.split (!~ "\\.") (value nrc) with | [a;b;c;d] -> int_of_string a, int_of_string b, int_of_string c, int_of_string d | _ -> assert false) | "copyright" -> rc.rc_copyright <- value nrc | "icons" -> , Buffer.create 1000 | _ -> () end tp; | "external_tasks" -> let external_tasks = Xml.fold begin fun acc tnode -> let task = Task.create ~name:"" ~env:[] ~dir:"" ~cmd:"" ~args:[] () in task.Task.et_name <- attrib tnode "name" (fun x -> x) ""; Xml.iter begin fun tp -> match Xml.tag tp with Backward compatibility with 1.7.0 Backward compatibility with 1.7.0 | "always_run_in_project" -> task.Task.et_always_run_in_project <- bool_of_string (value tp) | "always_run_in_script" -> task.Task.et_always_run_in_script <- bool_of_string (value tp) | "readonly" -> task.Task.et_readonly <- bool_of_string (value tp) | "visible" -> task.Task.et_visible <- bool_of_string (value tp) | "env" -> task.Task.et_env <- List.rev (Xml.fold (fun acc var -> (attrib var "enabled" bool_of_string true, value var) :: acc) [] tp); task.Task.et_env_replace <- (try bool_of_string (Xml.attrib tp "replace") with Xml.No_attribute _ -> false) | "dir" -> task.Task.et_dir <- value tp | "cmd" -> task.Task.et_cmd <- value tp | "args" -> task.Task.et_args <- List.rev (Xml.fold (fun acc arg -> (attrib arg "enabled" bool_of_string true, value arg) :: acc) [] tp); | "phase" -> task.Task.et_phase <- (match value tp with "" -> None | x -> Some (Task.phase_of_string x)) | _ -> () end tnode; task :: acc end [] tp in target.external_tasks <- List.rev external_tasks; | "restrictions" -> target.restrictions <- (Str.split (!~ "&") (value tp)) | "dependencies" -> target.dependencies <- (List.map int_of_string (Str.split (!~ ",") (value tp))) | _ -> () end tnode; incr i; target ! runtime_build_task ; if !create_default_runtime && target.target_type = Target.Executable then begin proj.executables <- { Rconf.id = (List.length proj.executables); target_id = target.id; name = target.Target.name; default = target.default; build_task = Target.task_of_string target !runtime_build_task; env = [!runtime_env]; env_replace = false; args = [!runtime_args] } :: proj.executables; end; target :: acc; end [] node in proj.targets <- List.rev targets; List.iter begin fun tg -> tg.sub_targets <- let ids = try List.assoc tg.id !sub_targets with Not_found -> [] in List.map (fun id -> try List.find (fun t -> t.id = id) proj.targets with Not_found -> assert false) ids end proj.targets | "build_script" -> let filename = (attrib node "filename" (fun x -> x) "") in proj.build_script <- {Build_script. bs_filename = filename; bs_targets = fold node "targets" (xml_bs_targets proj) []; bs_args = fold node "args" (xml_bs_args proj) []; bs_commands = fold node "commands" (xml_commands proj) []; } | _ -> () end xml; (* Patch build tasks connected to the runtime *) List.iter (fun (rconf, task_string) -> set_runtime_build_task proj rconf task_string) !task_map; (* Set default runtime configuration *) begin match List_opt.find (fun x -> x.Rconf.default) proj.executables with | None -> (match proj.executables with pr :: _ -> pr.Rconf.default <- true | _ -> ()); | _ -> () end; Translate ocamllib : " " - > ' ocamlc -where ' set_ocaml_home ~ocamllib:proj.ocamllib proj; (* *) proj;; (** from_local_xml *) let from_local_xml proj = let open Prj in let filename = Project.filename_local proj in let filename = if Sys.file_exists filename then filename else Project.mk_old_filename_local proj in if Sys.file_exists filename then begin let parser = XmlParser.make () in let xml = XmlParser.parse parser (XmlParser.SFile filename) in let value xml = try String.concat "\n" (List.map Xml.pcdata (Xml.children xml)) with Xml.Not_element _ -> "" in let get_int name xml = try int_of_string (Xml.attrib xml name) with Xml.No_attribute _ -> 0 in let get_cursor xml = try int_of_string (Xml.attrib xml "cursor") with Xml.No_attribute _ -> 0 in let get_active xml = try bool_of_string (Xml.attrib xml "active") with Xml.No_attribute _ -> false in Xml.iter begin fun node -> match Xml.tag node with | "open_files" -> let files = Xml.fold (fun acc x -> ((value x), (get_int "scroll" x), (get_cursor x), (get_active x)) :: acc) [] node in proj.open_files <- List.rev files; | "bookmarks" -> Xml.iter begin fun xml -> let bm = { bm_filename = (value xml); bm_loc = Offset (get_int "offset" xml); bm_num = (get_int "num" xml); bm_marker = None; } in Project.set_bookmark bm proj end node; | _ -> () end xml; end;; let init () = Project.write_xml := write; Project.read_xml := read; Project.from_local_xml := from_local_xml;
null
https://raw.githubusercontent.com/ftovagliari/ocamleditor/53284253cf7603b96051e7425e85a731f09abcd1/src/project_xml.ml
ocaml
* write Xml.Element ("description", [], [Xml.PCData proj.description]); , _ _data * xml_bs_targets * xml_bs_args * xml_commands * read Backward compatibility with 1.7.5 Backward compatibility with 1.7.5 Backward compatibility with 1.7.5 Patch build tasks connected to the runtime Set default runtime configuration * from_local_xml
OCamlEditor Copyright ( C ) 2010 - 2014 This file is part of OCamlEditor . OCamlEditor is free software : you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation , either version 3 of the License , or ( at your option ) any later version . OCamlEditor is distributed in the hope that it will be useful , but WITHOUT ANY WARRANTY ; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the GNU General Public License for more details . You should have received a copy of the GNU General Public License along with this program . If not , see < / > . OCamlEditor Copyright (C) 2010-2014 Francesco Tovagliari This file is part of OCamlEditor. OCamlEditor is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. OCamlEditor is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see </>. *) open Project open Printf open Miscellanea open Oe let write proj = let open Prj in Xml.Element ("project", [], [ Xml.Element ("ocaml_home", [], [Xml.PCData proj.ocaml_home]); Xml.Element ("ocamllib", [], [Xml.PCData (if proj.ocamllib_from_env then proj.ocamllib else "")]); Xml.Element ("encoding", [], [Xml.PCData (match proj.encoding with None -> "" | Some x -> x)]); Xml.Element ("name", [], [Xml.PCData proj.name]); Xml.Element ("author", [], [Xml.PCData proj.author]); Xml.Element ("description", [], (List.map (fun x -> Xml.Element ("line", [], [Xml.PCData x])) (Miscellanea.split "\n" proj.description))); Xml.Element ("version", [], [Xml.PCData proj.version]); Xml.Element ("autocomp", [ "enabled", string_of_bool proj.autocomp_enabled; "delay", string_of_float proj.autocomp_delay; "cflags", proj.autocomp_cflags], []); Xml.Element ("targets", [], List.map begin fun t -> Xml.Element ("target", [ "name", t.Target.name; "default", string_of_bool t.Target.default; "id", string_of_int t.Target.id; "sub_targets", (String.concat "," (List.map (fun tg -> string_of_int tg.Target.id) t.Target.sub_targets)); "is_fl_package", string_of_bool t.Target.is_fl_package; "subsystem", (match t.Target.subsystem with Some x -> Target.string_of_subsystem x | _ -> ""); "readonly", string_of_bool t.Target.readonly; "visible", string_of_bool t.Target.visible; "node_collapsed", string_of_bool t.Target.node_collapsed; ], [ Xml.Element ("descr", [], [Xml.PCData (t.Target.descr)]); Xml.Element ("byt", [], [Xml.PCData (string_of_bool t.Target.byt)]); Xml.Element ("opt", [], [Xml.PCData (string_of_bool t.Target.opt)]); Xml.Element ("libs", [], [Xml.PCData t.Target.libs]); Xml.Element ("other_objects", [], [Xml.PCData t.Target.other_objects]); Xml.Element ("files", [], [Xml.PCData t.Target.files]); Xml.Element ("package", [], [Xml.PCData t.Target.package]); Xml.Element ("includes", [], [Xml.PCData t.Target.includes]); Xml.Element ("thread", [], [Xml.PCData (string_of_bool t.Target.thread)]); Xml.Element ("vmthread", [], [Xml.PCData (string_of_bool t.Target.vmthread)]); Xml.Element ("pp", [], [Xml.PCData t.Target.pp]); Xml.Element ("inline", [], [Xml.PCData (match t.Target.inline with Some num -> string_of_int num | _ -> "")]); Xml.Element ("nodep", [], [Xml.PCData (string_of_bool t.Target.nodep)]); Xml.Element ("dontlinkdep", [], [Xml.PCData (string_of_bool t.Target.dontlinkdep)]); Xml.Element ("dontaddopt", [], [Xml.PCData (string_of_bool t.Target.dontaddopt)]); Xml.Element ("cflags", [], [Xml.PCData t.Target.cflags]); Xml.Element ("lflags", [], [Xml.PCData t.Target.lflags]); Xml.Element ("target_type", [], [Xml.PCData (Target.string_of_target_type t.Target.target_type)]); Xml.Element ("outname", [], [Xml.PCData t.Target.outname]); Xml.Element ("lib_install_path", [], [Xml.PCData t.Target.lib_install_path]); Xml.Element ("external_tasks", [], List.map begin fun task -> Xml.Element ("task", ["name", task.Task.et_name], [ Xml.Element ("always_run_in_project", [], [Xml.PCData (string_of_bool task.Task.et_always_run_in_project)]); Xml.Element ("always_run_in_script", [], [Xml.PCData (string_of_bool task.Task.et_always_run_in_script)]); Xml.Element ("readonly", [], [Xml.PCData (string_of_bool task.Task.et_readonly)]); Xml.Element ("visible", [], [Xml.PCData (string_of_bool task.Task.et_visible)]); Xml.Element ("env", ["replace", string_of_bool task.Task.et_env_replace], List.map (fun (e, v) -> Xml.Element ("var", ["enabled", string_of_bool e], [Xml.PCData v])) task.Task.et_env); Xml.Element ("dir", [], [Xml.PCData (task.Task.et_dir)]); Xml.Element ("cmd", [], [Xml.PCData (task.Task.et_cmd)]); Xml.Element ("args", [], List.map (fun (e, v) -> Xml.Element ("arg", ["enabled", string_of_bool e], [Xml.PCData v])) task.Task.et_args); Xml.Element ("phase", [], [Xml.PCData (match task.Task.et_phase with Some x -> Task.string_of_phase x | _ -> "")]); ]) end t.Target.external_tasks); Xml.Element ("restrictions", [], [Xml.PCData (String.concat "&" t.Target.restrictions)]); Xml.Element ("dependencies", [], [Xml.PCData (String.concat "," (List.map string_of_int t.Target.dependencies))]); ] @ (match t.Target.resource_file with | None -> [] | Some rc -> [ Xml.Element ("resource_file", [], let open Resource_file in [ Xml.Element ("filename", [], [Xml.PCData rc.rc_filename]); Xml.Element ("title", [], [Xml.PCData rc.rc_title]); Xml.Element ("company", [], [Xml.PCData rc.rc_company]); Xml.Element ("product", [], [Xml.PCData rc.rc_product]); Xml.Element ("copyright", [], [Xml.PCData rc.rc_copyright]); Xml.Element ("file_version", [], [Xml.PCData (match rc.rc_file_version with a,b,c,d -> sprintf "%d.%d.%d.%d" a b c d)]); ])]) ) end proj.targets); Xml.Element ("executables", [], List.map begin fun t -> Xml.Element ("executable", [ "name", t.Rconf.name; "default", string_of_bool t.Rconf.default; "target_id", string_of_int t.Rconf.target_id; "id", string_of_int t.Rconf.id], [ Xml.Element ("build_task", [], [Xml.PCData (Target.string_of_task t.Rconf.build_task)]); Xml.Element ("env", ["replace", string_of_bool t.Rconf.env_replace], List.map (fun (e, v) -> Xml.Element ("var", ["enabled", string_of_bool e], [Xml.PCData v])) t.Rconf.env ); Xml.Element ("args", [], List.map (fun (e, v) -> Xml.Element ("arg", ["enabled", string_of_bool e], [Xml.PCData v])) t.Rconf.args); ]) end proj.executables); Xml.Element ("build_script", ["filename", proj.build_script.Build_script.bs_filename], let targets = List.map begin fun target -> Xml.Element ("target", [ "target_id", (string_of_int target.Build_script.bst_target.Target.id); "show", (string_of_bool target.Build_script.bst_show); ], []) end proj.build_script.Build_script.bs_targets in let args = List.map begin fun arg -> Xml.Element ("arg", [ "id", (string_of_int arg.Build_script_args.bsa_id); "type", (Build_script_args.string_of_type arg.Build_script_args.bsa_type); "key", arg.Build_script_args.bsa_key; "pass", (Build_script_args.string_of_pass arg.Build_script_args.bsa_pass); "command", (Build_script_command.string_of_command arg.Build_script_args.bsa_cmd); ], [ Xml.Element ("task", (match arg.Build_script_args.bsa_task with Some (bc, et) -> [ "target_id", string_of_int bc.Target.id; "task_name", et.Task.et_name; ] | None -> []), []); Xml.Element ("mode", [], [Xml.PCData (match arg.Build_script_args.bsa_mode with `add -> Build_script_args.string_of_add | `replace x -> x)]); Xml.Element ("default", [ "type", (match arg.Build_script_args.bsa_default with `flag _ -> "flag" | `bool _ -> "bool" | `string _ -> "string"); "override", (string_of_bool arg.Build_script_args.bsa_default_override); ], [Xml.PCData (match arg.Build_script_args.bsa_default with `flag x -> string_of_bool x | `bool x -> string_of_bool x | `string x -> x)]); Xml.Element ("doc", [], [Xml.PCData arg.Build_script_args.bsa_doc]); ]) end proj.build_script.Build_script.bs_args in let commands = List.map begin fun cmd -> Xml.Element ("command", [ "name", (Build_script.string_of_command cmd.Build_script.bsc_name); "descr", cmd.Build_script.bsc_descr; "target_id", string_of_int cmd.Build_script.bsc_target.Target.id; "task_name", (cmd.Build_script.bsc_task.Task.et_name); ], []) end proj.build_script.Build_script.bs_commands in [ Xml.Element ("targets", [], targets); Xml.Element ("args", [], args); Xml.Element ("commands", [], commands); ]) ]);; let value xml = try String.concat "\n" (List.map Xml.pcdata (Xml.children xml)) with Xml.Not_element _ -> "";; let fold node tag f init = Xml.fold begin fun acc node -> if Xml.tag node = tag then f node else acc end init node;; let attrib node name f default = match List_opt.assoc name (Xml.attribs node) with Some v -> f v | _ -> default;; let fattrib node name f default = match List_opt.assoc name (Xml.attribs node) with Some v -> f v | _ -> (default ());; let xml_bs_targets proj node = let open Prj in List.rev (Xml.fold begin fun acc target_node -> try {Build_script. bst_target = (match fattrib target_node "target_id" (find_target_string proj) (fun _ -> None) with Some x -> x | _ -> raise Exit); bst_show = fattrib target_node "show" bool_of_string (fun () -> true); } :: acc with Exit -> acc end [] node);; let xml_bs_args proj node = let open Prj in let count_bsa_id = ref 0 in Xml.map begin fun arg -> let bsa_doc = ref "" in let bsa_mode = ref `add in let bsa_default_override = ref true in let bsa_default = ref (`flag false) in let bsa_task = ref (None, None) in Xml.iter begin fun tp -> match Xml.tag tp with | "doc" -> bsa_doc := value tp | "mode" -> bsa_mode := begin match value tp with | x when x = Build_script_args.string_of_add -> `add | x -> `replace x end | "default" -> bsa_default_override := attrib tp "override" bool_of_string !bsa_default_override; bsa_default := begin match fattrib tp "type" (fun x -> x) (fun () -> "string") with | "flag" -> `flag (bool_of_string (value tp)) | "bool" -> `bool (bool_of_string (value tp)) | "string" -> `string (value tp) | _ -> !bsa_default end | "task" -> bsa_task := begin let target = fattrib tp "target_id" (find_target_string proj) (fun _ -> None) in let task = fattrib tp "task_name" (find_task proj) (fun _ -> None) in target, task end | _ -> () end arg; {Build_script_args. bsa_id = fattrib arg "id" int_of_string (fun () -> incr count_bsa_id; !count_bsa_id); bsa_type = fattrib arg "type" Build_script_args.type_of_string (fun _ -> Build_script_args.String); bsa_key = attrib arg "key" (fun x -> x) ""; bsa_doc = !bsa_doc; bsa_mode = !bsa_mode; bsa_default_override = !bsa_default_override; bsa_default = !bsa_default; bsa_task = begin match !bsa_task with | Some bc, Some et -> Some (bc, et) | _ -> None end; bsa_pass = fattrib arg "pass" Build_script_args.pass_of_string (fun _ -> `key_value); bsa_cmd = fattrib arg "command" Build_script_command.command_of_string (fun _ -> `Show); } end node;; let xml_commands proj node = let open Prj in List.rev (Xml.fold begin fun acc target_node -> try {Build_script. bsc_name = (fattrib target_node "name" Build_script.command_of_string (fun _ -> raise Exit)); bsc_descr = (attrib target_node "descr" (fun x -> x) ""); bsc_target = (match fattrib target_node "target_id" (find_target_string proj) (fun _ -> None) with Some x -> x | _ -> raise Exit); bsc_task = fattrib target_node "task_name" (fun y -> match find_task proj y with Some x -> x | _ -> raise Exit) (fun _ -> raise Exit) } :: acc with Exit -> acc end [] node);; let read filename = let open Prj in let proj = create ~filename () in let parser = XmlParser.make () in let xml = XmlParser.parse parser (XmlParser.SFile filename) in let get_offset xml = try int_of_string (Xml.attrib xml "offset") with Xml.No_attribute _ -> 0 in let get_active xml = try bool_of_string (Xml.attrib xml "active") with Xml.No_attribute _ -> false in let task_map = ref [] in Xml.iter begin fun node -> match Xml.tag node with | "ocaml_home" -> proj.ocaml_home <- value node | "ocamllib" -> proj.ocamllib <- value node | "encoding" -> proj.encoding <- (match value node with "" -> None | x -> Some x) | "name" -> proj.name <- value node | "author" -> proj.author <- value node | "description" -> proj.description <- String.concat "\n" (Xml.map value node) | "version" -> proj.version <- value node | "autocomp" -> proj.autocomp_enabled <- (attrib node "enabled" bool_of_string true); proj.autocomp_delay <- (float_of_string (Xml.attrib node "delay")); proj.autocomp_cflags <- (Xml.attrib node "cflags"); backward compatibility with 1.7.2 let files = Xml.fold (fun acc x -> ((value x), 0, (get_offset x), (get_active x)) :: acc) [] node in proj.open_files <- List.rev files; let runtime = Xml.fold begin fun acc tnode -> let config = { Rconf.id = (attrib tnode "id" int_of_string 0); name = (attrib tnode "name" (fun x -> x) ""); default = (attrib tnode "default" bool_of_string false); build_task = `NONE; env = []; env_replace = false; args = [] } in Xml.iter begin fun tp -> match Xml.tag tp with Backward compatibility with 1.7.0 Backward compatibility with 1.7.0 Backward compatibility with 1.7.0 Backward compatibility with 1.7.0 | "build_task" -> config.Rconf.build_task <- `NONE; task_map := (config, (value tp)) :: !task_map | "env" -> config.Rconf.env <- List.rev (Xml.fold (fun acc var -> (attrib var "enabled" bool_of_string true, value var) :: acc) [] tp); config.Rconf.env_replace <- (try bool_of_string (Xml.attrib tp "replace") with Xml.No_attribute _ -> false) | "args" -> begin try config.Rconf.args <- List.rev (Xml.fold (fun acc arg -> (attrib arg "enabled" bool_of_string true, value arg) :: acc) [] tp); with Xml.Not_element _ -> (config.Rconf.args <- [true, (value tp)]) end; | _ -> () end tnode; config :: acc end [] node in proj.executables <- List.rev runtime; let i = ref 0 in let sub_targets = ref [] in let open Target in let targets = Xml.fold begin fun acc tnode -> let target = Target.create ~id:0 ~name:(sprintf "Config_%d" !i) in let runtime_build_task = ref "" in let runtime_env = ref (false, "") in let runtime_args = ref (false, "") in let create_default_runtime = ref false in target.id <- attrib tnode "id" int_of_string 0; target.Target.name <- attrib tnode "name" (fun x -> x) ""; target.default <- attrib tnode "default" bool_of_string false; sub_targets := (target.id, List.map int_of_string (attrib tnode "sub_targets" (Str.split (Str.regexp "[;, ]+")) [])) :: !sub_targets; target.is_fl_package <- attrib tnode "is_fl_package" bool_of_string false; target.subsystem <- (try attrib tnode "subsystem" (fun x -> Some (Target.subsystem_of_string x)) None with Failure _ -> None); target.readonly <- attrib tnode "readonly" bool_of_string false; target.visible <- attrib tnode "visible" bool_of_string true; target.node_collapsed <- attrib tnode "node_collapsed" bool_of_string false; Xml.iter begin fun tp -> match Xml.tag tp with | "descr" -> target.descr <- value tp Backward compatibility with 1.7.0 Backward compatibility with 1.7.0 Backward compatibility with 1.7.0 | "byt" -> target.byt <- bool_of_string (value tp) | "opt" -> target.opt <- bool_of_string (value tp) | "libs" -> target.libs <- value tp | "other_objects" -> target.other_objects <- value tp | "files" -> target.Target.files <- value tp | "package" -> target.package <- value tp | "includes" -> target.includes <- value tp | "thread" -> target.thread <- bool_of_string (value tp) | "vmthread" -> target.vmthread <- bool_of_string (value tp) | "pp" -> target.pp <- value tp | "inline" -> target.inline <- (let x = value tp in if x = "" then None else Some (int_of_string x)) | "nodep" -> target.nodep <- bool_of_string (value tp) | "dontlinkdep" -> target.dontlinkdep <- bool_of_string (value tp) | "dontaddopt" -> target.dontaddopt <- bool_of_string (value tp) | "cflags" -> target.cflags <- value tp | "lflags" -> target.lflags <- value tp | "is_library" -> target.target_type <- (if bool_of_string (value tp) then Target.Library else Target.Executable) | "target_type" | "outkind" -> target.target_type <- target_type_of_string (value tp) | "outname" -> target.outname <- value tp | "runtime_build_task" -> runtime_build_task := (value tp); create_default_runtime := true; | "runtime_env" | "env" -> runtime_env := (attrib tp "enabed" bool_of_string true, value tp); | "runtime_args" | "run" -> runtime_args := (attrib tp "enabed" bool_of_string true, value tp); | "lib_install_path" -> target.lib_install_path <- value tp | "resource_file" -> let rc = Resource_file.create () in Xml.iter begin fun nrc -> let open Resource_file in match Xml.tag nrc with | "filename" -> target.resource_file <- Some rc; rc.rc_filename <- value nrc | "title" -> rc.rc_title <- value nrc | "company" -> rc.rc_company <- value nrc | "product" -> rc.rc_product <- value nrc | "file_version" -> rc.rc_file_version <- (match Str.split (!~ "\\.") (value nrc) with | [a;b;c;d] -> int_of_string a, int_of_string b, int_of_string c, int_of_string d | _ -> assert false) | "copyright" -> rc.rc_copyright <- value nrc | "icons" -> , Buffer.create 1000 | _ -> () end tp; | "external_tasks" -> let external_tasks = Xml.fold begin fun acc tnode -> let task = Task.create ~name:"" ~env:[] ~dir:"" ~cmd:"" ~args:[] () in task.Task.et_name <- attrib tnode "name" (fun x -> x) ""; Xml.iter begin fun tp -> match Xml.tag tp with Backward compatibility with 1.7.0 Backward compatibility with 1.7.0 | "always_run_in_project" -> task.Task.et_always_run_in_project <- bool_of_string (value tp) | "always_run_in_script" -> task.Task.et_always_run_in_script <- bool_of_string (value tp) | "readonly" -> task.Task.et_readonly <- bool_of_string (value tp) | "visible" -> task.Task.et_visible <- bool_of_string (value tp) | "env" -> task.Task.et_env <- List.rev (Xml.fold (fun acc var -> (attrib var "enabled" bool_of_string true, value var) :: acc) [] tp); task.Task.et_env_replace <- (try bool_of_string (Xml.attrib tp "replace") with Xml.No_attribute _ -> false) | "dir" -> task.Task.et_dir <- value tp | "cmd" -> task.Task.et_cmd <- value tp | "args" -> task.Task.et_args <- List.rev (Xml.fold (fun acc arg -> (attrib arg "enabled" bool_of_string true, value arg) :: acc) [] tp); | "phase" -> task.Task.et_phase <- (match value tp with "" -> None | x -> Some (Task.phase_of_string x)) | _ -> () end tnode; task :: acc end [] tp in target.external_tasks <- List.rev external_tasks; | "restrictions" -> target.restrictions <- (Str.split (!~ "&") (value tp)) | "dependencies" -> target.dependencies <- (List.map int_of_string (Str.split (!~ ",") (value tp))) | _ -> () end tnode; incr i; target ! runtime_build_task ; if !create_default_runtime && target.target_type = Target.Executable then begin proj.executables <- { Rconf.id = (List.length proj.executables); target_id = target.id; name = target.Target.name; default = target.default; build_task = Target.task_of_string target !runtime_build_task; env = [!runtime_env]; env_replace = false; args = [!runtime_args] } :: proj.executables; end; target :: acc; end [] node in proj.targets <- List.rev targets; List.iter begin fun tg -> tg.sub_targets <- let ids = try List.assoc tg.id !sub_targets with Not_found -> [] in List.map (fun id -> try List.find (fun t -> t.id = id) proj.targets with Not_found -> assert false) ids end proj.targets | "build_script" -> let filename = (attrib node "filename" (fun x -> x) "") in proj.build_script <- {Build_script. bs_filename = filename; bs_targets = fold node "targets" (xml_bs_targets proj) []; bs_args = fold node "args" (xml_bs_args proj) []; bs_commands = fold node "commands" (xml_commands proj) []; } | _ -> () end xml; List.iter (fun (rconf, task_string) -> set_runtime_build_task proj rconf task_string) !task_map; begin match List_opt.find (fun x -> x.Rconf.default) proj.executables with | None -> (match proj.executables with pr :: _ -> pr.Rconf.default <- true | _ -> ()); | _ -> () end; Translate ocamllib : " " - > ' ocamlc -where ' set_ocaml_home ~ocamllib:proj.ocamllib proj; proj;; let from_local_xml proj = let open Prj in let filename = Project.filename_local proj in let filename = if Sys.file_exists filename then filename else Project.mk_old_filename_local proj in if Sys.file_exists filename then begin let parser = XmlParser.make () in let xml = XmlParser.parse parser (XmlParser.SFile filename) in let value xml = try String.concat "\n" (List.map Xml.pcdata (Xml.children xml)) with Xml.Not_element _ -> "" in let get_int name xml = try int_of_string (Xml.attrib xml name) with Xml.No_attribute _ -> 0 in let get_cursor xml = try int_of_string (Xml.attrib xml "cursor") with Xml.No_attribute _ -> 0 in let get_active xml = try bool_of_string (Xml.attrib xml "active") with Xml.No_attribute _ -> false in Xml.iter begin fun node -> match Xml.tag node with | "open_files" -> let files = Xml.fold (fun acc x -> ((value x), (get_int "scroll" x), (get_cursor x), (get_active x)) :: acc) [] node in proj.open_files <- List.rev files; | "bookmarks" -> Xml.iter begin fun xml -> let bm = { bm_filename = (value xml); bm_loc = Offset (get_int "offset" xml); bm_num = (get_int "num" xml); bm_marker = None; } in Project.set_bookmark bm proj end node; | _ -> () end xml; end;; let init () = Project.write_xml := write; Project.read_xml := read; Project.from_local_xml := from_local_xml;
77b3ff9688d844219d5517c0e24a49730e509e2cf00ca3e4aa6a3f55b3477266
blancas/kern
json.clj
(ns ^{:doc "A sample JSON parser." :author "Armando Blancas"} json (:use [blancas.kern.core] [blancas.kern.lexer.basic])) ;; To try: (comment (load "json") (ns json) (run jvalue (slurp "src/main/resources/tweet.json")) ) (declare jvalue) (def pair "Parses the rule: pair := String ':' jvalue" (bind [f string-lit _ colon v jvalue] (return [f v]))) (def array "Parses the rule: array := '[' (jvalue (',' jvalue)*)* ']'" (brackets (comma-sep (fwd jvalue)))) (def object "Parses the rule: object := '{' (pair (',' pair)*)* '}'" (braces (bind [members (comma-sep pair)] (return (apply hash-map (reduce concat [] members)))))) (def jvalue "Parses a JSON value." (<|> string-lit dec-lit float-lit bool-lit nil-lit array object))
null
https://raw.githubusercontent.com/blancas/kern/3ef65e559658c06a321a9ca7c85a541edc7b9ff2/src/main/resources/json.clj
clojure
To try:
(ns ^{:doc "A sample JSON parser." :author "Armando Blancas"} json (:use [blancas.kern.core] [blancas.kern.lexer.basic])) (comment (load "json") (ns json) (run jvalue (slurp "src/main/resources/tweet.json")) ) (declare jvalue) (def pair "Parses the rule: pair := String ':' jvalue" (bind [f string-lit _ colon v jvalue] (return [f v]))) (def array "Parses the rule: array := '[' (jvalue (',' jvalue)*)* ']'" (brackets (comma-sep (fwd jvalue)))) (def object "Parses the rule: object := '{' (pair (',' pair)*)* '}'" (braces (bind [members (comma-sep pair)] (return (apply hash-map (reduce concat [] members)))))) (def jvalue "Parses a JSON value." (<|> string-lit dec-lit float-lit bool-lit nil-lit array object))
5988ab8031d4117882b060cc5a1e29f5a53cf3790691549c93ea582f4f0e7d18
foreverbell/project-euler-solutions
81.hs
import Data.Array.ST import Control.Monad import Control.Monad.ST getShortest :: [[Int]] -> Int getShortest mat = runST $ do dp <- newArray ((0, 0), (n - 1, m - 1)) 0 :: ST s (STArray s (Int, Int) Int) forM_ [0 .. n - 1] $ \i -> do forM_ [0 .. m - 1] $ \j -> do update dp i j readArray dp (n - 1, m - 1) where n = length mat m = length $ mat!!0 update :: STArray s (Int, Int) Int -> Int -> Int -> ST s () update dp 0 0 = writeArray dp (0, 0) ((mat!!0)!!0) update dp 0 j = do go <- readArray dp (0, j - 1) writeArray dp (0, j) (go + ((mat!!0)!!j)) update dp i 0 = do go <- readArray dp (i - 1, 0) writeArray dp (i, 0) (go + ((mat!!i)!!0)) update dp i j = do go1 <- readArray dp (i - 1, j) go2 <- readArray dp (i, j - 1) let go = min go1 go2 writeArray dp (i, j) (go + ((mat!!i)!!j)) comma :: String -> [Int] comma [] = [] comma (',' : xs) = comma xs comma s = (read a) : (comma b) where (a, b) = span (/= ',') s readInput :: IO [[Int]] readInput = (readFile "input/p081_matrix.txt") >>= (return . (map comma) . words) main = readInput >>= (print . getShortest)
null
https://raw.githubusercontent.com/foreverbell/project-euler-solutions/c0bf2746aafce9be510892814e2d03e20738bf2b/src/81.hs
haskell
import Data.Array.ST import Control.Monad import Control.Monad.ST getShortest :: [[Int]] -> Int getShortest mat = runST $ do dp <- newArray ((0, 0), (n - 1, m - 1)) 0 :: ST s (STArray s (Int, Int) Int) forM_ [0 .. n - 1] $ \i -> do forM_ [0 .. m - 1] $ \j -> do update dp i j readArray dp (n - 1, m - 1) where n = length mat m = length $ mat!!0 update :: STArray s (Int, Int) Int -> Int -> Int -> ST s () update dp 0 0 = writeArray dp (0, 0) ((mat!!0)!!0) update dp 0 j = do go <- readArray dp (0, j - 1) writeArray dp (0, j) (go + ((mat!!0)!!j)) update dp i 0 = do go <- readArray dp (i - 1, 0) writeArray dp (i, 0) (go + ((mat!!i)!!0)) update dp i j = do go1 <- readArray dp (i - 1, j) go2 <- readArray dp (i, j - 1) let go = min go1 go2 writeArray dp (i, j) (go + ((mat!!i)!!j)) comma :: String -> [Int] comma [] = [] comma (',' : xs) = comma xs comma s = (read a) : (comma b) where (a, b) = span (/= ',') s readInput :: IO [[Int]] readInput = (readFile "input/p081_matrix.txt") >>= (return . (map comma) . words) main = readInput >>= (print . getShortest)
2597151350ea4e899db9aa5e5123c94373c35cf42560b817b67c40cebe473c12
S8A/htdp-exercises
ex221.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 ex221) (read-case-sensitive #t) (teachpacks ((lib "image.rkt" "teachpack" "2htdp") (lib "universe.rkt" "teachpack" "2htdp") (lib "batch-io.rkt" "teachpack" "2htdp") (lib "itunes.rkt" "teachpack" "2htdp"))) (htdp-settings #(#t constructor repeating-decimal #f #t none #f ((lib "image.rkt" "teachpack" "2htdp") (lib "universe.rkt" "teachpack" "2htdp") (lib "batch-io.rkt" "teachpack" "2htdp") (lib "itunes.rkt" "teachpack" "2htdp")) #f))) ; Constants :. (define WIDTH 10) ; # of blocks, horizontally (define HEIGHT WIDTH) (define SIZE 10) ; blocks are squares (define SCENE-SIZE (* WIDTH SIZE)) (define BLOCK ; red squares with black rims (overlay (square (- SIZE 1) "solid" "red") (square SIZE "outline" "black"))) (define HALF-BLOCK (/ SIZE 2)) (define BACKG (empty-scene SCENE-SIZE SCENE-SIZE "midnightblue")) ; Data definitions :. (define-struct tetris [block landscape]) (define-struct block [x y]) A Tetris is a structure : ; (make-tetris Block Landscape) ; A Landscape is one of: ; – '() ; – (cons Block Landscape) ; A Block is a structure: ( make - block N N ) ; interpretations ; (make-block x y) depicts a block whose left ; corner is (* x SIZE) pixels from the left and ; (* y SIZE) pixels from the top; ; (make-tetris b0 (list b1 b2 ...)) means b0 is the ; dropping block, while b1, b2, and ... are resting ; Data examples :. (define block-dropping0 (make-block 0 0)) (define block-dropping1 (make-block 3 4)) (define block-landed (make-block 0 (- HEIGHT 1))) (define block-on-block (make-block 0 (- HEIGHT 2))) (define landscape0 '()) (define landscape1 (list block-landed)) (define landscape2 (list block-on-block block-landed)) (define tetris0 (make-tetris block-dropping0 landscape0)) (define tetris1 (make-tetris block-dropping1 landscape0)) (define tetris2 (make-tetris block-dropping0 landscape1)) (define tetris3 (make-tetris block-dropping1 landscape2)) (define tetris4 (make-tetris block-landed landscape0)) (define tetris5 (make-tetris block-on-block landscape1)) ; Main ::.. ; Number -> Tetris Runs the simplified tetris game with a clock that ticks every x seconds . (define (tetris-main x) (big-bang (make-tetris block-dropping0 landscape0) [to-draw tetris-render] [on-tick tetris-tock x])) ; Functions :. Tetris - > Image ; Renders the current state of the tetris game as an image. (define (tetris-render t) (block-render (tetris-block t) (landscape-render (tetris-landscape t) BACKG))) (check-expect (tetris-render tetris0) (block-render block-dropping0 (landscape-render landscape0 BACKG))) (check-expect (tetris-render tetris1) (block-render block-dropping1 (landscape-render landscape0 BACKG))) (check-expect (tetris-render tetris2) (block-render block-dropping0 (landscape-render landscape1 BACKG))) (check-expect (tetris-render tetris3) (block-render block-dropping1 (landscape-render landscape2 BACKG))) Tetris - > Tetris After each tick , makes block fall one unit . If the block reaches the ; ground or the top of another block, add it to the landscape and make ; another block fall. (define (tetris-tock t) (if (block-landed? t) (make-tetris (new-block (tetris-block t)) (cons (tetris-block t) (tetris-landscape t))) (make-tetris (move-down (tetris-block t)) (tetris-landscape t)))) (check-expect (tetris-tock tetris0) (make-tetris (move-down block-dropping0) landscape0)) (check-expect (tetris-tock tetris1) (make-tetris (move-down block-dropping1) landscape0)) (check-expect (tetris-tock tetris2) (make-tetris (move-down block-dropping0) landscape1)) (check-expect (tetris-tock tetris3) (make-tetris (move-down block-dropping1) landscape2)) (check-expect (tetris-tock tetris4) (make-tetris (new-block block-landed) (cons block-landed landscape0))) (check-expect (tetris-tock tetris5) (make-tetris (new-block block-on-block) (cons block-on-block landscape1))) ; Landscape Image -> Image ; Renders the landscape over the given image. (define (landscape-render ls im) (cond [(empty? ls) im] [(cons? ls) (block-render (first ls) (landscape-render (rest ls) im))])) (check-expect (landscape-render landscape0 BACKG) BACKG) (check-expect (landscape-render landscape1 BACKG) (block-render block-landed BACKG)) (check-expect (landscape-render landscape2 BACKG) (block-render block-on-block (block-render block-landed BACKG))) ; Block Image -> Image ; Renders the block at its corresponding position over the given image. (define (block-render b im) (place-image BLOCK (+ (* (block-x b) SIZE) HALF-BLOCK) (+ (* (block-y b) SIZE) HALF-BLOCK) im)) (check-expect (block-render block-dropping0 BACKG) (place-image BLOCK HALF-BLOCK HALF-BLOCK BACKG)) (check-expect (block-render block-dropping1 BACKG) (place-image BLOCK (+ (* 3 SIZE) HALF-BLOCK) (+ (* 4 SIZE) HALF-BLOCK) BACKG)) (check-expect (block-render block-landed BACKG) (place-image BLOCK HALF-BLOCK (+ (* (- HEIGHT 1) SIZE) HALF-BLOCK) BACKG)) (check-expect (block-render block-on-block BACKG) (place-image BLOCK HALF-BLOCK (+ (* (- HEIGHT 2) SIZE) HALF-BLOCK) BACKG)) Tetris - > Boolean Determines whether the block of the given Tetris has landed on the ground ; or over any block of its landscape (define (block-landed? t) (or (= (block-y (tetris-block t)) (- HEIGHT 1)) (member? (move-down (tetris-block t)) (tetris-landscape t)))) (check-expect (block-landed? tetris0) #false) (check-expect (block-landed? tetris1) #false) (check-expect (block-landed? tetris2) #false) (check-expect (block-landed? tetris3) #false) (check-expect (block-landed? tetris4) #true) (check-expect (block-landed? tetris5) #true) ; Block -> Block Moves the given block down by one unit . (define (move-down b) (make-block (block-x b) (+ (block-y b) 1))) (check-expect (move-down block-dropping0) (make-block 0 1)) (check-expect (move-down block-dropping1) (make-block 3 5)) ; Block -> Block ; Creates a new block that descends on the column to the right of ; the given one, or at the left-most column if the given block is at ; the right-most column (define (new-block b) (make-block (modulo (+ (block-x b) 1) WIDTH) 0)) (check-expect (new-block block-landed) (make-block 1 0)) (check-expect (new-block block-dropping1) (make-block 4 0)) (check-expect (new-block (make-block (- WIDTH 1) 5)) (make-block 0 0))
null
https://raw.githubusercontent.com/S8A/htdp-exercises/578e49834a9513f29ef81b7589b28081c5e0b69f/ex221.rkt
racket
about the language level of this file in a form that our tools can easily process. Constants :. # of blocks, horizontally blocks are squares red squares with black rims Data definitions :. (make-tetris Block Landscape) A Landscape is one of: – '() – (cons Block Landscape) A Block is a structure: interpretations (make-block x y) depicts a block whose left corner is (* x SIZE) pixels from the left and (* y SIZE) pixels from the top; (make-tetris b0 (list b1 b2 ...)) means b0 is the dropping block, while b1, b2, and ... are resting Data examples :. Main ::.. Number -> Tetris Functions :. Renders the current state of the tetris game as an image. ground or the top of another block, add it to the landscape and make another block fall. Landscape Image -> Image Renders the landscape over the given image. Block Image -> Image Renders the block at its corresponding position over the given image. or over any block of its landscape Block -> Block Block -> Block Creates a new block that descends on the column to the right of the given one, or at the left-most column if the given block is at the right-most column
The first three lines of this file were inserted by . They record metadata #reader(lib "htdp-beginner-abbr-reader.ss" "lang")((modname ex221) (read-case-sensitive #t) (teachpacks ((lib "image.rkt" "teachpack" "2htdp") (lib "universe.rkt" "teachpack" "2htdp") (lib "batch-io.rkt" "teachpack" "2htdp") (lib "itunes.rkt" "teachpack" "2htdp"))) (htdp-settings #(#t constructor repeating-decimal #f #t none #f ((lib "image.rkt" "teachpack" "2htdp") (lib "universe.rkt" "teachpack" "2htdp") (lib "batch-io.rkt" "teachpack" "2htdp") (lib "itunes.rkt" "teachpack" "2htdp")) #f))) (define HEIGHT WIDTH) (define SCENE-SIZE (* WIDTH SIZE)) (overlay (square (- SIZE 1) "solid" "red") (square SIZE "outline" "black"))) (define HALF-BLOCK (/ SIZE 2)) (define BACKG (empty-scene SCENE-SIZE SCENE-SIZE "midnightblue")) (define-struct tetris [block landscape]) (define-struct block [x y]) A Tetris is a structure : ( make - block N N ) (define block-dropping0 (make-block 0 0)) (define block-dropping1 (make-block 3 4)) (define block-landed (make-block 0 (- HEIGHT 1))) (define block-on-block (make-block 0 (- HEIGHT 2))) (define landscape0 '()) (define landscape1 (list block-landed)) (define landscape2 (list block-on-block block-landed)) (define tetris0 (make-tetris block-dropping0 landscape0)) (define tetris1 (make-tetris block-dropping1 landscape0)) (define tetris2 (make-tetris block-dropping0 landscape1)) (define tetris3 (make-tetris block-dropping1 landscape2)) (define tetris4 (make-tetris block-landed landscape0)) (define tetris5 (make-tetris block-on-block landscape1)) Runs the simplified tetris game with a clock that ticks every x seconds . (define (tetris-main x) (big-bang (make-tetris block-dropping0 landscape0) [to-draw tetris-render] [on-tick tetris-tock x])) Tetris - > Image (define (tetris-render t) (block-render (tetris-block t) (landscape-render (tetris-landscape t) BACKG))) (check-expect (tetris-render tetris0) (block-render block-dropping0 (landscape-render landscape0 BACKG))) (check-expect (tetris-render tetris1) (block-render block-dropping1 (landscape-render landscape0 BACKG))) (check-expect (tetris-render tetris2) (block-render block-dropping0 (landscape-render landscape1 BACKG))) (check-expect (tetris-render tetris3) (block-render block-dropping1 (landscape-render landscape2 BACKG))) Tetris - > Tetris After each tick , makes block fall one unit . If the block reaches the (define (tetris-tock t) (if (block-landed? t) (make-tetris (new-block (tetris-block t)) (cons (tetris-block t) (tetris-landscape t))) (make-tetris (move-down (tetris-block t)) (tetris-landscape t)))) (check-expect (tetris-tock tetris0) (make-tetris (move-down block-dropping0) landscape0)) (check-expect (tetris-tock tetris1) (make-tetris (move-down block-dropping1) landscape0)) (check-expect (tetris-tock tetris2) (make-tetris (move-down block-dropping0) landscape1)) (check-expect (tetris-tock tetris3) (make-tetris (move-down block-dropping1) landscape2)) (check-expect (tetris-tock tetris4) (make-tetris (new-block block-landed) (cons block-landed landscape0))) (check-expect (tetris-tock tetris5) (make-tetris (new-block block-on-block) (cons block-on-block landscape1))) (define (landscape-render ls im) (cond [(empty? ls) im] [(cons? ls) (block-render (first ls) (landscape-render (rest ls) im))])) (check-expect (landscape-render landscape0 BACKG) BACKG) (check-expect (landscape-render landscape1 BACKG) (block-render block-landed BACKG)) (check-expect (landscape-render landscape2 BACKG) (block-render block-on-block (block-render block-landed BACKG))) (define (block-render b im) (place-image BLOCK (+ (* (block-x b) SIZE) HALF-BLOCK) (+ (* (block-y b) SIZE) HALF-BLOCK) im)) (check-expect (block-render block-dropping0 BACKG) (place-image BLOCK HALF-BLOCK HALF-BLOCK BACKG)) (check-expect (block-render block-dropping1 BACKG) (place-image BLOCK (+ (* 3 SIZE) HALF-BLOCK) (+ (* 4 SIZE) HALF-BLOCK) BACKG)) (check-expect (block-render block-landed BACKG) (place-image BLOCK HALF-BLOCK (+ (* (- HEIGHT 1) SIZE) HALF-BLOCK) BACKG)) (check-expect (block-render block-on-block BACKG) (place-image BLOCK HALF-BLOCK (+ (* (- HEIGHT 2) SIZE) HALF-BLOCK) BACKG)) Tetris - > Boolean Determines whether the block of the given Tetris has landed on the ground (define (block-landed? t) (or (= (block-y (tetris-block t)) (- HEIGHT 1)) (member? (move-down (tetris-block t)) (tetris-landscape t)))) (check-expect (block-landed? tetris0) #false) (check-expect (block-landed? tetris1) #false) (check-expect (block-landed? tetris2) #false) (check-expect (block-landed? tetris3) #false) (check-expect (block-landed? tetris4) #true) (check-expect (block-landed? tetris5) #true) Moves the given block down by one unit . (define (move-down b) (make-block (block-x b) (+ (block-y b) 1))) (check-expect (move-down block-dropping0) (make-block 0 1)) (check-expect (move-down block-dropping1) (make-block 3 5)) (define (new-block b) (make-block (modulo (+ (block-x b) 1) WIDTH) 0)) (check-expect (new-block block-landed) (make-block 1 0)) (check-expect (new-block block-dropping1) (make-block 4 0)) (check-expect (new-block (make-block (- WIDTH 1) 5)) (make-block 0 0))
758410b69aab83d5e8049b10b6ca737866d36a735affe4dfeed3720f5127a9f1
clash-lang/clash-prelude
DDR.hs
| Copyright : ( C ) 2017 , Google Inc License : BSD2 ( see the file LICENSE ) Maintainer : < > We simulate DDR signal by using ' Signal 's which have exactly half the period ( or double the speed ) of our normal ' Signal 's . The primives in this module can be used to produce of consume DDR signals . DDR signals are not meant to be used internally in a design , but only to communicate with the outside world . In some cases hardware specific DDR IN registers can be infered by synthesis tools from these generic primitives . But to be sure your design will synthesize to dedicated hardware resources use the functions from " Clash . Intel . DDR " or " Clash . Xilinx . DDR " . Copyright : (C) 2017, Google Inc License : BSD2 (see the file LICENSE) Maintainer : Christiaan Baaij <> We simulate DDR signal by using 'Signal's which have exactly half the period (or double the speed) of our normal 'Signal's. The primives in this module can be used to produce of consume DDR signals. DDR signals are not meant to be used internally in a design, but only to communicate with the outside world. In some cases hardware specific DDR IN registers can be infered by synthesis tools from these generic primitives. But to be sure your design will synthesize to dedicated hardware resources use the functions from "Clash.Intel.DDR" or "Clash.Xilinx.DDR". -} # LANGUAGE CPP # {-# LANGUAGE DataKinds #-} # LANGUAGE MagicHash # # LANGUAGE ScopedTypeVariables # # LANGUAGE TypeFamilies # {-# LANGUAGE TypeOperators #-} #if __GLASGOW_HASKELL__ >= 806 # LANGUAGE NoStarIsType # #endif module Clash.Explicit.DDR ( ddrIn , ddrOut -- * Internal , ddrIn# , ddrOut# ) where import GHC.Stack (HasCallStack, withFrozenCallStack) import Clash.Explicit.Prelude import Clash.Signal.Internal | DDR input primitive -- Consumes a DDR input signal and produces a regular signal containing a pair -- of values. ddrIn :: ( HasCallStack , fast ~ 'Dom n pFast , slow ~ 'Dom n (2*pFast)) => Clock slow gated -- ^ clock -> Reset slow synchronous -- ^ reset -> (a, a, a) -- ^ reset values -> Signal fast a -- ^ DDR input signal -> Signal slow (a,a) -- ^ normal speed output pairs ddrIn clk rst (i0,i1,i2) = withFrozenCallStack $ ddrIn# clk rst i0 i1 i2 For details about all the seq 's en 's see the [ Note : register strictness annotations ] in Clash . Signal . Internal ddrIn# :: forall a slow fast n pFast gated synchronous . ( HasCallStack , fast ~ 'Dom n pFast , slow ~ 'Dom n (2*pFast)) => Clock slow gated -> Reset slow synchronous -> a -> a -> a -> Signal fast a -> Signal slow (a,a) ddrIn# (Clock {}) (Sync rst) i0 i1 i2 = go ((errorX "ddrIn: initial value 0 undefined") ,(errorX "ddrIn: initial value 1 undefined") ,(errorX "ddrIn: initial value 2 undefined")) rst where go :: (a,a,a) -> Signal slow Bool -> Signal fast a -> Signal slow (a,a) go (o0,o1,o2) rt@(~(r :- rs)) as@(~(x0 :- x1 :- xs)) = let (o0',o1',o2') = if r then (i0,i1,i2) else (o2,x0,x1) in o0 `seqX` o1 `seqX` (o0,o1) :- (rt `seq` as `seq` go (o0',o1',o2') rs xs) ddrIn# (Clock {}) (Async rst) i0 i1 i2 = go ((errorX "ddrIn: initial value 0 undefined") ,(errorX "ddrIn: initial value 1 undefined") ,(errorX "ddrIn: initial value 2 undefined")) rst where go :: (a,a,a) -> Signal slow Bool -> Signal fast a -> Signal slow (a,a) go (o0,o1,o2) ~(r :- rs) as@(~(x0 :- x1 :- xs)) = let (o0',o1',o2') = if r then (i0,i1,i2) else (o0,o1,o2) in o0' `seqX` o1' `seqX`(o0',o1') :- (as `seq` go (o2',x0,x1) rs xs) ddrIn# (GatedClock _ _ ena) (Sync rst) i0 i1 i2 = go ((errorX "ddrIn: initial value 0 undefined") ,(errorX "ddrIn: initial value 1 undefined") ,(errorX "ddrIn: initial value 2 undefined")) rst ena where go :: (a,a,a) -> Signal slow Bool -> Signal slow Bool -> Signal fast a -> Signal slow (a,a) go (o0,o1,o2) rt@(~(r :- rs)) ~(e :- es) as@(~(x0 :- x1 :- xs)) = let (o0',o1',o2') = if r then (i0,i1,i2) else (o2,x0,x1) in o0 `seqX` o1 `seqX` (o0,o1) :- (rt `seq` as `seq` if e then go (o0',o1',o2') rs es xs else go (o0 ,o1 ,o2) rs es xs) ddrIn# (GatedClock _ _ ena) (Async rst) i0 i1 i2 = go ((errorX "ddrIn: initial value 0 undefined") ,(errorX "ddrIn: initial value 1 undefined") ,(errorX "ddrIn: initial value 2 undefined")) rst ena where go :: (a,a,a) -> Signal slow Bool -> Signal slow Bool -> Signal fast a -> Signal slow (a,a) go (o0,o1,o2) ~(r :- rs) ~(e :- es) as@(~(x0 :- x1 :- xs)) = let (o0',o1',o2') = if r then (i0,i1,i2) else (o0,o1,o2) in o0' `seqX` o1' `seqX` (o0',o1') :- (as `seq` if e then go (o2',x0 ,x1) rs es xs else go (o0',o1',o2') rs es xs) # NOINLINE ddrIn # # -- | DDR output primitive -- Produces a DDR output signal from a normal signal of pairs of input . ddrOut :: ( HasCallStack , Undefined a , fast ~ 'Dom n pFast , slow ~ 'Dom n (2*pFast)) => Clock slow gated -- ^ clock -> Reset slow synchronous -- ^ reset -> a -- ^ reset value -> Signal slow (a,a) -- ^ normal speed input pairs -> Signal fast a -- ^ DDR output signal ddrOut clk rst i0 = uncurry (withFrozenCallStack $ ddrOut# clk rst i0) . unbundle ddrOut# :: ( HasCallStack , Undefined a , fast ~ 'Dom n pFast , slow ~ 'Dom n (2*pFast)) => Clock slow gated -> Reset slow synchronous -> a -> Signal slow a -> Signal slow a -> Signal fast a ddrOut# clk rst i0 xs ys = We only observe one reset value , because when the mux switches on the next clock level , the second register will already be outputting its -- first input. -- That is why we drop the first value of the stream . let (_ :- out) = zipSig xs' ys' in out where xs' = register clk rst i0 xs ys' = register clk rst i0 ys zipSig (a :- as) (b :- bs) = a :- b :- zipSig as bs # NOINLINE ddrOut # #
null
https://raw.githubusercontent.com/clash-lang/clash-prelude/5645d8417ab495696cf4e0293796133c7fe2a9a7/src/Clash/Explicit/DDR.hs
haskell
# LANGUAGE DataKinds # # LANGUAGE TypeOperators # * Internal of values. ^ clock ^ reset ^ reset values ^ DDR input signal ^ normal speed output pairs | DDR output primitive ^ clock ^ reset ^ reset value ^ normal speed input pairs ^ DDR output signal first input.
| Copyright : ( C ) 2017 , Google Inc License : BSD2 ( see the file LICENSE ) Maintainer : < > We simulate DDR signal by using ' Signal 's which have exactly half the period ( or double the speed ) of our normal ' Signal 's . The primives in this module can be used to produce of consume DDR signals . DDR signals are not meant to be used internally in a design , but only to communicate with the outside world . In some cases hardware specific DDR IN registers can be infered by synthesis tools from these generic primitives . But to be sure your design will synthesize to dedicated hardware resources use the functions from " Clash . Intel . DDR " or " Clash . Xilinx . DDR " . Copyright : (C) 2017, Google Inc License : BSD2 (see the file LICENSE) Maintainer : Christiaan Baaij <> We simulate DDR signal by using 'Signal's which have exactly half the period (or double the speed) of our normal 'Signal's. The primives in this module can be used to produce of consume DDR signals. DDR signals are not meant to be used internally in a design, but only to communicate with the outside world. In some cases hardware specific DDR IN registers can be infered by synthesis tools from these generic primitives. But to be sure your design will synthesize to dedicated hardware resources use the functions from "Clash.Intel.DDR" or "Clash.Xilinx.DDR". -} # LANGUAGE CPP # # LANGUAGE MagicHash # # LANGUAGE ScopedTypeVariables # # LANGUAGE TypeFamilies # #if __GLASGOW_HASKELL__ >= 806 # LANGUAGE NoStarIsType # #endif module Clash.Explicit.DDR ( ddrIn , ddrOut , ddrIn# , ddrOut# ) where import GHC.Stack (HasCallStack, withFrozenCallStack) import Clash.Explicit.Prelude import Clash.Signal.Internal | DDR input primitive Consumes a DDR input signal and produces a regular signal containing a pair ddrIn :: ( HasCallStack , fast ~ 'Dom n pFast , slow ~ 'Dom n (2*pFast)) => Clock slow gated -> Reset slow synchronous -> (a, a, a) -> Signal fast a -> Signal slow (a,a) ddrIn clk rst (i0,i1,i2) = withFrozenCallStack $ ddrIn# clk rst i0 i1 i2 For details about all the seq 's en 's see the [ Note : register strictness annotations ] in Clash . Signal . Internal ddrIn# :: forall a slow fast n pFast gated synchronous . ( HasCallStack , fast ~ 'Dom n pFast , slow ~ 'Dom n (2*pFast)) => Clock slow gated -> Reset slow synchronous -> a -> a -> a -> Signal fast a -> Signal slow (a,a) ddrIn# (Clock {}) (Sync rst) i0 i1 i2 = go ((errorX "ddrIn: initial value 0 undefined") ,(errorX "ddrIn: initial value 1 undefined") ,(errorX "ddrIn: initial value 2 undefined")) rst where go :: (a,a,a) -> Signal slow Bool -> Signal fast a -> Signal slow (a,a) go (o0,o1,o2) rt@(~(r :- rs)) as@(~(x0 :- x1 :- xs)) = let (o0',o1',o2') = if r then (i0,i1,i2) else (o2,x0,x1) in o0 `seqX` o1 `seqX` (o0,o1) :- (rt `seq` as `seq` go (o0',o1',o2') rs xs) ddrIn# (Clock {}) (Async rst) i0 i1 i2 = go ((errorX "ddrIn: initial value 0 undefined") ,(errorX "ddrIn: initial value 1 undefined") ,(errorX "ddrIn: initial value 2 undefined")) rst where go :: (a,a,a) -> Signal slow Bool -> Signal fast a -> Signal slow (a,a) go (o0,o1,o2) ~(r :- rs) as@(~(x0 :- x1 :- xs)) = let (o0',o1',o2') = if r then (i0,i1,i2) else (o0,o1,o2) in o0' `seqX` o1' `seqX`(o0',o1') :- (as `seq` go (o2',x0,x1) rs xs) ddrIn# (GatedClock _ _ ena) (Sync rst) i0 i1 i2 = go ((errorX "ddrIn: initial value 0 undefined") ,(errorX "ddrIn: initial value 1 undefined") ,(errorX "ddrIn: initial value 2 undefined")) rst ena where go :: (a,a,a) -> Signal slow Bool -> Signal slow Bool -> Signal fast a -> Signal slow (a,a) go (o0,o1,o2) rt@(~(r :- rs)) ~(e :- es) as@(~(x0 :- x1 :- xs)) = let (o0',o1',o2') = if r then (i0,i1,i2) else (o2,x0,x1) in o0 `seqX` o1 `seqX` (o0,o1) :- (rt `seq` as `seq` if e then go (o0',o1',o2') rs es xs else go (o0 ,o1 ,o2) rs es xs) ddrIn# (GatedClock _ _ ena) (Async rst) i0 i1 i2 = go ((errorX "ddrIn: initial value 0 undefined") ,(errorX "ddrIn: initial value 1 undefined") ,(errorX "ddrIn: initial value 2 undefined")) rst ena where go :: (a,a,a) -> Signal slow Bool -> Signal slow Bool -> Signal fast a -> Signal slow (a,a) go (o0,o1,o2) ~(r :- rs) ~(e :- es) as@(~(x0 :- x1 :- xs)) = let (o0',o1',o2') = if r then (i0,i1,i2) else (o0,o1,o2) in o0' `seqX` o1' `seqX` (o0',o1') :- (as `seq` if e then go (o2',x0 ,x1) rs es xs else go (o0',o1',o2') rs es xs) # NOINLINE ddrIn # # Produces a DDR output signal from a normal signal of pairs of input . ddrOut :: ( HasCallStack , Undefined a , fast ~ 'Dom n pFast , slow ~ 'Dom n (2*pFast)) ddrOut clk rst i0 = uncurry (withFrozenCallStack $ ddrOut# clk rst i0) . unbundle ddrOut# :: ( HasCallStack , Undefined a , fast ~ 'Dom n pFast , slow ~ 'Dom n (2*pFast)) => Clock slow gated -> Reset slow synchronous -> a -> Signal slow a -> Signal slow a -> Signal fast a ddrOut# clk rst i0 xs ys = We only observe one reset value , because when the mux switches on the next clock level , the second register will already be outputting its That is why we drop the first value of the stream . let (_ :- out) = zipSig xs' ys' in out where xs' = register clk rst i0 xs ys' = register clk rst i0 ys zipSig (a :- as) (b :- bs) = a :- b :- zipSig as bs # NOINLINE ddrOut # #
df6bea7411719ac9c46174fff745ef1e705e507d1ac5f9a47f779e5a75a4fd5c
jiacai2050/blog-backup
runner.cljs
(ns blog-backup.runner (:require [doo.runner :refer-macros [doo-tests]] [blog-backup.util-test])) ;; (doo.runner/doo-all-tests) (doo-tests 'blog-backup.util-test)
null
https://raw.githubusercontent.com/jiacai2050/blog-backup/5c76db345699b23cfd3759b62d743f41edf17d2e/test/blog_backup/runner.cljs
clojure
(doo.runner/doo-all-tests)
(ns blog-backup.runner (:require [doo.runner :refer-macros [doo-tests]] [blog-backup.util-test])) (doo-tests 'blog-backup.util-test)
3315942b9e71baa7411bfbb8aa58969fdf7c7f9c4aa8f8927f86e11bab851d15
seckcoder/course-compiler
s1_2.rkt
(let ([x #f]) 42)
null
https://raw.githubusercontent.com/seckcoder/course-compiler/4363e5b3e15eaa7553902c3850b6452de80b2ef6/tests/s1_2.rkt
racket
(let ([x #f]) 42)
c9486b491a46cb4645b16dc87b36335681c3e631baca05fe73b6de00ac39b126
YoshikuniJujo/test_haskell
Q.hs
# LANGUAGE TemplateHaskell # # OPTIONS_GHC -Wall -fno - warn - tabs # module BigTuple.Example.Q where import Language.Haskell.TH data Tuple3 a b c = Tuple3 a b c deriving Show foo0 :: DecsQ foo0 = [d| data Tuple3 a b c = Tuple3 a b c |] foo :: ExpQ foo = [| Tuple3 1 2 3 |] bar :: TypeQ bar = [t| Tuple3 Int Char () |] baz :: PatQ baz = [p| Tuple3 x y z |]
null
https://raw.githubusercontent.com/YoshikuniJujo/test_haskell/59b4f68cfacd8e3b0911dc8d4cb754a201d7a381/tribial/try-tribials/src/BigTuple/Example/Q.hs
haskell
# LANGUAGE TemplateHaskell # # OPTIONS_GHC -Wall -fno - warn - tabs # module BigTuple.Example.Q where import Language.Haskell.TH data Tuple3 a b c = Tuple3 a b c deriving Show foo0 :: DecsQ foo0 = [d| data Tuple3 a b c = Tuple3 a b c |] foo :: ExpQ foo = [| Tuple3 1 2 3 |] bar :: TypeQ bar = [t| Tuple3 Int Char () |] baz :: PatQ baz = [p| Tuple3 x y z |]
97a43547abc957107ba657a37f8eb4dc7ed9d3f01f90e985df9b9b40b6c112a8
arcfide/chez-srfi
cut.sps
#!r6rs Copyright 2010 . My MIT - style license is in the file named ;; LICENSE from the original collection this file is distributed with. (import (except (rnrs) display newline) (srfi :78 lightweight-testing) (srfi private include) (srfi :26 cut)) (define (ignore . _) (values)) (define display ignore) (define newline ignore) (define check-all ignore) (let-syntax ((define (syntax-rules (check check-all for-each quote equal?) ((_ (check _) . _) (begin)) ((_ (check-all) (for-each check '((equal? expr val) ...))) (begin (check expr => val) ...))))) (include/resolve ("srfi" "%3a26") "check.scm")) ;;;; free-identifier=? of <> and <...> (check (let* ((<> 'wrong) (f (cut list <> <...>))) (set! <> 'ok) (f 1 2)) => '(ok 1 2)) (check (let* ((<...> 'wrong) (f (cut list <> <...>))) (set! <...> 'ok) (f 1)) => '(1 ok)) (check (let* ((<> 'ok) (f (cute list <> <...>))) (set! <> 'wrong) (f 1 2)) => '(ok 1 2)) (check (let* ((<...> 'ok) (f (cute list <> <...>))) (set! <...> 'wrong) (f 1)) => '(1 ok)) (check-report)
null
https://raw.githubusercontent.com/arcfide/chez-srfi/96fb553b6ba0834747d5ccfc08c181aa8fd5f612/tests/cut.sps
scheme
LICENSE from the original collection this file is distributed with. free-identifier=? of <> and <...>
#!r6rs Copyright 2010 . My MIT - style license is in the file named (import (except (rnrs) display newline) (srfi :78 lightweight-testing) (srfi private include) (srfi :26 cut)) (define (ignore . _) (values)) (define display ignore) (define newline ignore) (define check-all ignore) (let-syntax ((define (syntax-rules (check check-all for-each quote equal?) ((_ (check _) . _) (begin)) ((_ (check-all) (for-each check '((equal? expr val) ...))) (begin (check expr => val) ...))))) (include/resolve ("srfi" "%3a26") "check.scm")) (check (let* ((<> 'wrong) (f (cut list <> <...>))) (set! <> 'ok) (f 1 2)) => '(ok 1 2)) (check (let* ((<...> 'wrong) (f (cut list <> <...>))) (set! <...> 'ok) (f 1)) => '(1 ok)) (check (let* ((<> 'ok) (f (cute list <> <...>))) (set! <> 'wrong) (f 1 2)) => '(ok 1 2)) (check (let* ((<...> 'ok) (f (cute list <> <...>))) (set! <...> 'wrong) (f 1)) => '(1 ok)) (check-report)
f6b5ebcc099784faed0253b94c72f4fa29ad0e280e57d58fa9551a05f99edac6
p1mps/roterabebot
core.clj
(ns roterabebot.core (:gen-class) (:require [cheshire.core :as json] [clojure.string :as string] [mount.core :as mount] [roterabebot.http :as http] [roterabebot.markov :as markov] [roterabebot.nlp :as nlp] [roterabebot.socket :as socket])) (def bot-ids ["U028XHG7U4B" "UFTAL8WH4"]) (def events-messages-received (atom [])) (defn clean-message [previous-message] (when previous-message (-> previous-message (string/replace #"<@U028XHG7U4B>" "") (string/replace #"\s+" " ") (string/trim)))) (defn parse-message [m] (let [e (-> (json/parse-string m true) :payload :event)] {:event_ts (:event_ts e) :message (clean-message (:text e)) :type (:type e) :user (:user e)})) (defn user-message? [message] ;; not a bot nor empty (and (= "message" (:type message)) (not (some #{(:user message)} bot-ids)) (not-empty (:message message)))) (defn bot-mention? [message] (and (not (some #{(:event_ts message)} @events-messages-received)) (= "app_mention" (:type message))) ) (defn save-message [parsed-message] (spit "training_data.txt" (str (:message parsed-message) "\n") :append true)) (defn handler [message sentences] (let [parsed-message (parse-message message)] (println "message received: " parsed-message) ;; bot's mention, we reply (when (bot-mention? parsed-message) ;; keep in memory the timestamp of received messages to not reply to messages already received (swap! events-messages-received conj (:event_ts parsed-message)) (let [reply (:reply (nlp/reply parsed-message sentences))] (println reply) (http/send-message reply) (println "removing similar sentences") ;;(nlp/reset-sentences reply) )) ;; drop some messages when there are too many in memory (swap! events-messages-received (fn [events] (if (> (count events) 100) (drop 50 events) events))) ;; if it's a user message we save it and we just regenerate all our sentences (when (user-message? parsed-message) (markov/generate-sentences (:message parsed-message)) (save-message parsed-message)))) (defn -main [& _] (let [sentences (markov/generate-sentences (slurp "training_data.txt")) sentences (partition-all 1000 1000 sentences)] (mount/start-with-args {:handler-fn handler :sentences sentences :on-close-fn socket/on-close} #'socket/ws-socket)))
null
https://raw.githubusercontent.com/p1mps/roterabebot/1518ae1afe73dd8f64c4aabf46e6e5d091f36397/src/roterabebot/core.clj
clojure
not a bot nor empty bot's mention, we reply keep in memory the timestamp of received messages to not reply to messages already received (nlp/reset-sentences reply) drop some messages when there are too many in memory if it's a user message we save it and we just regenerate all our sentences
(ns roterabebot.core (:gen-class) (:require [cheshire.core :as json] [clojure.string :as string] [mount.core :as mount] [roterabebot.http :as http] [roterabebot.markov :as markov] [roterabebot.nlp :as nlp] [roterabebot.socket :as socket])) (def bot-ids ["U028XHG7U4B" "UFTAL8WH4"]) (def events-messages-received (atom [])) (defn clean-message [previous-message] (when previous-message (-> previous-message (string/replace #"<@U028XHG7U4B>" "") (string/replace #"\s+" " ") (string/trim)))) (defn parse-message [m] (let [e (-> (json/parse-string m true) :payload :event)] {:event_ts (:event_ts e) :message (clean-message (:text e)) :type (:type e) :user (:user e)})) (defn user-message? [message] (and (= "message" (:type message)) (not (some #{(:user message)} bot-ids)) (not-empty (:message message)))) (defn bot-mention? [message] (and (not (some #{(:event_ts message)} @events-messages-received)) (= "app_mention" (:type message))) ) (defn save-message [parsed-message] (spit "training_data.txt" (str (:message parsed-message) "\n") :append true)) (defn handler [message sentences] (let [parsed-message (parse-message message)] (println "message received: " parsed-message) (when (bot-mention? parsed-message) (swap! events-messages-received conj (:event_ts parsed-message)) (let [reply (:reply (nlp/reply parsed-message sentences))] (println reply) (http/send-message reply) (println "removing similar sentences") )) (swap! events-messages-received (fn [events] (if (> (count events) 100) (drop 50 events) events))) (when (user-message? parsed-message) (markov/generate-sentences (:message parsed-message)) (save-message parsed-message)))) (defn -main [& _] (let [sentences (markov/generate-sentences (slurp "training_data.txt")) sentences (partition-all 1000 1000 sentences)] (mount/start-with-args {:handler-fn handler :sentences sentences :on-close-fn socket/on-close} #'socket/ws-socket)))
af5f81aa4732f6d47f5ff29bde5820ef397ab9ebd20d8377e4b78dbceba02401
ailisp/simple-gui
cards.lisp
(eval-when (:compile-toplevel :load-toplevel :execute) (use-package :simple-gui) (use-package :q-)) (defparameter *rows* 6) (defparameter *cols* 8) (defparameter *block-size* 90) (defparameter *kinds* 15) (defvar *empty-icon*) (defvar *current-flip* nil) (defvar *board-total-size*) (defvar *board*) (defvar *board-1d*) (defun build-data () (setf *board-total-size* (* *rows* *cols*)) (assert (evenp *board-total-size*)) (setf *board-1d* (make-array *board-total-size* :element-type 'integer)) (loop for i below (/ *board-total-size* 2) do (setf (aref *board-1d* i) (random *kinds*) (aref *board-1d* (- *board-total-size* 1 i)) (aref *board-1d* i))) (setf *board-1d* (alexandria:shuffle *board-1d*)) (setf *board* (make-array `(,*cols* ,*rows*) :displaced-to *board-1d*)) (setf *empty-icon* (q-new q-icon "./pic/empty.png"))) (defun mkstr (&rest args) "Make a string from ARGS by princ." (with-output-to-string (s) (dolist (a args) (princ a s)))) (defun build-widgets () (q-widget window (:set (:window-title "Cards Rolling-Over") (:geometry 200 200 800 600) (:layout (q-grid-layout grid)))) (simple-gui::mkstr) (loop for i below *cols* do (loop for j below *rows* do (progn (add-widget (layout (gui grid)) (let* ((data (list i j)) (button (q-tool-button - (:set (:icon-size (q-new q-size *block-size* *block-size*))) (:connect* (:clicked #'on-click-block (append data (list it))))))) button) j i 1 1))))) (defun flip-button-icon-and-delete (data) (show-button-icon data) (let ((timer (q-new q-timer))) (set-interval timer 1000) (q-connect timer :timeout #'(lambda () (stop timer) (set-visible (third data) nil))) (start timer))) (defun flip-button-icon (data) (show-button-icon data) (let ((timer (q-new q-timer))) (set-interval timer 1000) (q-connect timer :timeout #'(lambda () (stop timer) (hide-button-icon data))) (start timer))) (defun show-button-icon (data) (set-icon (third data) (q-new q-icon (mkstr "./pic/" (aref *board* (first data) (second data)) ".png")))) (defun hide-button-icon (data) (set-icon (third data) *empty-icon*)) (defun on-click-block (data) (cond ((null *current-flip*) (setf *current-flip* data) (show-button-icon data)) ((equal data *current-flip*)) ((eql (aref *board* (first data) (second data)) (aref *board* (first *current-flip*) (second *current-flip*))) (flip-button-icon-and-delete data) (flip-button-icon-and-delete *current-flip*) (setf *current-flip* nil)) (t (flip-button-icon data) (flip-button-icon *current-flip*) (setf *current-flip* nil)))) (defun main () (q-application) (build-data) (build-widgets) (show (gui window)) (exec (q-application)))
null
https://raw.githubusercontent.com/ailisp/simple-gui/35919f8cab7771f106d0fc268f47866b0fb5526d/examples/cards.lisp
lisp
(eval-when (:compile-toplevel :load-toplevel :execute) (use-package :simple-gui) (use-package :q-)) (defparameter *rows* 6) (defparameter *cols* 8) (defparameter *block-size* 90) (defparameter *kinds* 15) (defvar *empty-icon*) (defvar *current-flip* nil) (defvar *board-total-size*) (defvar *board*) (defvar *board-1d*) (defun build-data () (setf *board-total-size* (* *rows* *cols*)) (assert (evenp *board-total-size*)) (setf *board-1d* (make-array *board-total-size* :element-type 'integer)) (loop for i below (/ *board-total-size* 2) do (setf (aref *board-1d* i) (random *kinds*) (aref *board-1d* (- *board-total-size* 1 i)) (aref *board-1d* i))) (setf *board-1d* (alexandria:shuffle *board-1d*)) (setf *board* (make-array `(,*cols* ,*rows*) :displaced-to *board-1d*)) (setf *empty-icon* (q-new q-icon "./pic/empty.png"))) (defun mkstr (&rest args) "Make a string from ARGS by princ." (with-output-to-string (s) (dolist (a args) (princ a s)))) (defun build-widgets () (q-widget window (:set (:window-title "Cards Rolling-Over") (:geometry 200 200 800 600) (:layout (q-grid-layout grid)))) (simple-gui::mkstr) (loop for i below *cols* do (loop for j below *rows* do (progn (add-widget (layout (gui grid)) (let* ((data (list i j)) (button (q-tool-button - (:set (:icon-size (q-new q-size *block-size* *block-size*))) (:connect* (:clicked #'on-click-block (append data (list it))))))) button) j i 1 1))))) (defun flip-button-icon-and-delete (data) (show-button-icon data) (let ((timer (q-new q-timer))) (set-interval timer 1000) (q-connect timer :timeout #'(lambda () (stop timer) (set-visible (third data) nil))) (start timer))) (defun flip-button-icon (data) (show-button-icon data) (let ((timer (q-new q-timer))) (set-interval timer 1000) (q-connect timer :timeout #'(lambda () (stop timer) (hide-button-icon data))) (start timer))) (defun show-button-icon (data) (set-icon (third data) (q-new q-icon (mkstr "./pic/" (aref *board* (first data) (second data)) ".png")))) (defun hide-button-icon (data) (set-icon (third data) *empty-icon*)) (defun on-click-block (data) (cond ((null *current-flip*) (setf *current-flip* data) (show-button-icon data)) ((equal data *current-flip*)) ((eql (aref *board* (first data) (second data)) (aref *board* (first *current-flip*) (second *current-flip*))) (flip-button-icon-and-delete data) (flip-button-icon-and-delete *current-flip*) (setf *current-flip* nil)) (t (flip-button-icon data) (flip-button-icon *current-flip*) (setf *current-flip* nil)))) (defun main () (q-application) (build-data) (build-widgets) (show (gui window)) (exec (q-application)))
ec69e51f82dd360ad462bacfc145a24eb9c9f4661bcf53225dfb360636067994
kafka4beam/snabbkaffe
snabbkaffe_sup.erl
Copyright 2019 - 2020 Klarna Bank AB Copyright 2021 snabbkaffe contributors %% 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. @private -module(snabbkaffe_sup). -behaviour(supervisor). %% API -export([start_link/0, stop/0]). %% Supervisor callbacks -export([init/1]). -define(SERVER, ?MODULE). %%%=================================================================== %%% API functions %%%=================================================================== start_link() -> supervisor:start_link({local, ?SERVER}, ?MODULE, []). stop() -> case whereis(?MODULE) of undefined -> ok; Pid -> monitor(process, Pid), unlink(Pid), exit(Pid, shutdown), receive {'DOWN', _MRef, process, Pid, _} -> ok end end. %%%=================================================================== %%% Supervisor callbacks %%%=================================================================== init([]) -> SupFlags = #{ strategy => one_for_all , intensity => 0 }, Collector = #{ id => snabbkaffe_collector , start => {snabbkaffe_collector, start_link, []} }, Nemesis = #{ id => snabbkaffe_nemesis , start => {snabbkaffe_nemesis, start_link, []} }, {ok, {SupFlags, [Collector, Nemesis]}}. %%%=================================================================== Internal functions %%%===================================================================
null
https://raw.githubusercontent.com/kafka4beam/snabbkaffe/13bda71d0dfd2c7c23352412f365f23145b43d06/src/snabbkaffe_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 =================================================================== API functions =================================================================== =================================================================== Supervisor callbacks =================================================================== =================================================================== ===================================================================
Copyright 2019 - 2020 Klarna Bank AB Copyright 2021 snabbkaffe contributors Licensed under the Apache License , Version 2.0 ( the " License " ) ; distributed under the License is distributed on an " AS IS " BASIS , @private -module(snabbkaffe_sup). -behaviour(supervisor). -export([start_link/0, stop/0]). -export([init/1]). -define(SERVER, ?MODULE). start_link() -> supervisor:start_link({local, ?SERVER}, ?MODULE, []). stop() -> case whereis(?MODULE) of undefined -> ok; Pid -> monitor(process, Pid), unlink(Pid), exit(Pid, shutdown), receive {'DOWN', _MRef, process, Pid, _} -> ok end end. init([]) -> SupFlags = #{ strategy => one_for_all , intensity => 0 }, Collector = #{ id => snabbkaffe_collector , start => {snabbkaffe_collector, start_link, []} }, Nemesis = #{ id => snabbkaffe_nemesis , start => {snabbkaffe_nemesis, start_link, []} }, {ok, {SupFlags, [Collector, Nemesis]}}. Internal functions
39e6541f7a882ef010538e41dbd8ebc4abbb8bc2ef31f80cceb1b7f4f380a803
RBornat/jape
rewinf.ml
Copyright ( C ) 2003 - 19 This file is part of the proof engine , which is part of . is free software ; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation ; either version 2 of the License , or ( at your option ) any later version . is distributed in the hope that it will be useful , but WITHOUT ANY WARRANTY ; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the GNU General Public License for more details . You should have received a copy of the GNU General Public License along with ; if not , write to the Free Software Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 USA ( or look at ) . Copyright (C) 2003-19 Richard Bornat & Bernard Sufrin This file is part of the jape proof engine, which is part of jape. Jape is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. Jape is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with jape; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA (or look at ). *) open Stringfuns open Termstring open Listfuns open Optionfuns open Termfuns type term = Termtype.term and vid = Termtype.vid (* see rewrite.sml for an explanation of this data structure *) type rewinf = Rewinf of (term list * vid list * int list * int option) let nullrewinf = Rewinf ([], [], [], None) let mkrewinf v = Rewinf v let rec rawinf_of_rew = fun (Rewinf r) -> r let rec rewinf_vars = fun (Rewinf (vars, _, _, _)) -> vars let rec rewinf_uVIDs = fun (Rewinf (_, uVIDs, _, _)) -> uVIDs let rec rewinf_badres = fun (Rewinf (_, _, badres, _)) -> badres let rec rewinf_psig = fun (Rewinf (_, _, _, psig)) -> psig let rec rewinf_setvars = fun (Rewinf (_, uVIDs, badres, psig)) vars -> Rewinf (vars, uVIDs, badres, psig) let rec rewinf_setuVIDs = fun (Rewinf (vars, _, badres, psig)) uVIDs -> Rewinf (vars, uVIDs, badres, psig) let rec rewinf_setbadres = fun (Rewinf (vars, uVIDs, _, psig)) badres -> Rewinf (vars, uVIDs, badres, psig) let rec rewinf_setpsig = fun (Rewinf (vars, uVIDs, badres, _)) psig -> Rewinf (vars, uVIDs, badres, psig) let rec rewinf_addvars = fun (Rewinf (vars, uVIDs, badres, psig)) vars' -> Rewinf (vars' @ vars, uVIDs, badres, psig) let rec rewinf_adduVIDs = fun (Rewinf (vars, uVIDs, badres, psig)) uVIDs' -> Rewinf (vars, uVIDs' @ uVIDs, badres, psig) let rec rewinf_addbadres = fun (Rewinf (vars, uVIDs, badres, psig)) badres' -> Rewinf (vars, uVIDs, badres' @ badres, psig) let rec string_of_rewinf = fun (Rewinf r) -> "Rewinf" ^ string_of_quadruple string_of_termlist (bracketed_string_of_list string_of_vid ",") (bracketed_string_of_list string_of_int ",") (string_of_option string_of_int) "," r let rec rewinf_merge = fun (Rewinf (allvars, uVIDs, badres, psig), Rewinf (allvars', uVIDs', badres', psig')) -> Rewinf (mergevars allvars allvars', mergeVIDs uVIDs uVIDs', sortedmerge (<) badres badres', (match psig, psig' with Some n, Some n' -> Some (min n n') | Some _, None -> psig | _ -> psig'))
null
https://raw.githubusercontent.com/RBornat/jape/afe9f207e89e965636b43ef8fad38fd1f69737ae/distrib/camlengine/rewinf.ml
ocaml
see rewrite.sml for an explanation of this data structure
Copyright ( C ) 2003 - 19 This file is part of the proof engine , which is part of . is free software ; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation ; either version 2 of the License , or ( at your option ) any later version . is distributed in the hope that it will be useful , but WITHOUT ANY WARRANTY ; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the GNU General Public License for more details . You should have received a copy of the GNU General Public License along with ; if not , write to the Free Software Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 USA ( or look at ) . Copyright (C) 2003-19 Richard Bornat & Bernard Sufrin This file is part of the jape proof engine, which is part of jape. Jape is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. Jape is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with jape; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA (or look at ). *) open Stringfuns open Termstring open Listfuns open Optionfuns open Termfuns type term = Termtype.term and vid = Termtype.vid type rewinf = Rewinf of (term list * vid list * int list * int option) let nullrewinf = Rewinf ([], [], [], None) let mkrewinf v = Rewinf v let rec rawinf_of_rew = fun (Rewinf r) -> r let rec rewinf_vars = fun (Rewinf (vars, _, _, _)) -> vars let rec rewinf_uVIDs = fun (Rewinf (_, uVIDs, _, _)) -> uVIDs let rec rewinf_badres = fun (Rewinf (_, _, badres, _)) -> badres let rec rewinf_psig = fun (Rewinf (_, _, _, psig)) -> psig let rec rewinf_setvars = fun (Rewinf (_, uVIDs, badres, psig)) vars -> Rewinf (vars, uVIDs, badres, psig) let rec rewinf_setuVIDs = fun (Rewinf (vars, _, badres, psig)) uVIDs -> Rewinf (vars, uVIDs, badres, psig) let rec rewinf_setbadres = fun (Rewinf (vars, uVIDs, _, psig)) badres -> Rewinf (vars, uVIDs, badres, psig) let rec rewinf_setpsig = fun (Rewinf (vars, uVIDs, badres, _)) psig -> Rewinf (vars, uVIDs, badres, psig) let rec rewinf_addvars = fun (Rewinf (vars, uVIDs, badres, psig)) vars' -> Rewinf (vars' @ vars, uVIDs, badres, psig) let rec rewinf_adduVIDs = fun (Rewinf (vars, uVIDs, badres, psig)) uVIDs' -> Rewinf (vars, uVIDs' @ uVIDs, badres, psig) let rec rewinf_addbadres = fun (Rewinf (vars, uVIDs, badres, psig)) badres' -> Rewinf (vars, uVIDs, badres' @ badres, psig) let rec string_of_rewinf = fun (Rewinf r) -> "Rewinf" ^ string_of_quadruple string_of_termlist (bracketed_string_of_list string_of_vid ",") (bracketed_string_of_list string_of_int ",") (string_of_option string_of_int) "," r let rec rewinf_merge = fun (Rewinf (allvars, uVIDs, badres, psig), Rewinf (allvars', uVIDs', badres', psig')) -> Rewinf (mergevars allvars allvars', mergeVIDs uVIDs uVIDs', sortedmerge (<) badres badres', (match psig, psig' with Some n, Some n' -> Some (min n n') | Some _, None -> psig | _ -> psig'))
db42a072304cbc6e91c4ac3d9a9b63381a9477c5dd3e0d47967d69255789b102
typeclasses/haskell-phrasebook
test-logging.hs
import qualified Data.Map.Strict as Map main = propertyMain $ withTests 1 $ property do let levels = ["INFO", "ERROR"] (output, fileOutputs) <- liftIO $ flip runContT pure do files <- Map.fromList <$> for levels \l -> do f <- ContT \c -> withSystemTempFile (l <> ".txt") \fp h -> hClose h *> c fp pure (l, f) output <- exeStdout (phrasebook "logging"){ exeEnv = files } fileOutputs <- for files readFileText pure (output, fileOutputs) strLines output === [ "(Boot info) Starting", "(App info) Application started" ] fmap lines fileOutputs === [("INFO", [ "Application started" ]), ("ERROR", [])]
null
https://raw.githubusercontent.com/typeclasses/haskell-phrasebook/2b0aa44ef6f6e9745c51ed47b4e59ff704346c87/tests/test-logging.hs
haskell
import qualified Data.Map.Strict as Map main = propertyMain $ withTests 1 $ property do let levels = ["INFO", "ERROR"] (output, fileOutputs) <- liftIO $ flip runContT pure do files <- Map.fromList <$> for levels \l -> do f <- ContT \c -> withSystemTempFile (l <> ".txt") \fp h -> hClose h *> c fp pure (l, f) output <- exeStdout (phrasebook "logging"){ exeEnv = files } fileOutputs <- for files readFileText pure (output, fileOutputs) strLines output === [ "(Boot info) Starting", "(App info) Application started" ] fmap lines fileOutputs === [("INFO", [ "Application started" ]), ("ERROR", [])]
555f434a86bc5cbd7689a0cc52e1cce034045b6d076989933a501f6778c468b9
themetaschemer/malt
test-E-argmax.rkt
(module+ test (require (only-in "../tensors.rkt" tensor)) (let ((y (tensor 0.0 0.0 1.0 0.0))) (check-ρ-∇ (d-argmax y) 2.0 (list (tensor 0.0 0.0 0.0 0.0)))) (let ((y (tensor (tensor 0.0 0.0 1.0 0.0) (tensor 0.0 1.0 0.0 0.0) (tensor 1.0 0.0 0.0 0.0) (tensor 0.0 0.0 0.0 1.0)))) (check-ρ-∇ (d-argmax y) (tensor 2.0 1.0 0.0 3.0) (list (tensor (tensor 0.0 0.0 0.0 0.0) (tensor 0.0 0.0 0.0 0.0) (tensor 0.0 0.0 0.0 0.0) (tensor 0.0 0.0 0.0 0.0))))))
null
https://raw.githubusercontent.com/themetaschemer/malt/78a04063a5a343f5cf4332e84da0e914cdb4d347/flat-tensors/ext-ops/test/test-E-argmax.rkt
racket
(module+ test (require (only-in "../tensors.rkt" tensor)) (let ((y (tensor 0.0 0.0 1.0 0.0))) (check-ρ-∇ (d-argmax y) 2.0 (list (tensor 0.0 0.0 0.0 0.0)))) (let ((y (tensor (tensor 0.0 0.0 1.0 0.0) (tensor 0.0 1.0 0.0 0.0) (tensor 1.0 0.0 0.0 0.0) (tensor 0.0 0.0 0.0 1.0)))) (check-ρ-∇ (d-argmax y) (tensor 2.0 1.0 0.0 3.0) (list (tensor (tensor 0.0 0.0 0.0 0.0) (tensor 0.0 0.0 0.0 0.0) (tensor 0.0 0.0 0.0 0.0) (tensor 0.0 0.0 0.0 0.0))))))
0f6c895c7e83b7ae510fd09047732c61c88d0300adde6d2b3319676e3537d5bb
janestreet/lwt-async
lwt_pool.mli
Lwt * * Copyright ( C ) 2008 * 2012 * Laboratoire PPS - CNRS Université Paris Diderot * * 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 , with linking exceptions ; * either version 2.1 of the License , or ( at your option ) any later version . * See COPYING file for details . * * 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 . * * You should have received a copy of the GNU Lesser General Public License * along with this program ; if not , write to the Free Software * Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , MA 02111 - 1307 , USA . * * Copyright (C) 2008 Jérôme Vouillon * 2012 Jérémie Dimino * Laboratoire PPS - CNRS Université Paris Diderot * * 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, with linking exceptions; * either version 2.1 of the License, or (at your option) any later version. * See COPYING file for details. * * 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. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *) (** Creating pools (for example pools of connections to a database). *) (** Instead of creating a new connection each time you need one, keep a pool of opened connections and reuse opened connections that are free. *) type 'a t (** Type of pools *) val create : int -> ?check : ('a -> (bool -> unit) -> unit) -> ?validate : ('a -> bool Lwt.t) -> (unit -> 'a Lwt.t) -> 'a t (** [create n ?check ?validate f] creates a new pool with at most [n] members. [f] is the function to use to create a new pool member. An element of the pool is validated by the optional [validate] function before its {!use}. Invalid elements are re-created. The optional function [check] is called after a [use] of an element failed. It must call its argument excatly one with [true] if the pool member is still valid and [false] otherwise. *) val use : 'a t -> ('a -> 'b Lwt.t) -> 'b Lwt.t * [ use p f ] takes one free member of the pool [ p ] and gives it to the function [ f ] . the function [f]. *)
null
https://raw.githubusercontent.com/janestreet/lwt-async/c738e6202c1c7409e079e513c7bdf469f7f9984c/src/core/lwt_pool.mli
ocaml
* Creating pools (for example pools of connections to a database). * Instead of creating a new connection each time you need one, keep a pool of opened connections and reuse opened connections that are free. * Type of pools * [create n ?check ?validate f] creates a new pool with at most [n] members. [f] is the function to use to create a new pool member. An element of the pool is validated by the optional [validate] function before its {!use}. Invalid elements are re-created. The optional function [check] is called after a [use] of an element failed. It must call its argument excatly one with [true] if the pool member is still valid and [false] otherwise.
Lwt * * Copyright ( C ) 2008 * 2012 * Laboratoire PPS - CNRS Université Paris Diderot * * 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 , with linking exceptions ; * either version 2.1 of the License , or ( at your option ) any later version . * See COPYING file for details . * * 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 . * * You should have received a copy of the GNU Lesser General Public License * along with this program ; if not , write to the Free Software * Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , MA 02111 - 1307 , USA . * * Copyright (C) 2008 Jérôme Vouillon * 2012 Jérémie Dimino * Laboratoire PPS - CNRS Université Paris Diderot * * 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, with linking exceptions; * either version 2.1 of the License, or (at your option) any later version. * See COPYING file for details. * * 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. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *) type 'a t val create : int -> ?check : ('a -> (bool -> unit) -> unit) -> ?validate : ('a -> bool Lwt.t) -> (unit -> 'a Lwt.t) -> 'a t val use : 'a t -> ('a -> 'b Lwt.t) -> 'b Lwt.t * [ use p f ] takes one free member of the pool [ p ] and gives it to the function [ f ] . the function [f]. *)
12ef367c9944e341b16bdc10fce5711972816f7f6642aed191bbc5345441d3ba
sgimenez/laby
level.mli
* Copyright ( C ) 2007 - 2014 The laby team * You have permission to copy , modify , and redistribute under the * terms of the GPL-3.0 . For full license terms , see gpl-3.0.txt . * Copyright (C) 2007-2014 The laby team * You have permission to copy, modify, and redistribute under the * terms of the GPL-3.0. For full license terms, see gpl-3.0.txt. *) type t (* type of levels *) val load : string -> t (* loads a given file *) val size : t -> int * int (* width and height of the level *) val title : t -> string val comment : t -> string val help : t -> string val generate : t -> State.t (* generates a initial labyrinth state for the given level *) val dummy : t
null
https://raw.githubusercontent.com/sgimenez/laby/47f9560eb827790d26900bb553719afb4b0554ea/src/level.mli
ocaml
type of levels loads a given file width and height of the level generates a initial labyrinth state for the given level
* Copyright ( C ) 2007 - 2014 The laby team * You have permission to copy , modify , and redistribute under the * terms of the GPL-3.0 . For full license terms , see gpl-3.0.txt . * Copyright (C) 2007-2014 The laby team * You have permission to copy, modify, and redistribute under the * terms of the GPL-3.0. For full license terms, see gpl-3.0.txt. *) type t val load : string -> t val size : t -> int * int val title : t -> string val comment : t -> string val help : t -> string val generate : t -> State.t val dummy : t
1a1f750a11f93e688a47c6dbc356f50918a8888323da8ffd57ec2c3bdef63af8
input-output-hk/project-icarus-importer
Util.hs
| Pending tx utils which db depends on module Pos.Wallet.Web.Pending.Util ( incPtxSubmitTimingPure , mkPtxSubmitTiming , ptxMarkAcknowledgedPure , cancelApplyingPtx , resetFailedPtx , sortPtxsChrono , allPendingAddresses , nonConfirmedTransactions ) where import Universum import Control.Lens ((*=), (+=), (+~), (<<*=), (<<.=)) import qualified Data.Set as Set import Data.Reflection (give) import Pos.Client.Txp.Util (PendingAddresses (..)) import Pos.Core.Common (Address) import Pos.Core (ProtocolConstants(..)) import Pos.Core.Slotting (FlatSlotId, SlotId, flatSlotId) import Pos.Crypto (WithHash (..)) import Pos.Txp (Tx (..), TxAux (..), TxOut (..), topsortTxs) import Pos.Util.Chrono (OldestFirst (..)) import Pos.Wallet.Web.Pending.Types (PendingTx (..), PtxCondition (..), PtxCondition (..), PtxSubmitTiming (..), pstNextDelay, pstNextSlot, ptxPeerAck, ptxSubmitTiming) mkPtxSubmitTiming :: ProtocolConstants -> SlotId -> PtxSubmitTiming mkPtxSubmitTiming pc creationSlot = give pc $ PtxSubmitTiming { _pstNextSlot = creationSlot & flatSlotId +~ initialSubmitDelay , _pstNextDelay = 1 } where initialSubmitDelay = 3 :: FlatSlotId -- | Sort pending transactions as close as possible to chronological order. sortPtxsChrono :: [PendingTx] -> OldestFirst [] PendingTx sortPtxsChrono = OldestFirst . sortWith _ptxCreationSlot . tryTopsort where tryTopsort txs = fromMaybe txs $ topsortTxs wHash txs wHash PendingTx{..} = WithHash (taTx _ptxTxAux) _ptxTxId incPtxSubmitTimingPure :: ProtocolConstants -> PtxSubmitTiming -> PtxSubmitTiming incPtxSubmitTimingPure pc = give pc $ execState $ do curDelay <- pstNextDelay <<*= 2 pstNextSlot . flatSlotId += curDelay ptxMarkAcknowledgedPure :: PendingTx -> PendingTx ptxMarkAcknowledgedPure = execState $ do wasAcked <- ptxPeerAck <<.= True unless wasAcked $ ptxSubmitTiming . pstNextDelay *= 8 -- | If given pending transaction is not yet confirmed, cancels it. cancelApplyingPtx :: () => PendingTx -> PendingTx cancelApplyingPtx ptx@PendingTx{..} | PtxApplying poolInfo <- _ptxCond = ptx { _ptxCond = PtxWontApply reason poolInfo , _ptxPeerAck = False } | otherwise = ptx where reason = "Canceled manually" -- | If given transaction is in 'PtxWontApply' condition, sets its condition to ' PtxApplying ' . This allows " stuck " transactions to be resubmitted -- again. -- -- Has no effect for transactions in other conditions. resetFailedPtx :: ProtocolConstants -> SlotId -> PendingTx -> PendingTx resetFailedPtx pc curSlot ptx@PendingTx{..} | PtxWontApply _ poolInfo <- _ptxCond = ptx { _ptxCond = PtxApplying poolInfo , _ptxSubmitTiming = mkPtxSubmitTiming pc curSlot } | otherwise = ptx -- | Returns the full list of "pending addresses", which are @output@ addresses -- associated to transactions not yet persisted in the blockchain. allPendingAddresses :: [PendingTx] -> PendingAddresses allPendingAddresses = PendingAddresses . Set.unions . map grabTxOutputs . nonConfirmedTransactions where grabTxOutputs :: PendingTx -> Set.Set Address grabTxOutputs PendingTx{..} = let (TxAux tx _) = _ptxTxAux (UnsafeTx _ outputs _) = tx in Set.fromList $ map (\(TxOut a _) -> a) (toList outputs) | Filters the input ' [ ] ' to choose only the ones which are not -- yet persisted in the blockchain. nonConfirmedTransactions :: [PendingTx] -> [PendingTx] nonConfirmedTransactions = filter isPending where | Is this ' ' really pending ? isPending :: PendingTx -> Bool isPending PendingTx{..} = case _ptxCond of PtxInNewestBlocks _ -> False PtxPersisted -> False _ -> True
null
https://raw.githubusercontent.com/input-output-hk/project-icarus-importer/36342f277bcb7f1902e677a02d1ce93e4cf224f0/wallet/src/Pos/Wallet/Web/Pending/Util.hs
haskell
| Sort pending transactions as close as possible to chronological order. | If given pending transaction is not yet confirmed, cancels it. | If given transaction is in 'PtxWontApply' condition, sets its condition again. Has no effect for transactions in other conditions. | Returns the full list of "pending addresses", which are @output@ addresses associated to transactions not yet persisted in the blockchain. yet persisted in the blockchain.
| Pending tx utils which db depends on module Pos.Wallet.Web.Pending.Util ( incPtxSubmitTimingPure , mkPtxSubmitTiming , ptxMarkAcknowledgedPure , cancelApplyingPtx , resetFailedPtx , sortPtxsChrono , allPendingAddresses , nonConfirmedTransactions ) where import Universum import Control.Lens ((*=), (+=), (+~), (<<*=), (<<.=)) import qualified Data.Set as Set import Data.Reflection (give) import Pos.Client.Txp.Util (PendingAddresses (..)) import Pos.Core.Common (Address) import Pos.Core (ProtocolConstants(..)) import Pos.Core.Slotting (FlatSlotId, SlotId, flatSlotId) import Pos.Crypto (WithHash (..)) import Pos.Txp (Tx (..), TxAux (..), TxOut (..), topsortTxs) import Pos.Util.Chrono (OldestFirst (..)) import Pos.Wallet.Web.Pending.Types (PendingTx (..), PtxCondition (..), PtxCondition (..), PtxSubmitTiming (..), pstNextDelay, pstNextSlot, ptxPeerAck, ptxSubmitTiming) mkPtxSubmitTiming :: ProtocolConstants -> SlotId -> PtxSubmitTiming mkPtxSubmitTiming pc creationSlot = give pc $ PtxSubmitTiming { _pstNextSlot = creationSlot & flatSlotId +~ initialSubmitDelay , _pstNextDelay = 1 } where initialSubmitDelay = 3 :: FlatSlotId sortPtxsChrono :: [PendingTx] -> OldestFirst [] PendingTx sortPtxsChrono = OldestFirst . sortWith _ptxCreationSlot . tryTopsort where tryTopsort txs = fromMaybe txs $ topsortTxs wHash txs wHash PendingTx{..} = WithHash (taTx _ptxTxAux) _ptxTxId incPtxSubmitTimingPure :: ProtocolConstants -> PtxSubmitTiming -> PtxSubmitTiming incPtxSubmitTimingPure pc = give pc $ execState $ do curDelay <- pstNextDelay <<*= 2 pstNextSlot . flatSlotId += curDelay ptxMarkAcknowledgedPure :: PendingTx -> PendingTx ptxMarkAcknowledgedPure = execState $ do wasAcked <- ptxPeerAck <<.= True unless wasAcked $ ptxSubmitTiming . pstNextDelay *= 8 cancelApplyingPtx :: () => PendingTx -> PendingTx cancelApplyingPtx ptx@PendingTx{..} | PtxApplying poolInfo <- _ptxCond = ptx { _ptxCond = PtxWontApply reason poolInfo , _ptxPeerAck = False } | otherwise = ptx where reason = "Canceled manually" to ' PtxApplying ' . This allows " stuck " transactions to be resubmitted resetFailedPtx :: ProtocolConstants -> SlotId -> PendingTx -> PendingTx resetFailedPtx pc curSlot ptx@PendingTx{..} | PtxWontApply _ poolInfo <- _ptxCond = ptx { _ptxCond = PtxApplying poolInfo , _ptxSubmitTiming = mkPtxSubmitTiming pc curSlot } | otherwise = ptx allPendingAddresses :: [PendingTx] -> PendingAddresses allPendingAddresses = PendingAddresses . Set.unions . map grabTxOutputs . nonConfirmedTransactions where grabTxOutputs :: PendingTx -> Set.Set Address grabTxOutputs PendingTx{..} = let (TxAux tx _) = _ptxTxAux (UnsafeTx _ outputs _) = tx in Set.fromList $ map (\(TxOut a _) -> a) (toList outputs) | Filters the input ' [ ] ' to choose only the ones which are not nonConfirmedTransactions :: [PendingTx] -> [PendingTx] nonConfirmedTransactions = filter isPending where | Is this ' ' really pending ? isPending :: PendingTx -> Bool isPending PendingTx{..} = case _ptxCond of PtxInNewestBlocks _ -> False PtxPersisted -> False _ -> True
0692c0f7ccaa04fe25040926f57d4e4e13a9186f459088daf465984b399bd3f0
yi-editor/yi
Tag.hs
{-# LANGUAGE CPP #-} {-# LANGUAGE DeriveDataTypeable #-} # LANGUAGE DeriveGeneric # # LANGUAGE FlexibleContexts # {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TemplateHaskell #-} {-# OPTIONS_HADDOCK show-extensions #-} # LANGUAGE GeneralizedNewtypeDeriving # -- | -- Module : Yi.Tag -- License : GPL-2 -- Maintainer : -- Stability : experimental -- Portability : portable -- A module for CTags integration . Note that this reads the ‘ tags ’ -- file produced by @hasktags@, not the ‘TAGS’ file which uses a -- different format (etags). module Yi.Tag ( lookupTag , importTagTable , hintTags , completeTag , Tag(..) , unTag' , TagTable(..) , getTags , setTags , resetTags , tagsFileList , readCTags ) where import GHC.Generics (Generic) import Lens.Micro.Platform (makeLenses) import Data.Binary (Binary) import qualified Data.ByteString as BS (readFile) import Data.Default (Default, def) import qualified Data.Foldable as F (concat) import Data.Map (Map, fromListWith, keys, lookup) import Data.Maybe (mapMaybe) import qualified Data.Text as T (Text, append, isPrefixOf, lines, unpack, words) import qualified Data.Text.Encoding as E (decodeUtf8) import qualified Data.Text.Read as R (decimal) import qualified Yi.CompletionTree as CT import System.FilePath (takeDirectory, takeFileName, (</>)) import System.FriendlyPath (expandTilda) import Yi.Config.Simple.Types (Field, customVariable) import Yi.Editor (EditorM, getEditorDyn, putEditorDyn) import Yi.Types (YiConfigVariable, YiVariable) newtype TagsFileList = TagsFileList { _unTagsFileList :: [FilePath] } instance Default TagsFileList where def = TagsFileList ["tags"] instance YiConfigVariable TagsFileList makeLenses ''TagsFileList tagsFileList :: Field [FilePath] tagsFileList = customVariable . unTagsFileList newtype Tags = Tags (Maybe TagTable) deriving (Binary) instance Default Tags where def = Tags Nothing instance YiVariable Tags newtype Tag = Tag { _unTag :: T.Text } deriving (Show, Eq, Ord, Binary) unTag' :: Tag -> T.Text unTag' = _unTag data TagTable = TagTable { tagFileName :: FilePath -- ^ local name of the tag file TODO : reload if this file is changed , tagBaseDir :: FilePath -- ^ path to the tag file directory -- tags are relative to this path , tagFileMap :: Map Tag [(FilePath, Int)] -- ^ map from tags to files , tagCompletionTree :: CT.CompletionTree T.Text -- ^ trie to speed up tag hinting } deriving (Generic) -- | Find the location of a tag using the tag table. -- Returns a full path and line number lookupTag :: Tag -> TagTable -> [(FilePath, Int)] lookupTag tag tagTable = do (file, line) <- F.concat . Data.Map.lookup tag $ tagFileMap tagTable return (tagBaseDir tagTable </> file, line) | Super simple parsing CTag format 1 parsing algorithm TODO : support search patterns in addition to lineno readCTags :: T.Text -> Map Tag [(FilePath, Int)] readCTags = fromListWith (++) . mapMaybe (parseTagLine . T.words) . T.lines where parseTagLine (tag:tagfile:lineno:_) = -- remove ctag control lines if "!_TAG_" `T.isPrefixOf` tag then Nothing else Just (Tag tag, [(T.unpack tagfile, getLineNumber lineno)]) where getLineNumber = (\(Right x) -> x) . fmap fst . R.decimal parseTagLine _ = Nothing -- | Read in a tag file from the system importTagTable :: FilePath -> IO TagTable importTagTable filename = do friendlyName <- expandTilda filename tagStr <- E.decodeUtf8 <$> BS.readFile friendlyName let cts = readCTags tagStr return TagTable { tagFileName = takeFileName filename , tagBaseDir = takeDirectory filename , tagFileMap = cts , tagCompletionTree = CT.fromList . map (_unTag) $ keys cts } | Gives all the possible expanded tags that could match a given @prefix@ hintTags :: TagTable -> T.Text -> [T.Text] hintTags tags prefix = map (prefix `T.append`) sufs where sufs :: [T.Text] sufs = CT.toList (CT.update (tagCompletionTree tags) prefix) -- | Extends the string to the longest certain length completeTag :: TagTable -> T.Text -> T.Text completeTag tags prefix = prefix `T.append` fst (CT.complete (CT.update (tagCompletionTree tags) prefix)) -- --------------------------------------------------------------------- Direct access interface to TagTable . | Set a new TagTable setTags :: TagTable -> EditorM () setTags = putEditorDyn . Tags . Just | Reset the TagTable resetTags :: EditorM () resetTags = putEditorDyn $ Tags Nothing -- | Get the currently registered tag table getTags :: EditorM (Maybe TagTable) getTags = do Tags t <- getEditorDyn return t instance Binary TagTable
null
https://raw.githubusercontent.com/yi-editor/yi/58c239e3a77cef8f4f77e94677bd6a295f585f5f/yi-core/src/Yi/Tag.hs
haskell
# LANGUAGE CPP # # LANGUAGE DeriveDataTypeable # # LANGUAGE OverloadedStrings # # LANGUAGE TemplateHaskell # # OPTIONS_HADDOCK show-extensions # | Module : Yi.Tag License : GPL-2 Maintainer : Stability : experimental Portability : portable file produced by @hasktags@, not the ‘TAGS’ file which uses a different format (etags). ^ local name of the tag file ^ path to the tag file directory tags are relative to this path ^ map from tags to files ^ trie to speed up tag hinting | Find the location of a tag using the tag table. Returns a full path and line number remove ctag control lines | Read in a tag file from the system | Extends the string to the longest certain length --------------------------------------------------------------------- | Get the currently registered tag table
# LANGUAGE DeriveGeneric # # LANGUAGE FlexibleContexts # # LANGUAGE GeneralizedNewtypeDeriving # A module for CTags integration . Note that this reads the ‘ tags ’ module Yi.Tag ( lookupTag , importTagTable , hintTags , completeTag , Tag(..) , unTag' , TagTable(..) , getTags , setTags , resetTags , tagsFileList , readCTags ) where import GHC.Generics (Generic) import Lens.Micro.Platform (makeLenses) import Data.Binary (Binary) import qualified Data.ByteString as BS (readFile) import Data.Default (Default, def) import qualified Data.Foldable as F (concat) import Data.Map (Map, fromListWith, keys, lookup) import Data.Maybe (mapMaybe) import qualified Data.Text as T (Text, append, isPrefixOf, lines, unpack, words) import qualified Data.Text.Encoding as E (decodeUtf8) import qualified Data.Text.Read as R (decimal) import qualified Yi.CompletionTree as CT import System.FilePath (takeDirectory, takeFileName, (</>)) import System.FriendlyPath (expandTilda) import Yi.Config.Simple.Types (Field, customVariable) import Yi.Editor (EditorM, getEditorDyn, putEditorDyn) import Yi.Types (YiConfigVariable, YiVariable) newtype TagsFileList = TagsFileList { _unTagsFileList :: [FilePath] } instance Default TagsFileList where def = TagsFileList ["tags"] instance YiConfigVariable TagsFileList makeLenses ''TagsFileList tagsFileList :: Field [FilePath] tagsFileList = customVariable . unTagsFileList newtype Tags = Tags (Maybe TagTable) deriving (Binary) instance Default Tags where def = Tags Nothing instance YiVariable Tags newtype Tag = Tag { _unTag :: T.Text } deriving (Show, Eq, Ord, Binary) unTag' :: Tag -> T.Text unTag' = _unTag data TagTable = TagTable { tagFileName :: FilePath TODO : reload if this file is changed , tagBaseDir :: FilePath , tagFileMap :: Map Tag [(FilePath, Int)] , tagCompletionTree :: CT.CompletionTree T.Text } deriving (Generic) lookupTag :: Tag -> TagTable -> [(FilePath, Int)] lookupTag tag tagTable = do (file, line) <- F.concat . Data.Map.lookup tag $ tagFileMap tagTable return (tagBaseDir tagTable </> file, line) | Super simple parsing CTag format 1 parsing algorithm TODO : support search patterns in addition to lineno readCTags :: T.Text -> Map Tag [(FilePath, Int)] readCTags = fromListWith (++) . mapMaybe (parseTagLine . T.words) . T.lines where parseTagLine (tag:tagfile:lineno:_) = if "!_TAG_" `T.isPrefixOf` tag then Nothing else Just (Tag tag, [(T.unpack tagfile, getLineNumber lineno)]) where getLineNumber = (\(Right x) -> x) . fmap fst . R.decimal parseTagLine _ = Nothing importTagTable :: FilePath -> IO TagTable importTagTable filename = do friendlyName <- expandTilda filename tagStr <- E.decodeUtf8 <$> BS.readFile friendlyName let cts = readCTags tagStr return TagTable { tagFileName = takeFileName filename , tagBaseDir = takeDirectory filename , tagFileMap = cts , tagCompletionTree = CT.fromList . map (_unTag) $ keys cts } | Gives all the possible expanded tags that could match a given @prefix@ hintTags :: TagTable -> T.Text -> [T.Text] hintTags tags prefix = map (prefix `T.append`) sufs where sufs :: [T.Text] sufs = CT.toList (CT.update (tagCompletionTree tags) prefix) completeTag :: TagTable -> T.Text -> T.Text completeTag tags prefix = prefix `T.append` fst (CT.complete (CT.update (tagCompletionTree tags) prefix)) Direct access interface to TagTable . | Set a new TagTable setTags :: TagTable -> EditorM () setTags = putEditorDyn . Tags . Just | Reset the TagTable resetTags :: EditorM () resetTags = putEditorDyn $ Tags Nothing getTags :: EditorM (Maybe TagTable) getTags = do Tags t <- getEditorDyn return t instance Binary TagTable
4fe4c339819a2601bcd9bb4886ec8affbf4c90f0b50f7da6e3eae553e0448473
scicloj/clj-djl
cv.clj
(ns clj-djl.modality.cv (:import [ai.djl.modality.cv ImageFactory])) (defn download-image-from [url] (.fromUrl (ImageFactory/getInstance) url))
null
https://raw.githubusercontent.com/scicloj/clj-djl/f089b10a22c869c0e643d456dc9bbad8233bd6ac/src/clj_djl/modality/cv.clj
clojure
(ns clj-djl.modality.cv (:import [ai.djl.modality.cv ImageFactory])) (defn download-image-from [url] (.fromUrl (ImageFactory/getInstance) url))
5046f4c2e7c2dd1e8f277611efed1c92b3040a0c7fdf9e9d267ecdc2c55722be
ivan-m/graphviz
Values.hs
# LANGUAGE CPP , OverloadedStrings # {-# OPTIONS_HADDOCK hide #-} | Module : Data . GraphViz . Attributes . Values Description : Values for use with the Attribute data type Copyright : ( c ) License : 3 - Clause BSD - style Maintainer : Defined to have smaller modules and thus faster compilation times . Module : Data.GraphViz.Attributes.Values Description : Values for use with the Attribute data type Copyright : (c) Ivan Lazar Miljenovic License : 3-Clause BSD-style Maintainer : Defined to have smaller modules and thus faster compilation times. -} module Data.GraphViz.Attributes.Values where import qualified Data.GraphViz.Attributes.HTML as Html import Data.GraphViz.Attributes.Internal import Data.GraphViz.Internal.State (getLayerListSep, getLayerSep, setLayerListSep, setLayerSep) import Data.GraphViz.Internal.Util (bool, stringToInt) import Data.GraphViz.Parsing import Data.GraphViz.Printing import Data.List (intercalate) import Data.Maybe (isJust) import Data.Text.Lazy (Text) import qualified Data.Text.Lazy as T import Data.Word (Word16) import System.FilePath (searchPathSeparator, splitSearchPath) #if !MIN_VERSION_base (4,13,0) import Data.Monoid ((<>)) #endif -- ----------------------------------------------------------------------------- | Some ' Attribute 's ( mainly label - like ones ) take a ' String ' argument that allows for extra escape codes . This library does n't do any extra checks or special parsing for these escape codes , but usage of ' EscString ' rather than ' Text ' indicates that the Graphviz tools will recognise these extra escape codes for these ' Attribute 's . The extra escape codes include ( note that these are all Strings ): [ @\\N@ ] Replace with the name of the node ( for Node ' Attribute 's ) . [ @\\G@ ] Replace with the name of the graph ( for Node ' Attribute 's ) or the name of the graph or cluster , whichever is applicable ( for Graph , Cluster and Edge ' Attribute 's ) . [ ] Replace with the name of the edge , formed by the two adjoining nodes and the edge type ( for Edge ' Attribute 's ) . [ @\\T@ ] Replace with the name of the tail node ( for Edge ' Attribute 's ) . [ @\\H@ ] Replace with the name of the head node ( for Edge ' Attribute 's ) . [ @\\L@ ] Replace with the object 's label ( for all ' Attribute 's ) . Also , if the ' Attribute ' in question is ' Label ' , ' HeadLabel ' or ' TailLabel ' , then , @\\l@ and @\\r@ split the label into lines centered , left - justified and right - justified respectively . Some 'Attribute's (mainly label-like ones) take a 'String' argument that allows for extra escape codes. This library doesn't do any extra checks or special parsing for these escape codes, but usage of 'EscString' rather than 'Text' indicates that the Graphviz tools will recognise these extra escape codes for these 'Attribute's. The extra escape codes include (note that these are all Strings): [@\\N@] Replace with the name of the node (for Node 'Attribute's). [@\\G@] Replace with the name of the graph (for Node 'Attribute's) or the name of the graph or cluster, whichever is applicable (for Graph, Cluster and Edge 'Attribute's). [@\\E@] Replace with the name of the edge, formed by the two adjoining nodes and the edge type (for Edge 'Attribute's). [@\\T@] Replace with the name of the tail node (for Edge 'Attribute's). [@\\H@] Replace with the name of the head node (for Edge 'Attribute's). [@\\L@] Replace with the object's label (for all 'Attribute's). Also, if the 'Attribute' in question is 'Label', 'HeadLabel' or 'TailLabel', then @\\n@, @\\l@ and @\\r@ split the label into lines centered, left-justified and right-justified respectively. -} type EscString = Text -- ----------------------------------------------------------------------------- -- | Should only have 2D points (i.e. created with 'createPoint'). data Rect = Rect Point Point deriving (Eq, Ord, Show, Read) instance PrintDot Rect where unqtDot (Rect p1 p2) = printPoint2DUnqt p1 <> comma <> printPoint2DUnqt p2 toDot = dquotes . unqtDot unqtListToDot = hsep . mapM unqtDot instance ParseDot Rect where parseUnqt = uncurry Rect <$> commaSep' parsePoint2D parsePoint2D parse = quotedParse parseUnqt parseUnqtList = sepBy1 parseUnqt whitespace1 -- ----------------------------------------------------------------------------- -- | If 'Local', then sub-graphs that are clusters are given special treatment . ' Global ' and ' NoCluster ' currently appear to be -- identical and turn off the special cluster processing. data ClusterMode = Local | Global | NoCluster deriving (Eq, Ord, Bounded, Enum, Show, Read) instance PrintDot ClusterMode where unqtDot Local = text "local" unqtDot Global = text "global" unqtDot NoCluster = text "none" instance ParseDot ClusterMode where parseUnqt = oneOf [ stringRep Local "local" , stringRep Global "global" , stringRep NoCluster "none" ] -- ----------------------------------------------------------------------------- -- | Specify where to place arrow heads on an edge. data DirType = Forward -- ^ Draw a directed edge with an arrow to the -- node it's pointing go. | Back -- ^ Draw a reverse directed edge with an arrow -- to the node it's coming from. | Both -- ^ Draw arrows on both ends of the edge. | NoDir -- ^ Draw an undirected edge. deriving (Eq, Ord, Bounded, Enum, Show, Read) instance PrintDot DirType where unqtDot Forward = text "forward" unqtDot Back = text "back" unqtDot Both = text "both" unqtDot NoDir = text "none" instance ParseDot DirType where parseUnqt = oneOf [ stringRep Forward "forward" , stringRep Back "back" , stringRep Both "both" , stringRep NoDir "none" ] -- ----------------------------------------------------------------------------- | Only when @mode = = ' IpSep'@. data DEConstraints = EdgeConstraints | NoConstraints | HierConstraints deriving (Eq, Ord, Bounded, Enum, Show, Read) instance PrintDot DEConstraints where unqtDot EdgeConstraints = unqtDot True unqtDot NoConstraints = unqtDot False unqtDot HierConstraints = text "hier" instance ParseDot DEConstraints where parseUnqt = fmap (bool NoConstraints EdgeConstraints) parse `onFail` stringRep HierConstraints "hier" -- ----------------------------------------------------------------------------- | Either a ' Double ' or a ( 2D ) ' Point ' ( i.e. created with -- 'createPoint'). -- Whilst it is possible to create a ' Point ' value with either a third co - ordinate or a forced position , these are ignored for -- printing/parsing. -- -- An optional prefix of @\'+\'@ is allowed when parsing. data DPoint = DVal Double | PVal Point deriving (Eq, Ord, Show, Read) instance PrintDot DPoint where unqtDot (DVal d) = unqtDot d unqtDot (PVal p) = printPoint2DUnqt p toDot (DVal d) = toDot d toDot (PVal p) = printPoint2D p instance ParseDot DPoint where parseUnqt = optional (character '+') *> oneOf [ PVal <$> parsePoint2D , DVal <$> parseUnqt ] parse = quotedParse parseUnqt -- A `+' would need to be quoted. `onFail` fmap DVal (parseSignedFloat False) -- Don't use parseUnqt! -- ----------------------------------------------------------------------------- -- | The mapping used for 'FontName' values in SVG output. -- -- More information can be found at <>. data SVGFontNames = SvgNames -- ^ Use the legal generic SVG font names. | PostScriptNames -- ^ Use PostScript font names. | FontConfigNames -- ^ Use fontconfig font conventions. deriving (Eq, Ord, Bounded, Enum, Show, Read) instance PrintDot SVGFontNames where unqtDot SvgNames = text "svg" unqtDot PostScriptNames = text "ps" unqtDot FontConfigNames = text "gd" instance ParseDot SVGFontNames where parseUnqt = oneOf [ stringRep SvgNames "svg" , stringRep PostScriptNames "ps" , stringRep FontConfigNames "gd" ] parse = stringRep SvgNames "\"\"" `onFail` optionalQuoted parseUnqt -- ----------------------------------------------------------------------------- -- | Maximum width and height of drawing in inches. data GraphSize = GSize { width :: Double -- | If @Nothing@, then the height is the -- same as the width. , height :: Maybe Double -- | If drawing is smaller than specified -- size, this value determines whether it -- is scaled up. , desiredSize :: Bool } deriving (Eq, Ord, Show, Read) instance PrintDot GraphSize where unqtDot (GSize w mh ds) = bool id (<> char '!') ds . maybe id (\h -> (<> unqtDot h) . (<> comma)) mh $ unqtDot w toDot (GSize w Nothing False) = toDot w toDot gs = dquotes $ unqtDot gs instance ParseDot GraphSize where parseUnqt = GSize <$> parseUnqt <*> optional (parseComma *> whitespace *> parseUnqt) <*> (isJust <$> optional (character '!')) parse = quotedParse parseUnqt `onFail` fmap (\ w -> GSize w Nothing False) (parseSignedFloat False) -- ----------------------------------------------------------------------------- -- | For 'Neato' unless indicated otherwise. data ModeType = Major | KK | Hier | IpSep ^ For ' Sfdp ' , requires Graphviz > = 2.32.0 . ^ For ' Sfdp ' , requires Graphviz > = 2.32.0 . deriving (Eq, Ord, Bounded, Enum, Show, Read) instance PrintDot ModeType where unqtDot Major = text "major" unqtDot KK = text "KK" unqtDot Hier = text "hier" unqtDot IpSep = text "ipsep" unqtDot SpringMode = text "spring" unqtDot MaxEnt = text "maxent" instance ParseDot ModeType where parseUnqt = oneOf [ stringRep Major "major" , stringRep KK "KK" , stringRep Hier "hier" , stringRep IpSep "ipsep" , stringRep SpringMode "spring" , stringRep MaxEnt "maxent" ] -- ----------------------------------------------------------------------------- data Model = ShortPath | SubSet | Circuit | MDS deriving (Eq, Ord, Bounded, Enum, Show, Read) instance PrintDot Model where unqtDot ShortPath = text "shortpath" unqtDot SubSet = text "subset" unqtDot Circuit = text "circuit" unqtDot MDS = text "mds" instance ParseDot Model where parseUnqt = oneOf [ stringRep ShortPath "shortpath" , stringRep SubSet "subset" , stringRep Circuit "circuit" , stringRep MDS "mds" ] -- ----------------------------------------------------------------------------- data Label = StrLabel EscString ^ If ' PlainText ' is used , the -- 'Html.Label' value is the entire -- \"shape\"; if anything else except ' PointShape ' is used then -- the 'Html.Label' is embedded -- within the shape. | RecordLabel RecordFields -- ^ For nodes only; requires -- either 'Record' or -- 'MRecord' as the shape. deriving (Eq, Ord, Show, Read) instance PrintDot Label where unqtDot (StrLabel s) = unqtDot s unqtDot (HtmlLabel h) = angled $ unqtDot h unqtDot (RecordLabel fs) = unqtDot fs toDot (StrLabel s) = toDot s toDot h@HtmlLabel{} = unqtDot h toDot (RecordLabel fs) = toDot fs instance ParseDot Label where -- Don't have to worry about being able to tell the difference between an HtmlLabel and a RecordLabel starting with a PortPos , -- since the latter will be in quotes and the former won't. parseUnqt = oneOf [ HtmlLabel <$> parseAngled parseUnqt , RecordLabel <$> parseUnqt , StrLabel <$> parseUnqt ] parse = oneOf [ HtmlLabel <$> parseAngled parse , RecordLabel <$> parse , StrLabel <$> parse ] -- ----------------------------------------------------------------------------- | A RecordFields value should never be empty . type RecordFields = [RecordField] -- | Specifies the sub-values of a record-based label. By default, the cells are laid out horizontally ; use ' FlipFields ' to change -- the orientation of the fields (can be applied recursively). To change the default orientation , use ' RankDir ' . data RecordField = LabelledTarget PortName EscString | PortName PortName -- ^ Will result in no label for -- that cell. | FieldLabel EscString | FlipFields RecordFields deriving (Eq, Ord, Show, Read) instance PrintDot RecordField where Have to use ' printPortName ' to add the @\'<\'@ and @\'>\'@. unqtDot (LabelledTarget t s) = printPortName t <+> unqtRecordString s unqtDot (PortName t) = printPortName t unqtDot (FieldLabel s) = unqtRecordString s unqtDot (FlipFields rs) = braces $ unqtDot rs toDot (FieldLabel s) = printEscaped recordEscChars s toDot rf = dquotes $ unqtDot rf unqtListToDot [f] = unqtDot f unqtListToDot fs = hcat . punctuate (char '|') $ mapM unqtDot fs listToDot [f] = toDot f listToDot fs = dquotes $ unqtListToDot fs instance ParseDot RecordField where parseUnqt = (liftA2 maybe PortName LabelledTarget <$> (PN <$> parseAngled parseRecord) <*> optional (whitespace1 *> parseRecord) ) `onFail` fmap FieldLabel parseRecord `onFail` fmap FlipFields (parseBraced parseUnqt) `onFail` fail "Unable to parse RecordField" parse = quotedParse parseUnqt parseUnqtList = wrapWhitespace $ sepBy1 parseUnqt (wrapWhitespace $ character '|') Note : a singleton unquoted ' FieldLabel ' is /not/ valid , as it -- will cause parsing problems for other 'Label' types. parseList = do rfs <- quotedParse parseUnqtList if validRFs rfs then return rfs else fail "This is a StrLabel, not a RecordLabel" where validRFs [FieldLabel str] = T.any (`elem` recordEscChars) str validRFs _ = True -- | Print a 'PortName' value as expected within a Record data -- structure. printPortName :: PortName -> DotCode printPortName = angled . unqtRecordString . portName parseRecord :: Parse Text parseRecord = parseEscaped False recordEscChars [] unqtRecordString :: Text -> DotCode unqtRecordString = unqtEscaped recordEscChars recordEscChars :: [Char] recordEscChars = ['{', '}', '|', ' ', '<', '>'] -- ----------------------------------------------------------------------------- -- | How to treat a node whose name is of the form \"@|edgelabel|*@\" -- as a special node representing an edge label. data LabelScheme = NotEdgeLabel -- ^ No effect | CloseToCenter -- ^ Make node close to center of neighbor | CloseToOldCenter -- ^ Make node close to old center of neighbor ^ Use a two - step process . deriving (Eq, Ord, Bounded, Enum, Show, Read) instance PrintDot LabelScheme where unqtDot NotEdgeLabel = int 0 unqtDot CloseToCenter = int 1 unqtDot CloseToOldCenter = int 2 unqtDot RemoveAndStraighten = int 3 instance ParseDot LabelScheme where -- Use string-based parsing rather than parsing an integer just to make it easier parseUnqt = stringValue [ ("0", NotEdgeLabel) , ("1", CloseToCenter) , ("2", CloseToOldCenter) , ("3", RemoveAndStraighten) ] -- ----------------------------------------------------------------------------- data Point = Point { xCoord :: Double , yCoord :: Double -- | Can only be 'Just' for @'Dim' 3@ or greater. , zCoord :: Maybe Double | Input to Graphviz only : specify that the -- node position should not change. , forcePos :: Bool } deriving (Eq, Ord, Show, Read) -- | Create a point with only @x@ and @y@ values. createPoint :: Double -> Double -> Point createPoint x y = Point x y Nothing False printPoint2DUnqt :: Point -> DotCode printPoint2DUnqt p = commaDel (xCoord p) (yCoord p) printPoint2D :: Point -> DotCode printPoint2D = dquotes . printPoint2DUnqt parsePoint2D :: Parse Point parsePoint2D = uncurry createPoint <$> commaSepUnqt instance PrintDot Point where unqtDot (Point x y mz frs) = bool id (<> char '!') frs . maybe id (\ z -> (<> unqtDot z) . (<> comma)) mz $ commaDel x y toDot = dquotes . unqtDot unqtListToDot = hsep . mapM unqtDot listToDot = dquotes . unqtListToDot instance ParseDot Point where parseUnqt = uncurry Point <$> commaSepUnqt <*> optional (parseComma *> parseUnqt) <*> (isJust <$> optional (character '!')) parse = quotedParse parseUnqt parseUnqtList = sepBy1 parseUnqt whitespace1 -- ----------------------------------------------------------------------------- -- | How to deal with node overlaps. -- -- Defaults to 'KeepOverlaps' /except/ for 'Fdp' and 'Sfdp'. -- -- The ability to specify the number of tries for 'Fdp''s initial force - directed technique is /not/ supported ( by default , ' Fdp ' uses -- @9@ passes of its in-built technique, and then @'PrismOverlap' -- Nothing@). -- For ' Sfdp ' , the default is @'PrismOverlap ' ( Just 0)@. data Overlap = KeepOverlaps | ScaleOverlaps -- ^ Remove overlaps by uniformly scaling in x and y. | ScaleXYOverlaps -- ^ Remove overlaps by separately scaling x and y. | PrismOverlap (Maybe Word16) -- ^ Requires the Prism -- library to be -- available (if not, -- this is equivalent to ' ' ) . @'Nothing'@ -- is equivalent to @'Just ' 1000@. -- Influenced by -- 'OverlapScaling'. ^ Requires Graphviz > = 2.30.0 . ^ Scale layout down as much as -- possible without introducing -- overlaps, assuming none to begin -- with. | VpscOverlap -- ^ Uses quadratic optimization to -- minimize node displacement. | IpsepOverlap -- ^ Only when @mode == 'IpSep'@ deriving (Eq, Ord, Show, Read) instance PrintDot Overlap where unqtDot KeepOverlaps = unqtDot True unqtDot ScaleOverlaps = text "scale" unqtDot ScaleXYOverlaps = text "scalexy" unqtDot (PrismOverlap i) = maybe id (flip (<>) . unqtDot) i $ text "prism" unqtDot VoronoiOverlap = text "voronoi" unqtDot CompressOverlap = text "compress" unqtDot VpscOverlap = text "vpsc" unqtDot IpsepOverlap = text "ipsep" | Note that = false@ defaults to @'PrismOverlap ' Nothing@ , -- but if the Prism library isn't available then it is equivalent to ' ' . instance ParseDot Overlap where parseUnqt = oneOf [ stringRep KeepOverlaps "true" , stringRep ScaleXYOverlaps "scalexy" , stringRep ScaleOverlaps "scale" , string "prism" *> fmap PrismOverlap (optional parse) , stringRep (PrismOverlap Nothing) "false" , stringRep VoronoiOverlap "voronoi" , stringRep CompressOverlap "compress" , stringRep VpscOverlap "vpsc" , stringRep IpsepOverlap "ipsep" ] -- ----------------------------------------------------------------------------- newtype LayerSep = LSep Text deriving (Eq, Ord, Show, Read) instance PrintDot LayerSep where unqtDot (LSep ls) = setLayerSep (T.unpack ls) *> unqtDot ls toDot (LSep ls) = setLayerSep (T.unpack ls) *> toDot ls instance ParseDot LayerSep where parseUnqt = do ls <- parseUnqt setLayerSep $ T.unpack ls return $ LSep ls parse = do ls <- parse setLayerSep $ T.unpack ls return $ LSep ls newtype LayerListSep = LLSep Text deriving (Eq, Ord, Show, Read) instance PrintDot LayerListSep where unqtDot (LLSep ls) = setLayerListSep (T.unpack ls) *> unqtDot ls toDot (LLSep ls) = setLayerListSep (T.unpack ls) *> toDot ls instance ParseDot LayerListSep where parseUnqt = do ls <- parseUnqt setLayerListSep $ T.unpack ls return $ LLSep ls parse = do ls <- parse setLayerListSep $ T.unpack ls return $ LLSep ls type LayerRange = [LayerRangeElem] data LayerRangeElem = LRID LayerID | LRS LayerID LayerID deriving (Eq, Ord, Show, Read) instance PrintDot LayerRangeElem where unqtDot (LRID lid) = unqtDot lid unqtDot (LRS id1 id2) = do ls <- getLayerSep let s = unqtDot $ head ls unqtDot id1 <> s <> unqtDot id2 toDot (LRID lid) = toDot lid toDot lrs = dquotes $ unqtDot lrs unqtListToDot lr = do lls <- getLayerListSep let s = unqtDot $ head lls hcat . punctuate s $ mapM unqtDot lr listToDot [lre] = toDot lre listToDot lrs = dquotes $ unqtListToDot lrs instance ParseDot LayerRangeElem where parseUnqt = ignoreSep LRS parseUnqt parseLayerSep parseUnqt `onFail` fmap LRID parseUnqt parse = quotedParse (ignoreSep LRS parseUnqt parseLayerSep parseUnqt) `onFail` fmap LRID parse parseUnqtList = sepBy parseUnqt parseLayerListSep parseList = quotedParse parseUnqtList `onFail` fmap ((:[]) . LRID) parse parseLayerSep :: Parse () parseLayerSep = do ls <- getLayerSep many1Satisfy (`elem` ls) *> return () parseLayerName :: Parse Text parseLayerName = parseEscaped False [] =<< liftA2 (++) getLayerSep getLayerListSep parseLayerName' :: Parse Text parseLayerName' = stringBlock `onFail` quotedParse parseLayerName parseLayerListSep :: Parse () parseLayerListSep = do lls <- getLayerListSep many1Satisfy (`elem` lls) *> return () -- | You should not have any layer separator characters for the ' LRName ' option , as they wo n't be parseable . data LayerID = AllLayers | LRInt Int | LRName Text -- ^ Should not be a number or @"all"@. deriving (Eq, Ord, Show, Read) instance PrintDot LayerID where unqtDot AllLayers = text "all" unqtDot (LRInt n) = unqtDot n unqtDot (LRName nm) = unqtDot nm toDot (LRName nm) = toDot nm Other two do n't need quotes toDot li = unqtDot li unqtListToDot ll = do ls <- getLayerSep let s = unqtDot $ head ls hcat . punctuate s $ mapM unqtDot ll listToDot [l] = toDot l -- Might not need quotes, but probably will. Can't tell either -- way since we don't know what the separator character will be. listToDot ll = dquotes $ unqtDot ll instance ParseDot LayerID where parseUnqt = checkLayerName <$> parseLayerName -- tests for Int and All parse = oneOf [ checkLayerName <$> parseLayerName' , LRInt <$> parse -- Mainly for unquoted case. ] checkLayerName :: Text -> LayerID checkLayerName str = maybe checkAll LRInt $ stringToInt str where checkAll = if T.toLower str == "all" then AllLayers else LRName str -- Remember: this /must/ be a newtype as we can't use arbitrary -- LayerID values! -- | A list of layer names. The names should all be unique 'LRName' -- values, and when printed will use an arbitrary character from -- 'defLayerSep'. The values in the list are implicitly numbered @1 , 2 , ... @. newtype LayerList = LL [LayerID] deriving (Eq, Ord, Show, Read) instance PrintDot LayerList where unqtDot (LL ll) = unqtDot ll toDot (LL ll) = toDot ll instance ParseDot LayerList where parseUnqt = LL <$> sepBy1 parseUnqt parseLayerSep parse = quotedParse parseUnqt `onFail` fmap (LL . (:[]) . LRName) stringBlock `onFail` quotedParse (stringRep (LL []) "") -- ----------------------------------------------------------------------------- data Order = OutEdges -- ^ Draw outgoing edges in order specified. | InEdges -- ^ Draw incoming edges in order specified. deriving (Eq, Ord, Bounded, Enum, Show, Read) instance PrintDot Order where unqtDot OutEdges = text "out" unqtDot InEdges = text "in" instance ParseDot Order where parseUnqt = oneOf [ stringRep OutEdges "out" , stringRep InEdges "in" ] -- ----------------------------------------------------------------------------- data OutputMode = BreadthFirst | NodesFirst | EdgesFirst deriving (Eq, Ord, Bounded, Enum, Show, Read) instance PrintDot OutputMode where unqtDot BreadthFirst = text "breadthfirst" unqtDot NodesFirst = text "nodesfirst" unqtDot EdgesFirst = text "edgesfirst" instance ParseDot OutputMode where parseUnqt = oneOf [ stringRep BreadthFirst "breadthfirst" , stringRep NodesFirst "nodesfirst" , stringRep EdgesFirst "edgesfirst" ] -- ----------------------------------------------------------------------------- data Pack = DoPack | DontPack | PackMargin Int -- ^ If non-negative, then packs; otherwise doesn't. deriving (Eq, Ord, Show, Read) instance PrintDot Pack where unqtDot DoPack = unqtDot True unqtDot DontPack = unqtDot False unqtDot (PackMargin m) = unqtDot m instance ParseDot Pack where -- What happens if it parses 0? It's non-negative, but parses as False parseUnqt = oneOf [ PackMargin <$> parseUnqt , bool DontPack DoPack <$> onlyBool ] -- ----------------------------------------------------------------------------- data PackMode = PackNode | PackClust | PackGraph | PackArray Bool Bool (Maybe Int) -- ^ Sort by cols, sort -- by user, number of -- rows/cols deriving (Eq, Ord, Show, Read) instance PrintDot PackMode where unqtDot PackNode = text "node" unqtDot PackClust = text "clust" unqtDot PackGraph = text "graph" unqtDot (PackArray c u mi) = addNum . isU . isC . isUnder $ text "array" where addNum = maybe id (flip (<>) . unqtDot) mi isUnder = if c || u then (<> char '_') else id isC = if c then (<> char 'c') else id isU = if u then (<> char 'u') else id instance ParseDot PackMode where parseUnqt = oneOf [ stringRep PackNode "node" , stringRep PackClust "clust" , stringRep PackGraph "graph" , do string "array" mcu <- optional $ character '_' *> many1 (satisfy isCU) let c = hasCharacter mcu 'c' u = hasCharacter mcu 'u' mi <- optional parseUnqt return $ PackArray c u mi ] where hasCharacter ms c = maybe False (elem c) ms -- Also checks and removes quote characters isCU = (`elem` ['c', 'u']) -- ----------------------------------------------------------------------------- data Pos = PointPos Point | SplinePos [Spline] deriving (Eq, Ord, Show, Read) instance PrintDot Pos where unqtDot (PointPos p) = unqtDot p unqtDot (SplinePos ss) = unqtDot ss toDot (PointPos p) = toDot p toDot (SplinePos ss) = toDot ss instance ParseDot Pos where Have to be careful with this : if we try to parse points first , -- then a spline with no start and end points will erroneously get -- parsed as a point and then the parser will crash as it expects a -- closing quote character... parseUnqt = do splns <- parseUnqt case splns of [Spline Nothing Nothing [p]] -> return $ PointPos p _ -> return $ SplinePos splns parse = quotedParse parseUnqt -- ----------------------------------------------------------------------------- -- | Controls how (and if) edges are represented. -- -- For 'Dot', the default is 'SplineEdges'; for all other layouts -- the default is 'LineEdges'. data EdgeType = SplineEdges -- ^ Except for 'Dot', requires -- non-overlapping nodes (see -- 'Overlap'). | LineEdges | NoEdges | PolyLine | Ortho -- ^ Does not handle ports or edge labels in 'Dot'. ^ Requires Graphviz > = 2.30.0 . | CompoundEdge -- ^ 'Fdp' only deriving (Eq, Ord, Bounded, Enum, Show, Read) instance PrintDot EdgeType where unqtDot SplineEdges = text "spline" unqtDot LineEdges = text "line" unqtDot NoEdges = empty unqtDot PolyLine = text "polyline" unqtDot Ortho = text "ortho" unqtDot Curved = text "curved" unqtDot CompoundEdge = text "compound" toDot NoEdges = dquotes empty toDot et = unqtDot et instance ParseDot EdgeType where Ca n't parse without quotes . parseUnqt = oneOf [ bool LineEdges SplineEdges <$> parse , stringRep SplineEdges "spline" , stringRep LineEdges "line" , stringRep NoEdges "none" , stringRep PolyLine "polyline" , stringRep Ortho "ortho" , stringRep Curved "curved" , stringRep CompoundEdge "compound" ] parse = stringRep NoEdges "\"\"" `onFail` optionalQuoted parseUnqt -- ----------------------------------------------------------------------------- | Upper - case first character is major order ; lower - case second character is minor order . data PageDir = Bl | Br | Tl | Tr | Rb | Rt | Lb | Lt deriving (Eq, Ord, Bounded, Enum, Show, Read) instance PrintDot PageDir where unqtDot Bl = text "BL" unqtDot Br = text "BR" unqtDot Tl = text "TL" unqtDot Tr = text "TR" unqtDot Rb = text "RB" unqtDot Rt = text "RT" unqtDot Lb = text "LB" unqtDot Lt = text "LT" instance ParseDot PageDir where parseUnqt = stringValue [ ("BL", Bl) , ("BR", Br) , ("TL", Tl) , ("TR", Tr) , ("RB", Rb) , ("RT", Rt) , ("LB", Lb) , ("LT", Lt) ] -- ----------------------------------------------------------------------------- | The number of points in the list must be equivalent to 1 mod 3 ; -- note that this is not checked. data Spline = Spline { endPoint :: Maybe Point , startPoint :: Maybe Point , splinePoints :: [Point] } deriving (Eq, Ord, Show, Read) instance PrintDot Spline where unqtDot (Spline me ms ps) = addE . addS . hsep $ mapM unqtDot ps where addP t = maybe id ((<+>) . commaDel t) addS = addP 's' ms addE = addP 'e' me toDot = dquotes . unqtDot unqtListToDot = hcat . punctuate semi . mapM unqtDot listToDot = dquotes . unqtListToDot instance ParseDot Spline where parseUnqt = Spline <$> parseP 'e' <*> parseP 's' <*> sepBy1 parseUnqt whitespace1 where parseP t = optional (character t *> parseComma *> parseUnqt <* whitespace1) parse = quotedParse parseUnqt parseUnqtList = sepBy1 parseUnqt (character ';') -- ----------------------------------------------------------------------------- data QuadType = NormalQT | FastQT | NoQT deriving (Eq, Ord, Bounded, Enum, Show, Read) instance PrintDot QuadType where unqtDot NormalQT = text "normal" unqtDot FastQT = text "fast" unqtDot NoQT = text "none" instance ParseDot QuadType where -- Have to take into account the slightly different interpretation of used as an option for parsing QuadType parseUnqt = oneOf [ stringRep NormalQT "normal" , stringRep FastQT "fast" , stringRep NoQT "none" , character '2' *> return FastQT -- weird bool , bool NoQT NormalQT <$> parse ] -- ----------------------------------------------------------------------------- | Specify the root node either as a Node attribute or a attribute . data Root = IsCentral -- ^ For Nodes only | NotCentral -- ^ For Nodes only | NodeName Text -- ^ For Graphs only deriving (Eq, Ord, Show, Read) instance PrintDot Root where unqtDot IsCentral = unqtDot True unqtDot NotCentral = unqtDot False unqtDot (NodeName n) = unqtDot n toDot (NodeName n) = toDot n toDot r = unqtDot r instance ParseDot Root where parseUnqt = fmap (bool NotCentral IsCentral) onlyBool `onFail` fmap NodeName parseUnqt parse = optionalQuoted (bool NotCentral IsCentral <$> onlyBool) `onFail` fmap NodeName parse -- ----------------------------------------------------------------------------- data RankType = SameRank | MinRank | SourceRank | MaxRank | SinkRank deriving (Eq, Ord, Bounded, Enum, Show, Read) instance PrintDot RankType where unqtDot SameRank = text "same" unqtDot MinRank = text "min" unqtDot SourceRank = text "source" unqtDot MaxRank = text "max" unqtDot SinkRank = text "sink" instance ParseDot RankType where parseUnqt = stringValue [ ("same", SameRank) , ("min", MinRank) , ("source", SourceRank) , ("max", MaxRank) , ("sink", SinkRank) ] -- ----------------------------------------------------------------------------- data RankDir = FromTop | FromLeft | FromBottom | FromRight deriving (Eq, Ord, Bounded, Enum, Show, Read) instance PrintDot RankDir where unqtDot FromTop = text "TB" unqtDot FromLeft = text "LR" unqtDot FromBottom = text "BT" unqtDot FromRight = text "RL" instance ParseDot RankDir where parseUnqt = oneOf [ stringRep FromTop "TB" , stringRep FromLeft "LR" , stringRep FromBottom "BT" , stringRep FromRight "RL" ] -- ----------------------------------------------------------------------------- -- | Geometries of shapes are affected by the attributes 'Regular', -- 'Peripheries' and 'Orientation'. data Shape ^ Has synonyms of /rect/ and /rectangle/. | Polygon -- ^ Also affected by 'Sides', 'Skew' and 'Distortion'. | Ellipse -- ^ Has synonym of /oval/. | Circle ^ Only affected by ' Peripheries ' , ' ' and -- 'Height'. | Egg | Triangle | PlainText -- ^ Has synonym of /none/. Recommended for ' HtmlLabel 's . | DiamondShape | Trapezium | Parallelogram | House | Pentagon | Hexagon | Septagon | Octagon | DoubleCircle | DoubleOctagon | TripleOctagon | InvTriangle | InvTrapezium | InvHouse | MDiamond | MSquare | MCircle | Square | Star -- ^ Requires Graphviz >= 2.32.0. ^ Requires Graphviz > = 2.36.0 . | Note | Tab | Folder | Box3D | Component ^ Requires Graphviz > = 2.30.0 . ^ Requires Graphviz > = 2.30.0 . ^ Requires Graphviz > = 2.30.0 . ^ Requires Graphviz > = 2.30.0 . ^ Requires Graphviz > = 2.30.0 . ^ Requires Graphviz > = 2.30.0 . ^ Requires Graphviz > = 2.30.0 . ^ Requires Graphviz > = 2.30.0 . ^ Requires Graphviz > = 2.30.0 . ^ Requires Graphviz > = 2.30.0 . ^ Requires Graphviz > = 2.30.0 . ^ Requires Graphviz > = 2.30.0 . ^ Requires Graphviz > = 2.30.0 . ^ Requires Graphviz > = 2.30.0 . ^ Requires Graphviz > = 2.30.0 . ^ Requires Graphviz > = 2.30.0 . ^ Requires Graphviz > = 2.30.0 . ^ Requires Graphviz > = 2.30.0 . ^ Requires Graphviz > = 2.30.0 . ^ Requires Graphviz > = 2.30.0 . | Record -- ^ Must specify the record shape with a 'Label'. | MRecord -- ^ Must specify the record shape with a 'Label'. deriving (Eq, Ord, Bounded, Enum, Show, Read) instance PrintDot Shape where unqtDot BoxShape = text "box" unqtDot Polygon = text "polygon" unqtDot Ellipse = text "ellipse" unqtDot Circle = text "circle" unqtDot PointShape = text "point" unqtDot Egg = text "egg" unqtDot Triangle = text "triangle" unqtDot PlainText = text "plaintext" unqtDot DiamondShape = text "diamond" unqtDot Trapezium = text "trapezium" unqtDot Parallelogram = text "parallelogram" unqtDot House = text "house" unqtDot Pentagon = text "pentagon" unqtDot Hexagon = text "hexagon" unqtDot Septagon = text "septagon" unqtDot Octagon = text "octagon" unqtDot DoubleCircle = text "doublecircle" unqtDot DoubleOctagon = text "doubleoctagon" unqtDot TripleOctagon = text "tripleoctagon" unqtDot InvTriangle = text "invtriangle" unqtDot InvTrapezium = text "invtrapezium" unqtDot InvHouse = text "invhouse" unqtDot MDiamond = text "Mdiamond" unqtDot MSquare = text "Msquare" unqtDot MCircle = text "Mcircle" unqtDot Square = text "square" unqtDot Star = text "star" unqtDot Underline = text "underline" unqtDot Note = text "note" unqtDot Tab = text "tab" unqtDot Folder = text "folder" unqtDot Box3D = text "box3d" unqtDot Component = text "component" unqtDot Promoter = text "promoter" unqtDot CDS = text "cds" unqtDot Terminator = text "terminator" unqtDot UTR = text "utr" unqtDot PrimerSite = text "primersite" unqtDot RestrictionSite = text "restrictionsite" unqtDot FivePovOverhang = text "fivepovoverhang" unqtDot ThreePovOverhang = text "threepovoverhang" unqtDot NoOverhang = text "nooverhang" unqtDot Assembly = text "assembly" unqtDot Signature = text "signature" unqtDot Insulator = text "insulator" unqtDot Ribosite = text "ribosite" unqtDot RNAStab = text "rnastab" unqtDot ProteaseSite = text "proteasesite" unqtDot ProteinStab = text "proteinstab" unqtDot RPromoter = text "rpromoter" unqtDot RArrow = text "rarrow" unqtDot LArrow = text "larrow" unqtDot LPromoter = text "lpromoter" unqtDot Record = text "record" unqtDot MRecord = text "Mrecord" instance ParseDot Shape where parseUnqt = stringValue [ ("box3d", Box3D) , ("box", BoxShape) , ("rectangle", BoxShape) , ("rect", BoxShape) , ("polygon", Polygon) , ("ellipse", Ellipse) , ("oval", Ellipse) , ("circle", Circle) , ("point", PointShape) , ("egg", Egg) , ("triangle", Triangle) , ("plaintext", PlainText) , ("none", PlainText) , ("diamond", DiamondShape) , ("trapezium", Trapezium) , ("parallelogram", Parallelogram) , ("house", House) , ("pentagon", Pentagon) , ("hexagon", Hexagon) , ("septagon", Septagon) , ("octagon", Octagon) , ("doublecircle", DoubleCircle) , ("doubleoctagon", DoubleOctagon) , ("tripleoctagon", TripleOctagon) , ("invtriangle", InvTriangle) , ("invtrapezium", InvTrapezium) , ("invhouse", InvHouse) , ("Mdiamond", MDiamond) , ("Msquare", MSquare) , ("Mcircle", MCircle) , ("square", Square) , ("star", Star) , ("underline", Underline) , ("note", Note) , ("tab", Tab) , ("folder", Folder) , ("component", Component) , ("promoter", Promoter) , ("cds", CDS) , ("terminator", Terminator) , ("utr", UTR) , ("primersite", PrimerSite) , ("restrictionsite", RestrictionSite) , ("fivepovoverhang", FivePovOverhang) , ("threepovoverhang", ThreePovOverhang) , ("nooverhang", NoOverhang) , ("assembly", Assembly) , ("signature", Signature) , ("insulator", Insulator) , ("ribosite", Ribosite) , ("rnastab", RNAStab) , ("proteasesite", ProteaseSite) , ("proteinstab", ProteinStab) , ("rpromoter", RPromoter) , ("rarrow", RArrow) , ("larrow", LArrow) , ("lpromoter", LPromoter) , ("record", Record) , ("Mrecord", MRecord) ] -- ----------------------------------------------------------------------------- data SmoothType = NoSmooth | AvgDist | GraphDist | PowerDist | RNG | Spring | TriangleSmooth deriving (Eq, Ord, Bounded, Enum, Show, Read) instance PrintDot SmoothType where unqtDot NoSmooth = text "none" unqtDot AvgDist = text "avg_dist" unqtDot GraphDist = text "graph_dist" unqtDot PowerDist = text "power_dist" unqtDot RNG = text "rng" unqtDot Spring = text "spring" unqtDot TriangleSmooth = text "triangle" instance ParseDot SmoothType where parseUnqt = oneOf [ stringRep NoSmooth "none" , stringRep AvgDist "avg_dist" , stringRep GraphDist "graph_dist" , stringRep PowerDist "power_dist" , stringRep RNG "rng" , stringRep Spring "spring" , stringRep TriangleSmooth "triangle" ] -- ----------------------------------------------------------------------------- data StartType = StartStyle STStyle | StartSeed Int | StartStyleSeed STStyle Int deriving (Eq, Ord, Show, Read) instance PrintDot StartType where unqtDot (StartStyle ss) = unqtDot ss unqtDot (StartSeed s) = unqtDot s unqtDot (StartStyleSeed ss s) = unqtDot ss <> unqtDot s instance ParseDot StartType where parseUnqt = oneOf [ liftA2 StartStyleSeed parseUnqt parseUnqt , StartStyle <$> parseUnqt , StartSeed <$> parseUnqt ] data STStyle = RegularStyle | SelfStyle | RandomStyle deriving (Eq, Ord, Bounded, Enum, Show, Read) instance PrintDot STStyle where unqtDot RegularStyle = text "regular" unqtDot SelfStyle = text "self" unqtDot RandomStyle = text "random" instance ParseDot STStyle where parseUnqt = oneOf [ stringRep RegularStyle "regular" , stringRep SelfStyle "self" , stringRep RandomStyle "random" ] -- ----------------------------------------------------------------------------- -- | An individual style item. Except for 'DD', the @['String']@ -- should be empty. data StyleItem = SItem StyleName [Text] deriving (Eq, Ord, Show, Read) instance PrintDot StyleItem where unqtDot (SItem nm args) | null args = dnm | otherwise = dnm <> parens args' where dnm = unqtDot nm args' = hcat . punctuate comma $ mapM unqtDot args toDot si@(SItem nm args) | null args = toDot nm | otherwise = dquotes $ unqtDot si unqtListToDot = hcat . punctuate comma . mapM unqtDot listToDot [SItem nm []] = toDot nm listToDot sis = dquotes $ unqtListToDot sis instance ParseDot StyleItem where parseUnqt = liftA2 SItem parseUnqt (tryParseList' parseArgs) parse = quotedParse (liftA2 SItem parseUnqt parseArgs) `onFail` fmap (`SItem` []) parse parseUnqtList = sepBy1 parseUnqt (wrapWhitespace parseComma) parseList = quotedParse parseUnqtList `onFail` -- Might not necessarily need to be quoted if a singleton... fmap return parse parseArgs :: Parse [Text] parseArgs = bracketSep (character '(') parseComma (character ')') parseStyleName data StyleName = Dashed -- ^ Nodes and Edges | Dotted -- ^ Nodes and Edges | Solid -- ^ Nodes and Edges | Bold -- ^ Nodes and Edges | Invisible -- ^ Nodes and Edges | Filled -- ^ Nodes and Clusters | Striped -- ^ Rectangularly-shaped Nodes and Clusters ; requires Graphviz > = 2.30.0 | Wedged -- ^ Elliptically-shaped Nodes only; requires Graphviz > = 2.30.0 | Diagonals -- ^ Nodes only | Rounded -- ^ Nodes and Clusters ^ Edges only ; requires Graphviz > = 2.29.0 | Radial -- ^ Nodes, Clusters and Graphs, for use with ' GradientAngle ' ; requires Graphviz > = 2.29.0 | DD Text -- ^ Device Dependent deriving (Eq, Ord, Show, Read) instance PrintDot StyleName where unqtDot Dashed = text "dashed" unqtDot Dotted = text "dotted" unqtDot Solid = text "solid" unqtDot Bold = text "bold" unqtDot Invisible = text "invis" unqtDot Filled = text "filled" unqtDot Striped = text "striped" unqtDot Wedged = text "wedged" unqtDot Diagonals = text "diagonals" unqtDot Rounded = text "rounded" unqtDot Tapered = text "tapered" unqtDot Radial = text "radial" unqtDot (DD nm) = unqtDot nm toDot (DD nm) = toDot nm toDot sn = unqtDot sn instance ParseDot StyleName where parseUnqt = checkDD <$> parseStyleName parse = quotedParse parseUnqt `onFail` fmap checkDD quotelessString checkDD :: Text -> StyleName checkDD str = case T.toLower str of "dashed" -> Dashed "dotted" -> Dotted "solid" -> Solid "bold" -> Bold "invis" -> Invisible "filled" -> Filled "striped" -> Striped "wedged" -> Wedged "diagonals" -> Diagonals "rounded" -> Rounded "tapered" -> Tapered "radial" -> Radial _ -> DD str parseStyleName :: Parse Text parseStyleName = liftA2 T.cons (orEscaped . noneOf $ ' ' : disallowedChars) (parseEscaped True [] disallowedChars) where disallowedChars = [quoteChar, '(', ')', ','] Used because the first character has slightly stricter requirements than the rest . orSlash p = stringRep '\\' "\\\\" `onFail` p orEscaped = orQuote . orSlash -- ----------------------------------------------------------------------------- data ViewPort = VP { wVal :: Double , hVal :: Double , zVal :: Double , focus :: Maybe FocusType } deriving (Eq, Ord, Show, Read) instance PrintDot ViewPort where unqtDot vp = maybe vs ((<>) (vs <> comma) . unqtDot) $ focus vp where vs = hcat . punctuate comma $ mapM (unqtDot . ($vp)) [wVal, hVal, zVal] toDot = dquotes . unqtDot instance ParseDot ViewPort where parseUnqt = VP <$> parseUnqt <* parseComma <*> parseUnqt <* parseComma <*> parseUnqt <*> optional (parseComma *> parseUnqt) parse = quotedParse parseUnqt -- | For use with 'ViewPort'. data FocusType = XY Point | NodeFocus Text deriving (Eq, Ord, Show, Read) instance PrintDot FocusType where unqtDot (XY p) = unqtDot p unqtDot (NodeFocus nm) = unqtDot nm toDot (XY p) = toDot p toDot (NodeFocus nm) = toDot nm instance ParseDot FocusType where parseUnqt = fmap XY parseUnqt `onFail` fmap NodeFocus parseUnqt parse = fmap XY parse `onFail` fmap NodeFocus parse -- ----------------------------------------------------------------------------- data VerticalPlacement = VTop | VCenter -- ^ Only valid for Nodes. | VBottom deriving (Eq, Ord, Bounded, Enum, Show, Read) instance PrintDot VerticalPlacement where unqtDot VTop = char 't' unqtDot VCenter = char 'c' unqtDot VBottom = char 'b' instance ParseDot VerticalPlacement where parseUnqt = oneOf [ stringReps VTop ["top", "t"] , stringReps VCenter ["centre", "center", "c"] , stringReps VBottom ["bottom", "b"] ] -- ----------------------------------------------------------------------------- -- | A list of search paths. newtype Paths = Paths { paths :: [FilePath] } deriving (Eq, Ord, Show, Read) instance PrintDot Paths where unqtDot = unqtDot . intercalate [searchPathSeparator] . paths toDot (Paths [p]) = toDot p toDot ps = dquotes $ unqtDot ps instance ParseDot Paths where parseUnqt = Paths . splitSearchPath <$> parseUnqt parse = quotedParse parseUnqt `onFail` fmap (Paths . (:[]) . T.unpack) quotelessString -- ----------------------------------------------------------------------------- data ScaleType = UniformScale | NoScale | FillWidth | FillHeight | FillBoth deriving (Eq, Ord, Bounded, Enum, Show, Read) instance PrintDot ScaleType where unqtDot UniformScale = unqtDot True unqtDot NoScale = unqtDot False unqtDot FillWidth = text "width" unqtDot FillHeight = text "height" unqtDot FillBoth = text "both" instance ParseDot ScaleType where parseUnqt = oneOf [ stringRep UniformScale "true" , stringRep NoScale "false" , stringRep FillWidth "width" , stringRep FillHeight "height" , stringRep FillBoth "both" ] -- ----------------------------------------------------------------------------- data Justification = JLeft | JRight | JCenter deriving (Eq, Ord, Bounded, Enum, Show, Read) instance PrintDot Justification where unqtDot JLeft = char 'l' unqtDot JRight = char 'r' unqtDot JCenter = char 'c' instance ParseDot Justification where parseUnqt = oneOf [ stringReps JLeft ["left", "l"] , stringReps JRight ["right", "r"] , stringReps JCenter ["center", "centre", "c"] ] -- ----------------------------------------------------------------------------- data Ratios = AspectRatio Double | FillRatio | CompressRatio | ExpandRatio | AutoRatio deriving (Eq, Ord, Show, Read) instance PrintDot Ratios where unqtDot (AspectRatio r) = unqtDot r unqtDot FillRatio = text "fill" unqtDot CompressRatio = text "compress" unqtDot ExpandRatio = text "expand" unqtDot AutoRatio = text "auto" toDot (AspectRatio r) = toDot r toDot r = unqtDot r instance ParseDot Ratios where parseUnqt = parseRatio True parse = quotedParse parseUnqt <|> parseRatio False parseRatio :: Bool -> Parse Ratios parseRatio q = oneOf [ AspectRatio <$> parseSignedFloat q , stringRep FillRatio "fill" , stringRep CompressRatio "compress" , stringRep ExpandRatio "expand" , stringRep AutoRatio "auto" ] -- ----------------------------------------------------------------------------- -- | A numeric type with an explicit separation between integers and -- floating-point values. data Number = Int Int | Dbl Double deriving (Eq, Ord, Show, Read) instance PrintDot Number where unqtDot (Int i) = unqtDot i unqtDot (Dbl d) = unqtDot d toDot (Int i) = toDot i toDot (Dbl d) = toDot d instance ParseDot Number where parseUnqt = parseNumber True parse = quotedParse parseUnqt <|> parseNumber False parseNumber :: Bool -> Parse Number parseNumber q = Dbl <$> parseStrictFloat q <|> Int <$> parseUnqt -- ----------------------------------------------------------------------------- | If set , normalizes coordinates such that the first point is at the origin and the first edge is at the angle if specified . ^ Equivalent to @'NormalizedAngle ' 0@. | NotNormalized ^ Angle of first edge when -- normalized. Requires -- Graphviz >= 2.32.0. deriving (Eq, Ord, Show, Read) instance PrintDot Normalized where unqtDot IsNormalized = unqtDot True unqtDot NotNormalized = unqtDot False unqtDot (NormalizedAngle a) = unqtDot a toDot (NormalizedAngle a) = toDot a toDot norm = unqtDot norm instance ParseDot Normalized where parseUnqt = parseNormalized True parse = quotedParse parseUnqt <|> parseNormalized False parseNormalized :: Bool -> Parse Normalized parseNormalized q = NormalizedAngle <$> parseSignedFloat q <|> bool NotNormalized IsNormalized <$> onlyBool -- ----------------------------------------------------------------------------- -- | Determine how the 'Width' and 'Height' attributes specify the -- size of nodes. data NodeSize = GrowAsNeeded -- ^ Nodes will be the smallest width and height -- needed to contain the label and any possible image . ' ' and ' Height ' are the minimum -- allowed sizes. | SetNodeSize ^ ' ' and ' Height ' dictate the size of the node -- with a warning if the label cannot fit in this. | SetShapeSize ^ ' ' and ' Height ' dictate the size of the -- shape only and the label can expand out of the -- shape (with a warning). Requires Graphviz >= 2.38.0 . deriving (Eq, Ord, Bounded, Enum, Show, Read) instance PrintDot NodeSize where unqtDot GrowAsNeeded = unqtDot False unqtDot SetNodeSize = unqtDot True unqtDot SetShapeSize = text "shape" instance ParseDot NodeSize where parseUnqt = bool GrowAsNeeded SetNodeSize <$> parseUnqt <|> stringRep SetShapeSize "shape" -- ----------------------------------------------------------------------------- As of Graphviz 2.36.0 this was commented out ; as such it might come back , so leave this here in case we need it again . data AspectType = RatioOnly Double | RatioPassCount Double Int deriving ( Eq , Ord , Show , Read ) instance PrintDot AspectType where unqtDot ( RatioOnly r ) = unqtDot r unqtDot ( RatioPassCount r p ) = commaDel r p toDot at@RatioOnly { } = unqtDot at toDot at@RatioPassCount { } = dquotes $ unqtDot at instance ParseDot AspectType where parseUnqt = fmap ( uncurry RatioPassCount ) commaSepUnqt ` onFail ` fmap RatioOnly parseUnqt parse = ( uncurry RatioPassCount < $ > commaSepUnqt ) ` onFail ` fmap RatioOnly parse As of Graphviz 2.36.0 this was commented out; as such it might come back, so leave this here in case we need it again. data AspectType = RatioOnly Double | RatioPassCount Double Int deriving (Eq, Ord, Show, Read) instance PrintDot AspectType where unqtDot (RatioOnly r) = unqtDot r unqtDot (RatioPassCount r p) = commaDel r p toDot at@RatioOnly{} = unqtDot at toDot at@RatioPassCount{} = dquotes $ unqtDot at instance ParseDot AspectType where parseUnqt = fmap (uncurry RatioPassCount) commaSepUnqt `onFail` fmap RatioOnly parseUnqt parse = quotedParse (uncurry RatioPassCount <$> commaSepUnqt) `onFail` fmap RatioOnly parse -}
null
https://raw.githubusercontent.com/ivan-m/graphviz/42dbb6312d7edf789d7055079de7b4fa099a4acc/Data/GraphViz/Attributes/Values.hs
haskell
# OPTIONS_HADDOCK hide # ----------------------------------------------------------------------------- ----------------------------------------------------------------------------- | Should only have 2D points (i.e. created with 'createPoint'). ----------------------------------------------------------------------------- | If 'Local', then sub-graphs that are clusters are given special identical and turn off the special cluster processing. ----------------------------------------------------------------------------- | Specify where to place arrow heads on an edge. ^ Draw a directed edge with an arrow to the node it's pointing go. ^ Draw a reverse directed edge with an arrow to the node it's coming from. ^ Draw arrows on both ends of the edge. ^ Draw an undirected edge. ----------------------------------------------------------------------------- ----------------------------------------------------------------------------- 'createPoint'). printing/parsing. An optional prefix of @\'+\'@ is allowed when parsing. A `+' would need to be quoted. Don't use parseUnqt! ----------------------------------------------------------------------------- | The mapping used for 'FontName' values in SVG output. More information can be found at <>. ^ Use the legal generic SVG font names. ^ Use PostScript font names. ^ Use fontconfig font conventions. ----------------------------------------------------------------------------- | Maximum width and height of drawing in inches. | If @Nothing@, then the height is the same as the width. | If drawing is smaller than specified size, this value determines whether it is scaled up. ----------------------------------------------------------------------------- | For 'Neato' unless indicated otherwise. ----------------------------------------------------------------------------- ----------------------------------------------------------------------------- 'Html.Label' value is the entire \"shape\"; if anything else the 'Html.Label' is embedded within the shape. ^ For nodes only; requires either 'Record' or 'MRecord' as the shape. Don't have to worry about being able to tell the difference since the latter will be in quotes and the former won't. ----------------------------------------------------------------------------- | Specifies the sub-values of a record-based label. By default, the orientation of the fields (can be applied recursively). To ^ Will result in no label for that cell. will cause parsing problems for other 'Label' types. | Print a 'PortName' value as expected within a Record data structure. ----------------------------------------------------------------------------- | How to treat a node whose name is of the form \"@|edgelabel|*@\" as a special node representing an edge label. ^ No effect ^ Make node close to center of neighbor ^ Make node close to old center of neighbor Use string-based parsing rather than parsing an integer just to make it easier ----------------------------------------------------------------------------- | Can only be 'Just' for @'Dim' 3@ or greater. node position should not change. | Create a point with only @x@ and @y@ values. ----------------------------------------------------------------------------- | How to deal with node overlaps. Defaults to 'KeepOverlaps' /except/ for 'Fdp' and 'Sfdp'. The ability to specify the number of tries for 'Fdp''s initial @9@ passes of its in-built technique, and then @'PrismOverlap' Nothing@). ^ Remove overlaps by uniformly scaling in x and y. ^ Remove overlaps by separately scaling x and y. ^ Requires the Prism library to be available (if not, this is equivalent to is equivalent to Influenced by 'OverlapScaling'. possible without introducing overlaps, assuming none to begin with. ^ Uses quadratic optimization to minimize node displacement. ^ Only when @mode == 'IpSep'@ but if the Prism library isn't available then it is equivalent to ----------------------------------------------------------------------------- | You should not have any layer separator characters for the ^ Should not be a number or @"all"@. Might not need quotes, but probably will. Can't tell either way since we don't know what the separator character will be. tests for Int and All Mainly for unquoted case. Remember: this /must/ be a newtype as we can't use arbitrary LayerID values! | A list of layer names. The names should all be unique 'LRName' values, and when printed will use an arbitrary character from 'defLayerSep'. The values in the list are implicitly numbered ----------------------------------------------------------------------------- ^ Draw outgoing edges in order specified. ^ Draw incoming edges in order specified. ----------------------------------------------------------------------------- ----------------------------------------------------------------------------- ^ If non-negative, then packs; otherwise doesn't. What happens if it parses 0? It's non-negative, but parses as False ----------------------------------------------------------------------------- ^ Sort by cols, sort by user, number of rows/cols Also checks and removes quote characters ----------------------------------------------------------------------------- then a spline with no start and end points will erroneously get parsed as a point and then the parser will crash as it expects a closing quote character... ----------------------------------------------------------------------------- | Controls how (and if) edges are represented. For 'Dot', the default is 'SplineEdges'; for all other layouts the default is 'LineEdges'. ^ Except for 'Dot', requires non-overlapping nodes (see 'Overlap'). ^ Does not handle ports or edge labels in 'Dot'. ^ 'Fdp' only ----------------------------------------------------------------------------- ----------------------------------------------------------------------------- note that this is not checked. ----------------------------------------------------------------------------- Have to take into account the slightly different interpretation weird bool ----------------------------------------------------------------------------- ^ For Nodes only ^ For Nodes only ^ For Graphs only ----------------------------------------------------------------------------- ----------------------------------------------------------------------------- ----------------------------------------------------------------------------- | Geometries of shapes are affected by the attributes 'Regular', 'Peripheries' and 'Orientation'. ^ Also affected by 'Sides', 'Skew' and 'Distortion'. ^ Has synonym of /oval/. 'Height'. ^ Has synonym of /none/. Recommended for ^ Requires Graphviz >= 2.32.0. ^ Must specify the record shape with a 'Label'. ^ Must specify the record shape with a 'Label'. ----------------------------------------------------------------------------- ----------------------------------------------------------------------------- ----------------------------------------------------------------------------- | An individual style item. Except for 'DD', the @['String']@ should be empty. Might not necessarily need to be quoted if a singleton... ^ Nodes and Edges ^ Nodes and Edges ^ Nodes and Edges ^ Nodes and Edges ^ Nodes and Edges ^ Nodes and Clusters ^ Rectangularly-shaped Nodes and ^ Elliptically-shaped Nodes only; ^ Nodes only ^ Nodes and Clusters ^ Nodes, Clusters and Graphs, for use ^ Device Dependent ----------------------------------------------------------------------------- | For use with 'ViewPort'. ----------------------------------------------------------------------------- ^ Only valid for Nodes. ----------------------------------------------------------------------------- | A list of search paths. ----------------------------------------------------------------------------- ----------------------------------------------------------------------------- ----------------------------------------------------------------------------- ----------------------------------------------------------------------------- | A numeric type with an explicit separation between integers and floating-point values. ----------------------------------------------------------------------------- normalized. Requires Graphviz >= 2.32.0. ----------------------------------------------------------------------------- | Determine how the 'Width' and 'Height' attributes specify the size of nodes. ^ Nodes will be the smallest width and height needed to contain the label and any possible allowed sizes. with a warning if the label cannot fit in this. shape only and the label can expand out of the shape (with a warning). Requires Graphviz >= -----------------------------------------------------------------------------
# LANGUAGE CPP , OverloadedStrings # | Module : Data . GraphViz . Attributes . Values Description : Values for use with the Attribute data type Copyright : ( c ) License : 3 - Clause BSD - style Maintainer : Defined to have smaller modules and thus faster compilation times . Module : Data.GraphViz.Attributes.Values Description : Values for use with the Attribute data type Copyright : (c) Ivan Lazar Miljenovic License : 3-Clause BSD-style Maintainer : Defined to have smaller modules and thus faster compilation times. -} module Data.GraphViz.Attributes.Values where import qualified Data.GraphViz.Attributes.HTML as Html import Data.GraphViz.Attributes.Internal import Data.GraphViz.Internal.State (getLayerListSep, getLayerSep, setLayerListSep, setLayerSep) import Data.GraphViz.Internal.Util (bool, stringToInt) import Data.GraphViz.Parsing import Data.GraphViz.Printing import Data.List (intercalate) import Data.Maybe (isJust) import Data.Text.Lazy (Text) import qualified Data.Text.Lazy as T import Data.Word (Word16) import System.FilePath (searchPathSeparator, splitSearchPath) #if !MIN_VERSION_base (4,13,0) import Data.Monoid ((<>)) #endif | Some ' Attribute 's ( mainly label - like ones ) take a ' String ' argument that allows for extra escape codes . This library does n't do any extra checks or special parsing for these escape codes , but usage of ' EscString ' rather than ' Text ' indicates that the Graphviz tools will recognise these extra escape codes for these ' Attribute 's . The extra escape codes include ( note that these are all Strings ): [ @\\N@ ] Replace with the name of the node ( for Node ' Attribute 's ) . [ @\\G@ ] Replace with the name of the graph ( for Node ' Attribute 's ) or the name of the graph or cluster , whichever is applicable ( for Graph , Cluster and Edge ' Attribute 's ) . [ ] Replace with the name of the edge , formed by the two adjoining nodes and the edge type ( for Edge ' Attribute 's ) . [ @\\T@ ] Replace with the name of the tail node ( for Edge ' Attribute 's ) . [ @\\H@ ] Replace with the name of the head node ( for Edge ' Attribute 's ) . [ @\\L@ ] Replace with the object 's label ( for all ' Attribute 's ) . Also , if the ' Attribute ' in question is ' Label ' , ' HeadLabel ' or ' TailLabel ' , then , @\\l@ and @\\r@ split the label into lines centered , left - justified and right - justified respectively . Some 'Attribute's (mainly label-like ones) take a 'String' argument that allows for extra escape codes. This library doesn't do any extra checks or special parsing for these escape codes, but usage of 'EscString' rather than 'Text' indicates that the Graphviz tools will recognise these extra escape codes for these 'Attribute's. The extra escape codes include (note that these are all Strings): [@\\N@] Replace with the name of the node (for Node 'Attribute's). [@\\G@] Replace with the name of the graph (for Node 'Attribute's) or the name of the graph or cluster, whichever is applicable (for Graph, Cluster and Edge 'Attribute's). [@\\E@] Replace with the name of the edge, formed by the two adjoining nodes and the edge type (for Edge 'Attribute's). [@\\T@] Replace with the name of the tail node (for Edge 'Attribute's). [@\\H@] Replace with the name of the head node (for Edge 'Attribute's). [@\\L@] Replace with the object's label (for all 'Attribute's). Also, if the 'Attribute' in question is 'Label', 'HeadLabel' or 'TailLabel', then @\\n@, @\\l@ and @\\r@ split the label into lines centered, left-justified and right-justified respectively. -} type EscString = Text data Rect = Rect Point Point deriving (Eq, Ord, Show, Read) instance PrintDot Rect where unqtDot (Rect p1 p2) = printPoint2DUnqt p1 <> comma <> printPoint2DUnqt p2 toDot = dquotes . unqtDot unqtListToDot = hsep . mapM unqtDot instance ParseDot Rect where parseUnqt = uncurry Rect <$> commaSep' parsePoint2D parsePoint2D parse = quotedParse parseUnqt parseUnqtList = sepBy1 parseUnqt whitespace1 treatment . ' Global ' and ' NoCluster ' currently appear to be data ClusterMode = Local | Global | NoCluster deriving (Eq, Ord, Bounded, Enum, Show, Read) instance PrintDot ClusterMode where unqtDot Local = text "local" unqtDot Global = text "global" unqtDot NoCluster = text "none" instance ParseDot ClusterMode where parseUnqt = oneOf [ stringRep Local "local" , stringRep Global "global" , stringRep NoCluster "none" ] deriving (Eq, Ord, Bounded, Enum, Show, Read) instance PrintDot DirType where unqtDot Forward = text "forward" unqtDot Back = text "back" unqtDot Both = text "both" unqtDot NoDir = text "none" instance ParseDot DirType where parseUnqt = oneOf [ stringRep Forward "forward" , stringRep Back "back" , stringRep Both "both" , stringRep NoDir "none" ] | Only when @mode = = ' IpSep'@. data DEConstraints = EdgeConstraints | NoConstraints | HierConstraints deriving (Eq, Ord, Bounded, Enum, Show, Read) instance PrintDot DEConstraints where unqtDot EdgeConstraints = unqtDot True unqtDot NoConstraints = unqtDot False unqtDot HierConstraints = text "hier" instance ParseDot DEConstraints where parseUnqt = fmap (bool NoConstraints EdgeConstraints) parse `onFail` stringRep HierConstraints "hier" | Either a ' Double ' or a ( 2D ) ' Point ' ( i.e. created with Whilst it is possible to create a ' Point ' value with either a third co - ordinate or a forced position , these are ignored for data DPoint = DVal Double | PVal Point deriving (Eq, Ord, Show, Read) instance PrintDot DPoint where unqtDot (DVal d) = unqtDot d unqtDot (PVal p) = printPoint2DUnqt p toDot (DVal d) = toDot d toDot (PVal p) = printPoint2D p instance ParseDot DPoint where parseUnqt = optional (character '+') *> oneOf [ PVal <$> parsePoint2D , DVal <$> parseUnqt ] `onFail` deriving (Eq, Ord, Bounded, Enum, Show, Read) instance PrintDot SVGFontNames where unqtDot SvgNames = text "svg" unqtDot PostScriptNames = text "ps" unqtDot FontConfigNames = text "gd" instance ParseDot SVGFontNames where parseUnqt = oneOf [ stringRep SvgNames "svg" , stringRep PostScriptNames "ps" , stringRep FontConfigNames "gd" ] parse = stringRep SvgNames "\"\"" `onFail` optionalQuoted parseUnqt data GraphSize = GSize { width :: Double , height :: Maybe Double , desiredSize :: Bool } deriving (Eq, Ord, Show, Read) instance PrintDot GraphSize where unqtDot (GSize w mh ds) = bool id (<> char '!') ds . maybe id (\h -> (<> unqtDot h) . (<> comma)) mh $ unqtDot w toDot (GSize w Nothing False) = toDot w toDot gs = dquotes $ unqtDot gs instance ParseDot GraphSize where parseUnqt = GSize <$> parseUnqt <*> optional (parseComma *> whitespace *> parseUnqt) <*> (isJust <$> optional (character '!')) parse = quotedParse parseUnqt `onFail` fmap (\ w -> GSize w Nothing False) (parseSignedFloat False) data ModeType = Major | KK | Hier | IpSep ^ For ' Sfdp ' , requires Graphviz > = 2.32.0 . ^ For ' Sfdp ' , requires Graphviz > = 2.32.0 . deriving (Eq, Ord, Bounded, Enum, Show, Read) instance PrintDot ModeType where unqtDot Major = text "major" unqtDot KK = text "KK" unqtDot Hier = text "hier" unqtDot IpSep = text "ipsep" unqtDot SpringMode = text "spring" unqtDot MaxEnt = text "maxent" instance ParseDot ModeType where parseUnqt = oneOf [ stringRep Major "major" , stringRep KK "KK" , stringRep Hier "hier" , stringRep IpSep "ipsep" , stringRep SpringMode "spring" , stringRep MaxEnt "maxent" ] data Model = ShortPath | SubSet | Circuit | MDS deriving (Eq, Ord, Bounded, Enum, Show, Read) instance PrintDot Model where unqtDot ShortPath = text "shortpath" unqtDot SubSet = text "subset" unqtDot Circuit = text "circuit" unqtDot MDS = text "mds" instance ParseDot Model where parseUnqt = oneOf [ stringRep ShortPath "shortpath" , stringRep SubSet "subset" , stringRep Circuit "circuit" , stringRep MDS "mds" ] data Label = StrLabel EscString ^ If ' PlainText ' is used , the except ' PointShape ' is used then deriving (Eq, Ord, Show, Read) instance PrintDot Label where unqtDot (StrLabel s) = unqtDot s unqtDot (HtmlLabel h) = angled $ unqtDot h unqtDot (RecordLabel fs) = unqtDot fs toDot (StrLabel s) = toDot s toDot h@HtmlLabel{} = unqtDot h toDot (RecordLabel fs) = toDot fs instance ParseDot Label where between an HtmlLabel and a RecordLabel starting with a PortPos , parseUnqt = oneOf [ HtmlLabel <$> parseAngled parseUnqt , RecordLabel <$> parseUnqt , StrLabel <$> parseUnqt ] parse = oneOf [ HtmlLabel <$> parseAngled parse , RecordLabel <$> parse , StrLabel <$> parse ] | A RecordFields value should never be empty . type RecordFields = [RecordField] the cells are laid out horizontally ; use ' FlipFields ' to change change the default orientation , use ' RankDir ' . data RecordField = LabelledTarget PortName EscString | FieldLabel EscString | FlipFields RecordFields deriving (Eq, Ord, Show, Read) instance PrintDot RecordField where Have to use ' printPortName ' to add the @\'<\'@ and @\'>\'@. unqtDot (LabelledTarget t s) = printPortName t <+> unqtRecordString s unqtDot (PortName t) = printPortName t unqtDot (FieldLabel s) = unqtRecordString s unqtDot (FlipFields rs) = braces $ unqtDot rs toDot (FieldLabel s) = printEscaped recordEscChars s toDot rf = dquotes $ unqtDot rf unqtListToDot [f] = unqtDot f unqtListToDot fs = hcat . punctuate (char '|') $ mapM unqtDot fs listToDot [f] = toDot f listToDot fs = dquotes $ unqtListToDot fs instance ParseDot RecordField where parseUnqt = (liftA2 maybe PortName LabelledTarget <$> (PN <$> parseAngled parseRecord) <*> optional (whitespace1 *> parseRecord) ) `onFail` fmap FieldLabel parseRecord `onFail` fmap FlipFields (parseBraced parseUnqt) `onFail` fail "Unable to parse RecordField" parse = quotedParse parseUnqt parseUnqtList = wrapWhitespace $ sepBy1 parseUnqt (wrapWhitespace $ character '|') Note : a singleton unquoted ' FieldLabel ' is /not/ valid , as it parseList = do rfs <- quotedParse parseUnqtList if validRFs rfs then return rfs else fail "This is a StrLabel, not a RecordLabel" where validRFs [FieldLabel str] = T.any (`elem` recordEscChars) str validRFs _ = True printPortName :: PortName -> DotCode printPortName = angled . unqtRecordString . portName parseRecord :: Parse Text parseRecord = parseEscaped False recordEscChars [] unqtRecordString :: Text -> DotCode unqtRecordString = unqtEscaped recordEscChars recordEscChars :: [Char] recordEscChars = ['{', '}', '|', ' ', '<', '>'] ^ Use a two - step process . deriving (Eq, Ord, Bounded, Enum, Show, Read) instance PrintDot LabelScheme where unqtDot NotEdgeLabel = int 0 unqtDot CloseToCenter = int 1 unqtDot CloseToOldCenter = int 2 unqtDot RemoveAndStraighten = int 3 instance ParseDot LabelScheme where parseUnqt = stringValue [ ("0", NotEdgeLabel) , ("1", CloseToCenter) , ("2", CloseToOldCenter) , ("3", RemoveAndStraighten) ] data Point = Point { xCoord :: Double , yCoord :: Double , zCoord :: Maybe Double | Input to Graphviz only : specify that the , forcePos :: Bool } deriving (Eq, Ord, Show, Read) createPoint :: Double -> Double -> Point createPoint x y = Point x y Nothing False printPoint2DUnqt :: Point -> DotCode printPoint2DUnqt p = commaDel (xCoord p) (yCoord p) printPoint2D :: Point -> DotCode printPoint2D = dquotes . printPoint2DUnqt parsePoint2D :: Parse Point parsePoint2D = uncurry createPoint <$> commaSepUnqt instance PrintDot Point where unqtDot (Point x y mz frs) = bool id (<> char '!') frs . maybe id (\ z -> (<> unqtDot z) . (<> comma)) mz $ commaDel x y toDot = dquotes . unqtDot unqtListToDot = hsep . mapM unqtDot listToDot = dquotes . unqtListToDot instance ParseDot Point where parseUnqt = uncurry Point <$> commaSepUnqt <*> optional (parseComma *> parseUnqt) <*> (isJust <$> optional (character '!')) parse = quotedParse parseUnqt parseUnqtList = sepBy1 parseUnqt whitespace1 force - directed technique is /not/ supported ( by default , ' Fdp ' uses For ' Sfdp ' , the default is @'PrismOverlap ' ( Just 0)@. data Overlap = KeepOverlaps ' ' ) . @'Nothing'@ @'Just ' 1000@. ^ Requires Graphviz > = 2.30.0 . ^ Scale layout down as much as deriving (Eq, Ord, Show, Read) instance PrintDot Overlap where unqtDot KeepOverlaps = unqtDot True unqtDot ScaleOverlaps = text "scale" unqtDot ScaleXYOverlaps = text "scalexy" unqtDot (PrismOverlap i) = maybe id (flip (<>) . unqtDot) i $ text "prism" unqtDot VoronoiOverlap = text "voronoi" unqtDot CompressOverlap = text "compress" unqtDot VpscOverlap = text "vpsc" unqtDot IpsepOverlap = text "ipsep" | Note that = false@ defaults to @'PrismOverlap ' Nothing@ , ' ' . instance ParseDot Overlap where parseUnqt = oneOf [ stringRep KeepOverlaps "true" , stringRep ScaleXYOverlaps "scalexy" , stringRep ScaleOverlaps "scale" , string "prism" *> fmap PrismOverlap (optional parse) , stringRep (PrismOverlap Nothing) "false" , stringRep VoronoiOverlap "voronoi" , stringRep CompressOverlap "compress" , stringRep VpscOverlap "vpsc" , stringRep IpsepOverlap "ipsep" ] newtype LayerSep = LSep Text deriving (Eq, Ord, Show, Read) instance PrintDot LayerSep where unqtDot (LSep ls) = setLayerSep (T.unpack ls) *> unqtDot ls toDot (LSep ls) = setLayerSep (T.unpack ls) *> toDot ls instance ParseDot LayerSep where parseUnqt = do ls <- parseUnqt setLayerSep $ T.unpack ls return $ LSep ls parse = do ls <- parse setLayerSep $ T.unpack ls return $ LSep ls newtype LayerListSep = LLSep Text deriving (Eq, Ord, Show, Read) instance PrintDot LayerListSep where unqtDot (LLSep ls) = setLayerListSep (T.unpack ls) *> unqtDot ls toDot (LLSep ls) = setLayerListSep (T.unpack ls) *> toDot ls instance ParseDot LayerListSep where parseUnqt = do ls <- parseUnqt setLayerListSep $ T.unpack ls return $ LLSep ls parse = do ls <- parse setLayerListSep $ T.unpack ls return $ LLSep ls type LayerRange = [LayerRangeElem] data LayerRangeElem = LRID LayerID | LRS LayerID LayerID deriving (Eq, Ord, Show, Read) instance PrintDot LayerRangeElem where unqtDot (LRID lid) = unqtDot lid unqtDot (LRS id1 id2) = do ls <- getLayerSep let s = unqtDot $ head ls unqtDot id1 <> s <> unqtDot id2 toDot (LRID lid) = toDot lid toDot lrs = dquotes $ unqtDot lrs unqtListToDot lr = do lls <- getLayerListSep let s = unqtDot $ head lls hcat . punctuate s $ mapM unqtDot lr listToDot [lre] = toDot lre listToDot lrs = dquotes $ unqtListToDot lrs instance ParseDot LayerRangeElem where parseUnqt = ignoreSep LRS parseUnqt parseLayerSep parseUnqt `onFail` fmap LRID parseUnqt parse = quotedParse (ignoreSep LRS parseUnqt parseLayerSep parseUnqt) `onFail` fmap LRID parse parseUnqtList = sepBy parseUnqt parseLayerListSep parseList = quotedParse parseUnqtList `onFail` fmap ((:[]) . LRID) parse parseLayerSep :: Parse () parseLayerSep = do ls <- getLayerSep many1Satisfy (`elem` ls) *> return () parseLayerName :: Parse Text parseLayerName = parseEscaped False [] =<< liftA2 (++) getLayerSep getLayerListSep parseLayerName' :: Parse Text parseLayerName' = stringBlock `onFail` quotedParse parseLayerName parseLayerListSep :: Parse () parseLayerListSep = do lls <- getLayerListSep many1Satisfy (`elem` lls) *> return () ' LRName ' option , as they wo n't be parseable . data LayerID = AllLayers | LRInt Int deriving (Eq, Ord, Show, Read) instance PrintDot LayerID where unqtDot AllLayers = text "all" unqtDot (LRInt n) = unqtDot n unqtDot (LRName nm) = unqtDot nm toDot (LRName nm) = toDot nm Other two do n't need quotes toDot li = unqtDot li unqtListToDot ll = do ls <- getLayerSep let s = unqtDot $ head ls hcat . punctuate s $ mapM unqtDot ll listToDot [l] = toDot l listToDot ll = dquotes $ unqtDot ll instance ParseDot LayerID where parse = oneOf [ checkLayerName <$> parseLayerName' ] checkLayerName :: Text -> LayerID checkLayerName str = maybe checkAll LRInt $ stringToInt str where checkAll = if T.toLower str == "all" then AllLayers else LRName str @1 , 2 , ... @. newtype LayerList = LL [LayerID] deriving (Eq, Ord, Show, Read) instance PrintDot LayerList where unqtDot (LL ll) = unqtDot ll toDot (LL ll) = toDot ll instance ParseDot LayerList where parseUnqt = LL <$> sepBy1 parseUnqt parseLayerSep parse = quotedParse parseUnqt `onFail` fmap (LL . (:[]) . LRName) stringBlock `onFail` quotedParse (stringRep (LL []) "") deriving (Eq, Ord, Bounded, Enum, Show, Read) instance PrintDot Order where unqtDot OutEdges = text "out" unqtDot InEdges = text "in" instance ParseDot Order where parseUnqt = oneOf [ stringRep OutEdges "out" , stringRep InEdges "in" ] data OutputMode = BreadthFirst | NodesFirst | EdgesFirst deriving (Eq, Ord, Bounded, Enum, Show, Read) instance PrintDot OutputMode where unqtDot BreadthFirst = text "breadthfirst" unqtDot NodesFirst = text "nodesfirst" unqtDot EdgesFirst = text "edgesfirst" instance ParseDot OutputMode where parseUnqt = oneOf [ stringRep BreadthFirst "breadthfirst" , stringRep NodesFirst "nodesfirst" , stringRep EdgesFirst "edgesfirst" ] data Pack = DoPack | DontPack deriving (Eq, Ord, Show, Read) instance PrintDot Pack where unqtDot DoPack = unqtDot True unqtDot DontPack = unqtDot False unqtDot (PackMargin m) = unqtDot m instance ParseDot Pack where parseUnqt = oneOf [ PackMargin <$> parseUnqt , bool DontPack DoPack <$> onlyBool ] data PackMode = PackNode | PackClust | PackGraph deriving (Eq, Ord, Show, Read) instance PrintDot PackMode where unqtDot PackNode = text "node" unqtDot PackClust = text "clust" unqtDot PackGraph = text "graph" unqtDot (PackArray c u mi) = addNum . isU . isC . isUnder $ text "array" where addNum = maybe id (flip (<>) . unqtDot) mi isUnder = if c || u then (<> char '_') else id isC = if c then (<> char 'c') else id isU = if u then (<> char 'u') else id instance ParseDot PackMode where parseUnqt = oneOf [ stringRep PackNode "node" , stringRep PackClust "clust" , stringRep PackGraph "graph" , do string "array" mcu <- optional $ character '_' *> many1 (satisfy isCU) let c = hasCharacter mcu 'c' u = hasCharacter mcu 'u' mi <- optional parseUnqt return $ PackArray c u mi ] where hasCharacter ms c = maybe False (elem c) ms isCU = (`elem` ['c', 'u']) data Pos = PointPos Point | SplinePos [Spline] deriving (Eq, Ord, Show, Read) instance PrintDot Pos where unqtDot (PointPos p) = unqtDot p unqtDot (SplinePos ss) = unqtDot ss toDot (PointPos p) = toDot p toDot (SplinePos ss) = toDot ss instance ParseDot Pos where Have to be careful with this : if we try to parse points first , parseUnqt = do splns <- parseUnqt case splns of [Spline Nothing Nothing [p]] -> return $ PointPos p _ -> return $ SplinePos splns parse = quotedParse parseUnqt | LineEdges | NoEdges | PolyLine ^ Requires Graphviz > = 2.30.0 . deriving (Eq, Ord, Bounded, Enum, Show, Read) instance PrintDot EdgeType where unqtDot SplineEdges = text "spline" unqtDot LineEdges = text "line" unqtDot NoEdges = empty unqtDot PolyLine = text "polyline" unqtDot Ortho = text "ortho" unqtDot Curved = text "curved" unqtDot CompoundEdge = text "compound" toDot NoEdges = dquotes empty toDot et = unqtDot et instance ParseDot EdgeType where Ca n't parse without quotes . parseUnqt = oneOf [ bool LineEdges SplineEdges <$> parse , stringRep SplineEdges "spline" , stringRep LineEdges "line" , stringRep NoEdges "none" , stringRep PolyLine "polyline" , stringRep Ortho "ortho" , stringRep Curved "curved" , stringRep CompoundEdge "compound" ] parse = stringRep NoEdges "\"\"" `onFail` optionalQuoted parseUnqt | Upper - case first character is major order ; lower - case second character is minor order . data PageDir = Bl | Br | Tl | Tr | Rb | Rt | Lb | Lt deriving (Eq, Ord, Bounded, Enum, Show, Read) instance PrintDot PageDir where unqtDot Bl = text "BL" unqtDot Br = text "BR" unqtDot Tl = text "TL" unqtDot Tr = text "TR" unqtDot Rb = text "RB" unqtDot Rt = text "RT" unqtDot Lb = text "LB" unqtDot Lt = text "LT" instance ParseDot PageDir where parseUnqt = stringValue [ ("BL", Bl) , ("BR", Br) , ("TL", Tl) , ("TR", Tr) , ("RB", Rb) , ("RT", Rt) , ("LB", Lb) , ("LT", Lt) ] | The number of points in the list must be equivalent to 1 mod 3 ; data Spline = Spline { endPoint :: Maybe Point , startPoint :: Maybe Point , splinePoints :: [Point] } deriving (Eq, Ord, Show, Read) instance PrintDot Spline where unqtDot (Spline me ms ps) = addE . addS . hsep $ mapM unqtDot ps where addP t = maybe id ((<+>) . commaDel t) addS = addP 's' ms addE = addP 'e' me toDot = dquotes . unqtDot unqtListToDot = hcat . punctuate semi . mapM unqtDot listToDot = dquotes . unqtListToDot instance ParseDot Spline where parseUnqt = Spline <$> parseP 'e' <*> parseP 's' <*> sepBy1 parseUnqt whitespace1 where parseP t = optional (character t *> parseComma *> parseUnqt <* whitespace1) parse = quotedParse parseUnqt parseUnqtList = sepBy1 parseUnqt (character ';') data QuadType = NormalQT | FastQT | NoQT deriving (Eq, Ord, Bounded, Enum, Show, Read) instance PrintDot QuadType where unqtDot NormalQT = text "normal" unqtDot FastQT = text "fast" unqtDot NoQT = text "none" instance ParseDot QuadType where of used as an option for parsing QuadType parseUnqt = oneOf [ stringRep NormalQT "normal" , stringRep FastQT "fast" , stringRep NoQT "none" , bool NoQT NormalQT <$> parse ] | Specify the root node either as a Node attribute or a attribute . deriving (Eq, Ord, Show, Read) instance PrintDot Root where unqtDot IsCentral = unqtDot True unqtDot NotCentral = unqtDot False unqtDot (NodeName n) = unqtDot n toDot (NodeName n) = toDot n toDot r = unqtDot r instance ParseDot Root where parseUnqt = fmap (bool NotCentral IsCentral) onlyBool `onFail` fmap NodeName parseUnqt parse = optionalQuoted (bool NotCentral IsCentral <$> onlyBool) `onFail` fmap NodeName parse data RankType = SameRank | MinRank | SourceRank | MaxRank | SinkRank deriving (Eq, Ord, Bounded, Enum, Show, Read) instance PrintDot RankType where unqtDot SameRank = text "same" unqtDot MinRank = text "min" unqtDot SourceRank = text "source" unqtDot MaxRank = text "max" unqtDot SinkRank = text "sink" instance ParseDot RankType where parseUnqt = stringValue [ ("same", SameRank) , ("min", MinRank) , ("source", SourceRank) , ("max", MaxRank) , ("sink", SinkRank) ] data RankDir = FromTop | FromLeft | FromBottom | FromRight deriving (Eq, Ord, Bounded, Enum, Show, Read) instance PrintDot RankDir where unqtDot FromTop = text "TB" unqtDot FromLeft = text "LR" unqtDot FromBottom = text "BT" unqtDot FromRight = text "RL" instance ParseDot RankDir where parseUnqt = oneOf [ stringRep FromTop "TB" , stringRep FromLeft "LR" , stringRep FromBottom "BT" , stringRep FromRight "RL" ] data Shape ^ Has synonyms of /rect/ and /rectangle/. | Circle ^ Only affected by ' Peripheries ' , ' ' and | Egg | Triangle ' HtmlLabel 's . | DiamondShape | Trapezium | Parallelogram | House | Pentagon | Hexagon | Septagon | Octagon | DoubleCircle | DoubleOctagon | TripleOctagon | InvTriangle | InvTrapezium | InvHouse | MDiamond | MSquare | MCircle | Square ^ Requires Graphviz > = 2.36.0 . | Note | Tab | Folder | Box3D | Component ^ Requires Graphviz > = 2.30.0 . ^ Requires Graphviz > = 2.30.0 . ^ Requires Graphviz > = 2.30.0 . ^ Requires Graphviz > = 2.30.0 . ^ Requires Graphviz > = 2.30.0 . ^ Requires Graphviz > = 2.30.0 . ^ Requires Graphviz > = 2.30.0 . ^ Requires Graphviz > = 2.30.0 . ^ Requires Graphviz > = 2.30.0 . ^ Requires Graphviz > = 2.30.0 . ^ Requires Graphviz > = 2.30.0 . ^ Requires Graphviz > = 2.30.0 . ^ Requires Graphviz > = 2.30.0 . ^ Requires Graphviz > = 2.30.0 . ^ Requires Graphviz > = 2.30.0 . ^ Requires Graphviz > = 2.30.0 . ^ Requires Graphviz > = 2.30.0 . ^ Requires Graphviz > = 2.30.0 . ^ Requires Graphviz > = 2.30.0 . ^ Requires Graphviz > = 2.30.0 . deriving (Eq, Ord, Bounded, Enum, Show, Read) instance PrintDot Shape where unqtDot BoxShape = text "box" unqtDot Polygon = text "polygon" unqtDot Ellipse = text "ellipse" unqtDot Circle = text "circle" unqtDot PointShape = text "point" unqtDot Egg = text "egg" unqtDot Triangle = text "triangle" unqtDot PlainText = text "plaintext" unqtDot DiamondShape = text "diamond" unqtDot Trapezium = text "trapezium" unqtDot Parallelogram = text "parallelogram" unqtDot House = text "house" unqtDot Pentagon = text "pentagon" unqtDot Hexagon = text "hexagon" unqtDot Septagon = text "septagon" unqtDot Octagon = text "octagon" unqtDot DoubleCircle = text "doublecircle" unqtDot DoubleOctagon = text "doubleoctagon" unqtDot TripleOctagon = text "tripleoctagon" unqtDot InvTriangle = text "invtriangle" unqtDot InvTrapezium = text "invtrapezium" unqtDot InvHouse = text "invhouse" unqtDot MDiamond = text "Mdiamond" unqtDot MSquare = text "Msquare" unqtDot MCircle = text "Mcircle" unqtDot Square = text "square" unqtDot Star = text "star" unqtDot Underline = text "underline" unqtDot Note = text "note" unqtDot Tab = text "tab" unqtDot Folder = text "folder" unqtDot Box3D = text "box3d" unqtDot Component = text "component" unqtDot Promoter = text "promoter" unqtDot CDS = text "cds" unqtDot Terminator = text "terminator" unqtDot UTR = text "utr" unqtDot PrimerSite = text "primersite" unqtDot RestrictionSite = text "restrictionsite" unqtDot FivePovOverhang = text "fivepovoverhang" unqtDot ThreePovOverhang = text "threepovoverhang" unqtDot NoOverhang = text "nooverhang" unqtDot Assembly = text "assembly" unqtDot Signature = text "signature" unqtDot Insulator = text "insulator" unqtDot Ribosite = text "ribosite" unqtDot RNAStab = text "rnastab" unqtDot ProteaseSite = text "proteasesite" unqtDot ProteinStab = text "proteinstab" unqtDot RPromoter = text "rpromoter" unqtDot RArrow = text "rarrow" unqtDot LArrow = text "larrow" unqtDot LPromoter = text "lpromoter" unqtDot Record = text "record" unqtDot MRecord = text "Mrecord" instance ParseDot Shape where parseUnqt = stringValue [ ("box3d", Box3D) , ("box", BoxShape) , ("rectangle", BoxShape) , ("rect", BoxShape) , ("polygon", Polygon) , ("ellipse", Ellipse) , ("oval", Ellipse) , ("circle", Circle) , ("point", PointShape) , ("egg", Egg) , ("triangle", Triangle) , ("plaintext", PlainText) , ("none", PlainText) , ("diamond", DiamondShape) , ("trapezium", Trapezium) , ("parallelogram", Parallelogram) , ("house", House) , ("pentagon", Pentagon) , ("hexagon", Hexagon) , ("septagon", Septagon) , ("octagon", Octagon) , ("doublecircle", DoubleCircle) , ("doubleoctagon", DoubleOctagon) , ("tripleoctagon", TripleOctagon) , ("invtriangle", InvTriangle) , ("invtrapezium", InvTrapezium) , ("invhouse", InvHouse) , ("Mdiamond", MDiamond) , ("Msquare", MSquare) , ("Mcircle", MCircle) , ("square", Square) , ("star", Star) , ("underline", Underline) , ("note", Note) , ("tab", Tab) , ("folder", Folder) , ("component", Component) , ("promoter", Promoter) , ("cds", CDS) , ("terminator", Terminator) , ("utr", UTR) , ("primersite", PrimerSite) , ("restrictionsite", RestrictionSite) , ("fivepovoverhang", FivePovOverhang) , ("threepovoverhang", ThreePovOverhang) , ("nooverhang", NoOverhang) , ("assembly", Assembly) , ("signature", Signature) , ("insulator", Insulator) , ("ribosite", Ribosite) , ("rnastab", RNAStab) , ("proteasesite", ProteaseSite) , ("proteinstab", ProteinStab) , ("rpromoter", RPromoter) , ("rarrow", RArrow) , ("larrow", LArrow) , ("lpromoter", LPromoter) , ("record", Record) , ("Mrecord", MRecord) ] data SmoothType = NoSmooth | AvgDist | GraphDist | PowerDist | RNG | Spring | TriangleSmooth deriving (Eq, Ord, Bounded, Enum, Show, Read) instance PrintDot SmoothType where unqtDot NoSmooth = text "none" unqtDot AvgDist = text "avg_dist" unqtDot GraphDist = text "graph_dist" unqtDot PowerDist = text "power_dist" unqtDot RNG = text "rng" unqtDot Spring = text "spring" unqtDot TriangleSmooth = text "triangle" instance ParseDot SmoothType where parseUnqt = oneOf [ stringRep NoSmooth "none" , stringRep AvgDist "avg_dist" , stringRep GraphDist "graph_dist" , stringRep PowerDist "power_dist" , stringRep RNG "rng" , stringRep Spring "spring" , stringRep TriangleSmooth "triangle" ] data StartType = StartStyle STStyle | StartSeed Int | StartStyleSeed STStyle Int deriving (Eq, Ord, Show, Read) instance PrintDot StartType where unqtDot (StartStyle ss) = unqtDot ss unqtDot (StartSeed s) = unqtDot s unqtDot (StartStyleSeed ss s) = unqtDot ss <> unqtDot s instance ParseDot StartType where parseUnqt = oneOf [ liftA2 StartStyleSeed parseUnqt parseUnqt , StartStyle <$> parseUnqt , StartSeed <$> parseUnqt ] data STStyle = RegularStyle | SelfStyle | RandomStyle deriving (Eq, Ord, Bounded, Enum, Show, Read) instance PrintDot STStyle where unqtDot RegularStyle = text "regular" unqtDot SelfStyle = text "self" unqtDot RandomStyle = text "random" instance ParseDot STStyle where parseUnqt = oneOf [ stringRep RegularStyle "regular" , stringRep SelfStyle "self" , stringRep RandomStyle "random" ] data StyleItem = SItem StyleName [Text] deriving (Eq, Ord, Show, Read) instance PrintDot StyleItem where unqtDot (SItem nm args) | null args = dnm | otherwise = dnm <> parens args' where dnm = unqtDot nm args' = hcat . punctuate comma $ mapM unqtDot args toDot si@(SItem nm args) | null args = toDot nm | otherwise = dquotes $ unqtDot si unqtListToDot = hcat . punctuate comma . mapM unqtDot listToDot [SItem nm []] = toDot nm listToDot sis = dquotes $ unqtListToDot sis instance ParseDot StyleItem where parseUnqt = liftA2 SItem parseUnqt (tryParseList' parseArgs) parse = quotedParse (liftA2 SItem parseUnqt parseArgs) `onFail` fmap (`SItem` []) parse parseUnqtList = sepBy1 parseUnqt (wrapWhitespace parseComma) parseList = quotedParse parseUnqtList `onFail` fmap return parse parseArgs :: Parse [Text] parseArgs = bracketSep (character '(') parseComma (character ')') parseStyleName Clusters ; requires Graphviz > = 2.30.0 requires Graphviz > = 2.30.0 ^ Edges only ; requires Graphviz > = 2.29.0 with ' GradientAngle ' ; requires Graphviz > = 2.29.0 deriving (Eq, Ord, Show, Read) instance PrintDot StyleName where unqtDot Dashed = text "dashed" unqtDot Dotted = text "dotted" unqtDot Solid = text "solid" unqtDot Bold = text "bold" unqtDot Invisible = text "invis" unqtDot Filled = text "filled" unqtDot Striped = text "striped" unqtDot Wedged = text "wedged" unqtDot Diagonals = text "diagonals" unqtDot Rounded = text "rounded" unqtDot Tapered = text "tapered" unqtDot Radial = text "radial" unqtDot (DD nm) = unqtDot nm toDot (DD nm) = toDot nm toDot sn = unqtDot sn instance ParseDot StyleName where parseUnqt = checkDD <$> parseStyleName parse = quotedParse parseUnqt `onFail` fmap checkDD quotelessString checkDD :: Text -> StyleName checkDD str = case T.toLower str of "dashed" -> Dashed "dotted" -> Dotted "solid" -> Solid "bold" -> Bold "invis" -> Invisible "filled" -> Filled "striped" -> Striped "wedged" -> Wedged "diagonals" -> Diagonals "rounded" -> Rounded "tapered" -> Tapered "radial" -> Radial _ -> DD str parseStyleName :: Parse Text parseStyleName = liftA2 T.cons (orEscaped . noneOf $ ' ' : disallowedChars) (parseEscaped True [] disallowedChars) where disallowedChars = [quoteChar, '(', ')', ','] Used because the first character has slightly stricter requirements than the rest . orSlash p = stringRep '\\' "\\\\" `onFail` p orEscaped = orQuote . orSlash data ViewPort = VP { wVal :: Double , hVal :: Double , zVal :: Double , focus :: Maybe FocusType } deriving (Eq, Ord, Show, Read) instance PrintDot ViewPort where unqtDot vp = maybe vs ((<>) (vs <> comma) . unqtDot) $ focus vp where vs = hcat . punctuate comma $ mapM (unqtDot . ($vp)) [wVal, hVal, zVal] toDot = dquotes . unqtDot instance ParseDot ViewPort where parseUnqt = VP <$> parseUnqt <* parseComma <*> parseUnqt <* parseComma <*> parseUnqt <*> optional (parseComma *> parseUnqt) parse = quotedParse parseUnqt data FocusType = XY Point | NodeFocus Text deriving (Eq, Ord, Show, Read) instance PrintDot FocusType where unqtDot (XY p) = unqtDot p unqtDot (NodeFocus nm) = unqtDot nm toDot (XY p) = toDot p toDot (NodeFocus nm) = toDot nm instance ParseDot FocusType where parseUnqt = fmap XY parseUnqt `onFail` fmap NodeFocus parseUnqt parse = fmap XY parse `onFail` fmap NodeFocus parse data VerticalPlacement = VTop | VBottom deriving (Eq, Ord, Bounded, Enum, Show, Read) instance PrintDot VerticalPlacement where unqtDot VTop = char 't' unqtDot VCenter = char 'c' unqtDot VBottom = char 'b' instance ParseDot VerticalPlacement where parseUnqt = oneOf [ stringReps VTop ["top", "t"] , stringReps VCenter ["centre", "center", "c"] , stringReps VBottom ["bottom", "b"] ] newtype Paths = Paths { paths :: [FilePath] } deriving (Eq, Ord, Show, Read) instance PrintDot Paths where unqtDot = unqtDot . intercalate [searchPathSeparator] . paths toDot (Paths [p]) = toDot p toDot ps = dquotes $ unqtDot ps instance ParseDot Paths where parseUnqt = Paths . splitSearchPath <$> parseUnqt parse = quotedParse parseUnqt `onFail` fmap (Paths . (:[]) . T.unpack) quotelessString data ScaleType = UniformScale | NoScale | FillWidth | FillHeight | FillBoth deriving (Eq, Ord, Bounded, Enum, Show, Read) instance PrintDot ScaleType where unqtDot UniformScale = unqtDot True unqtDot NoScale = unqtDot False unqtDot FillWidth = text "width" unqtDot FillHeight = text "height" unqtDot FillBoth = text "both" instance ParseDot ScaleType where parseUnqt = oneOf [ stringRep UniformScale "true" , stringRep NoScale "false" , stringRep FillWidth "width" , stringRep FillHeight "height" , stringRep FillBoth "both" ] data Justification = JLeft | JRight | JCenter deriving (Eq, Ord, Bounded, Enum, Show, Read) instance PrintDot Justification where unqtDot JLeft = char 'l' unqtDot JRight = char 'r' unqtDot JCenter = char 'c' instance ParseDot Justification where parseUnqt = oneOf [ stringReps JLeft ["left", "l"] , stringReps JRight ["right", "r"] , stringReps JCenter ["center", "centre", "c"] ] data Ratios = AspectRatio Double | FillRatio | CompressRatio | ExpandRatio | AutoRatio deriving (Eq, Ord, Show, Read) instance PrintDot Ratios where unqtDot (AspectRatio r) = unqtDot r unqtDot FillRatio = text "fill" unqtDot CompressRatio = text "compress" unqtDot ExpandRatio = text "expand" unqtDot AutoRatio = text "auto" toDot (AspectRatio r) = toDot r toDot r = unqtDot r instance ParseDot Ratios where parseUnqt = parseRatio True parse = quotedParse parseUnqt <|> parseRatio False parseRatio :: Bool -> Parse Ratios parseRatio q = oneOf [ AspectRatio <$> parseSignedFloat q , stringRep FillRatio "fill" , stringRep CompressRatio "compress" , stringRep ExpandRatio "expand" , stringRep AutoRatio "auto" ] data Number = Int Int | Dbl Double deriving (Eq, Ord, Show, Read) instance PrintDot Number where unqtDot (Int i) = unqtDot i unqtDot (Dbl d) = unqtDot d toDot (Int i) = toDot i toDot (Dbl d) = toDot d instance ParseDot Number where parseUnqt = parseNumber True parse = quotedParse parseUnqt <|> parseNumber False parseNumber :: Bool -> Parse Number parseNumber q = Dbl <$> parseStrictFloat q <|> Int <$> parseUnqt | If set , normalizes coordinates such that the first point is at the origin and the first edge is at the angle if specified . ^ Equivalent to @'NormalizedAngle ' 0@. | NotNormalized ^ Angle of first edge when deriving (Eq, Ord, Show, Read) instance PrintDot Normalized where unqtDot IsNormalized = unqtDot True unqtDot NotNormalized = unqtDot False unqtDot (NormalizedAngle a) = unqtDot a toDot (NormalizedAngle a) = toDot a toDot norm = unqtDot norm instance ParseDot Normalized where parseUnqt = parseNormalized True parse = quotedParse parseUnqt <|> parseNormalized False parseNormalized :: Bool -> Parse Normalized parseNormalized q = NormalizedAngle <$> parseSignedFloat q <|> bool NotNormalized IsNormalized <$> onlyBool data NodeSize = GrowAsNeeded image . ' ' and ' Height ' are the minimum | SetNodeSize ^ ' ' and ' Height ' dictate the size of the node | SetShapeSize ^ ' ' and ' Height ' dictate the size of the 2.38.0 . deriving (Eq, Ord, Bounded, Enum, Show, Read) instance PrintDot NodeSize where unqtDot GrowAsNeeded = unqtDot False unqtDot SetNodeSize = unqtDot True unqtDot SetShapeSize = text "shape" instance ParseDot NodeSize where parseUnqt = bool GrowAsNeeded SetNodeSize <$> parseUnqt <|> stringRep SetShapeSize "shape" As of Graphviz 2.36.0 this was commented out ; as such it might come back , so leave this here in case we need it again . data AspectType = RatioOnly Double | RatioPassCount Double Int deriving ( Eq , Ord , Show , Read ) instance PrintDot AspectType where unqtDot ( RatioOnly r ) = unqtDot r unqtDot ( RatioPassCount r p ) = commaDel r p toDot at@RatioOnly { } = unqtDot at toDot at@RatioPassCount { } = dquotes $ unqtDot at instance ParseDot AspectType where parseUnqt = fmap ( uncurry RatioPassCount ) commaSepUnqt ` onFail ` fmap RatioOnly parseUnqt parse = ( uncurry RatioPassCount < $ > commaSepUnqt ) ` onFail ` fmap RatioOnly parse As of Graphviz 2.36.0 this was commented out; as such it might come back, so leave this here in case we need it again. data AspectType = RatioOnly Double | RatioPassCount Double Int deriving (Eq, Ord, Show, Read) instance PrintDot AspectType where unqtDot (RatioOnly r) = unqtDot r unqtDot (RatioPassCount r p) = commaDel r p toDot at@RatioOnly{} = unqtDot at toDot at@RatioPassCount{} = dquotes $ unqtDot at instance ParseDot AspectType where parseUnqt = fmap (uncurry RatioPassCount) commaSepUnqt `onFail` fmap RatioOnly parseUnqt parse = quotedParse (uncurry RatioPassCount <$> commaSepUnqt) `onFail` fmap RatioOnly parse -}
9d5e5e08e96d8b1792e07facef86ddd63278ee13df9a593a2bc67c7049dfe8e7
HugoPeters1024/hs-sleuth
Fold.hs
-- | Benchmark which formats paragraph, like the @sort@ unix utility. -- -- Tested in this benchmark: -- -- * Reading the file -- -- * Splitting into paragraphs -- -- * Reformatting the paragraphs to a certain line width -- * the results using the text builder -- -- * Writing back to a handle -- {-# LANGUAGE OverloadedStrings #-} module Benchmarks.Programs.Fold ( benchmark ) where import Data.List (foldl') import Data.List (intersperse) import Data.Monoid (mempty, mappend, mconcat) import System.IO (Handle) import Criterion (Benchmark, bench, whnfIO) import qualified Data.Text as T import qualified Data.Text.IO as T import qualified Data.Text.Lazy.Builder as TLB import qualified Data.Text.Lazy as TL import qualified Data.Text.Lazy.IO as TL benchmark :: FilePath -> Handle -> Benchmark benchmark i o = bench "Fold" $ whnfIO $ T.readFile i >>= TL.hPutStr o . fold 80 -- | We represent a paragraph by a word list -- type Paragraph = [T.Text] -- | Fold a text -- fold :: Int -> T.Text -> TL.Text fold maxWidth = TLB.toLazyText . mconcat . intersperse "\n\n" . map (foldParagraph maxWidth) . paragraphs -- | Fold a paragraph -- foldParagraph :: Int -> Paragraph -> TLB.Builder foldParagraph _ [] = mempty foldParagraph max' (w : ws) = fst $ foldl' go (TLB.fromText w, T.length w) ws where go (builder, width) word | width + len + 1 <= max' = (builder `mappend` " " `mappend` word', width + len + 1) | otherwise = (builder `mappend` "\n" `mappend` word', len) where word' = TLB.fromText word len = T.length word -- | Divide a text into paragraphs -- paragraphs :: T.Text -> [Paragraph] paragraphs = splitParagraphs . map T.words . T.lines where splitParagraphs ls = case break null ls of ([], []) -> [] (p, []) -> [concat p] (p, lr) -> concat p : splitParagraphs (dropWhile null lr)
null
https://raw.githubusercontent.com/HugoPeters1024/hs-sleuth/385655e62031959a14a3bac5e9ccd1c42c045f0c/test-project/text-1.2.4.0/benchmarks/haskell/Benchmarks/Programs/Fold.hs
haskell
| Benchmark which formats paragraph, like the @sort@ unix utility. Tested in this benchmark: * Reading the file * Splitting into paragraphs * Reformatting the paragraphs to a certain line width * Writing back to a handle # LANGUAGE OverloadedStrings # | We represent a paragraph by a word list | Fold a text | Fold a paragraph | Divide a text into paragraphs
* the results using the text builder module Benchmarks.Programs.Fold ( benchmark ) where import Data.List (foldl') import Data.List (intersperse) import Data.Monoid (mempty, mappend, mconcat) import System.IO (Handle) import Criterion (Benchmark, bench, whnfIO) import qualified Data.Text as T import qualified Data.Text.IO as T import qualified Data.Text.Lazy.Builder as TLB import qualified Data.Text.Lazy as TL import qualified Data.Text.Lazy.IO as TL benchmark :: FilePath -> Handle -> Benchmark benchmark i o = bench "Fold" $ whnfIO $ T.readFile i >>= TL.hPutStr o . fold 80 type Paragraph = [T.Text] fold :: Int -> T.Text -> TL.Text fold maxWidth = TLB.toLazyText . mconcat . intersperse "\n\n" . map (foldParagraph maxWidth) . paragraphs foldParagraph :: Int -> Paragraph -> TLB.Builder foldParagraph _ [] = mempty foldParagraph max' (w : ws) = fst $ foldl' go (TLB.fromText w, T.length w) ws where go (builder, width) word | width + len + 1 <= max' = (builder `mappend` " " `mappend` word', width + len + 1) | otherwise = (builder `mappend` "\n" `mappend` word', len) where word' = TLB.fromText word len = T.length word paragraphs :: T.Text -> [Paragraph] paragraphs = splitParagraphs . map T.words . T.lines where splitParagraphs ls = case break null ls of ([], []) -> [] (p, []) -> [concat p] (p, lr) -> concat p : splitParagraphs (dropWhile null lr)
c6c0f0c3cb3dfb895ef956ce213825f42332f96b177f90700ac5b9036c96c419
lisp-mirror/clpm
cli-source.lisp
;;;; Definitions for using CLI options as a config source ;;;; This software is part of CLPM . See README.org for more information . See ;;;; LICENSE for license information. (uiop:define-package #:clpm/config/cli-source (:use #:cl #:clpm/config/defs #:clpm/config/source-defs) (:export #:config-cli-source)) (in-package #:clpm/config/cli-source) (defclass config-cli-source (config-source) ((bundle-clpmfile) (context) (local) (log-level)) (:documentation "A configuration source backed by CLI arguments.")) (defmethod initialize-instance :after ((config-source config-cli-source) &key arg-ht) (multiple-value-bind (value exists-p) (gethash :cli-config-bundle-clpmfile arg-ht) (when (and exists-p (not (eql value :missing))) (setf (slot-value config-source 'bundle-clpmfile) value))) (multiple-value-bind (value exists-p) (gethash :cli-config-context arg-ht) (when (and exists-p (not (eql value :missing))) (setf (slot-value config-source 'context) value))) (multiple-value-bind (value exists-p) (gethash :cli-config-local arg-ht) (when (and exists-p (not (eql value :missing))) (setf (slot-value config-source 'local) value))) (multiple-value-bind (value exists-p) (gethash :cli-config-log-level arg-ht) (when (and exists-p (plusp value)) (case value (1 (setf (slot-value config-source 'log-level) :info)) (2 (setf (slot-value config-source 'log-level) :debug)) (t (setf (slot-value config-source 'log-level) :trace)))))) (defmethod config-source-value ((config-source config-cli-source) path) (cond ((and (equal path '(:bundle :clpmfile)) (slot-boundp config-source 'bundle-clpmfile)) (values (slot-value config-source 'bundle-clpmfile) t)) ((and (equal path '(:context)) (slot-boundp config-source 'context)) (values (slot-value config-source 'context) t)) ((and (equal path '(:local)) (slot-boundp config-source 'local)) (values (slot-value config-source 'local) t)) ((and (equal path '(:log :level)) (slot-boundp config-source 'log-level)) (values (slot-value config-source 'log-level) t)))) (defmethod config-source-implicit-keys ((config-source config-cli-source) path) nil)
null
https://raw.githubusercontent.com/lisp-mirror/clpm/ad9a704fcdd0df5ce30ead106706ab6cc5fb3e5b/clpm/config/cli-source.lisp
lisp
Definitions for using CLI options as a config source LICENSE for license information.
This software is part of CLPM . See README.org for more information . See (uiop:define-package #:clpm/config/cli-source (:use #:cl #:clpm/config/defs #:clpm/config/source-defs) (:export #:config-cli-source)) (in-package #:clpm/config/cli-source) (defclass config-cli-source (config-source) ((bundle-clpmfile) (context) (local) (log-level)) (:documentation "A configuration source backed by CLI arguments.")) (defmethod initialize-instance :after ((config-source config-cli-source) &key arg-ht) (multiple-value-bind (value exists-p) (gethash :cli-config-bundle-clpmfile arg-ht) (when (and exists-p (not (eql value :missing))) (setf (slot-value config-source 'bundle-clpmfile) value))) (multiple-value-bind (value exists-p) (gethash :cli-config-context arg-ht) (when (and exists-p (not (eql value :missing))) (setf (slot-value config-source 'context) value))) (multiple-value-bind (value exists-p) (gethash :cli-config-local arg-ht) (when (and exists-p (not (eql value :missing))) (setf (slot-value config-source 'local) value))) (multiple-value-bind (value exists-p) (gethash :cli-config-log-level arg-ht) (when (and exists-p (plusp value)) (case value (1 (setf (slot-value config-source 'log-level) :info)) (2 (setf (slot-value config-source 'log-level) :debug)) (t (setf (slot-value config-source 'log-level) :trace)))))) (defmethod config-source-value ((config-source config-cli-source) path) (cond ((and (equal path '(:bundle :clpmfile)) (slot-boundp config-source 'bundle-clpmfile)) (values (slot-value config-source 'bundle-clpmfile) t)) ((and (equal path '(:context)) (slot-boundp config-source 'context)) (values (slot-value config-source 'context) t)) ((and (equal path '(:local)) (slot-boundp config-source 'local)) (values (slot-value config-source 'local) t)) ((and (equal path '(:log :level)) (slot-boundp config-source 'log-level)) (values (slot-value config-source 'log-level) t)))) (defmethod config-source-implicit-keys ((config-source config-cli-source) path) nil)
2e6fbb32a61961835d8a5c093f737eb2cef8341ce6e3ebcd6d955a139dcfd143
links-lang/links
transform.mli
module type INTERFACE = sig type state type 'a result val name : string val program : state -> Sugartypes.program -> Sugartypes.program result val sentence : state -> Sugartypes.sentence -> Sugartypes.sentence result end module type UNTYPED = sig type state = Context.t type 'a result = Result of { program: 'a; state: state } val return : state -> 'a -> 'a result val context : state -> Context.t module type S = sig module Untyped: sig include INTERFACE with type state := state and type 'a result := 'a result end end module Make: sig module Transformer(T : sig val name : string val obj : SugarTraversals.map end): sig include INTERFACE with type state := state and type 'a result := 'a result end end end module Untyped : UNTYPED module type TYPEABLE = sig type state = { datatype: Types.datatype; context: Context.t } type 'a result = Result of { program: 'a; state: state } val return : state -> 'a -> 'a result val with_type : Types.datatype option -> state -> state val context : state -> Context.t module type S = sig module Typeable: sig include INTERFACE with type state := state and type 'a result := 'a result end end (* This virtual class helps break the dependency cycle: Value -> DesugarDatatypes -> Transform -> TransformSugar -> DesugarDatatypes -> Transform *) class virtual sugar_transformer: object ('self) method virtual program : Sugartypes.program -> ('self * Sugartypes.program * Types.datatype option) method virtual sentence : Sugartypes.sentence -> ('self * Sugartypes.sentence * Types.datatype option) end module Make(T : sig val name : string val obj : Types.typing_environment -> sugar_transformer end): sig include INTERFACE with type state := state and type 'a result := 'a result end end module Typeable : TYPEABLE module Identity: sig include Untyped.S include Typeable.S end
null
https://raw.githubusercontent.com/links-lang/links/2923893c80677b67cacc6747a25b5bcd65c4c2b6/core/transform.mli
ocaml
This virtual class helps break the dependency cycle: Value -> DesugarDatatypes -> Transform -> TransformSugar -> DesugarDatatypes -> Transform
module type INTERFACE = sig type state type 'a result val name : string val program : state -> Sugartypes.program -> Sugartypes.program result val sentence : state -> Sugartypes.sentence -> Sugartypes.sentence result end module type UNTYPED = sig type state = Context.t type 'a result = Result of { program: 'a; state: state } val return : state -> 'a -> 'a result val context : state -> Context.t module type S = sig module Untyped: sig include INTERFACE with type state := state and type 'a result := 'a result end end module Make: sig module Transformer(T : sig val name : string val obj : SugarTraversals.map end): sig include INTERFACE with type state := state and type 'a result := 'a result end end end module Untyped : UNTYPED module type TYPEABLE = sig type state = { datatype: Types.datatype; context: Context.t } type 'a result = Result of { program: 'a; state: state } val return : state -> 'a -> 'a result val with_type : Types.datatype option -> state -> state val context : state -> Context.t module type S = sig module Typeable: sig include INTERFACE with type state := state and type 'a result := 'a result end end class virtual sugar_transformer: object ('self) method virtual program : Sugartypes.program -> ('self * Sugartypes.program * Types.datatype option) method virtual sentence : Sugartypes.sentence -> ('self * Sugartypes.sentence * Types.datatype option) end module Make(T : sig val name : string val obj : Types.typing_environment -> sugar_transformer end): sig include INTERFACE with type state := state and type 'a result := 'a result end end module Typeable : TYPEABLE module Identity: sig include Untyped.S include Typeable.S end
2bbe7a39089c3f9749618153d5b02d7262576d268c08c3f0797ca548d22292da
racket/htdp
jpr-bug.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-advanced-reader.ss" "lang")((modname jpr-bug) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #t #t none #f ()))) ;; This program demonstrated that the idea of using default handlers (K) for ;; absent mouse and key handlers was a horrible idea. The balls on his cannvas ;; just started jumping around when the mouse moved in. (require 2htdp/universe) (require 2htdp/image) (define (animation2) (local [(define SIZE 300) (define SCENE (rectangle SIZE SIZE 'outline "black")) (define dM 1) (define INIT 0) (define (suivant m) (+ m dM)) (define (dessiner m) (place-image (circle m 'solid "red") (random SIZE) (random SIZE) SCENE))] (big-bang INIT (on-tick suivant 1) (on-draw dessiner SIZE SIZE)))) (animation2)
null
https://raw.githubusercontent.com/racket/htdp/aa78794fa1788358d6abd11dad54b3c9f4f5a80b/htdp-test/2htdp/tests/jpr-bug.rkt
racket
about the language level of this file in a form that our tools can easily process. This program demonstrated that the idea of using default handlers (K) for absent mouse and key handlers was a horrible idea. The balls on his cannvas just started jumping around when the mouse moved in.
The first three lines of this file were inserted by . They record metadata #reader(lib "htdp-advanced-reader.ss" "lang")((modname jpr-bug) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #t #t none #f ()))) (require 2htdp/universe) (require 2htdp/image) (define (animation2) (local [(define SIZE 300) (define SCENE (rectangle SIZE SIZE 'outline "black")) (define dM 1) (define INIT 0) (define (suivant m) (+ m dM)) (define (dessiner m) (place-image (circle m 'solid "red") (random SIZE) (random SIZE) SCENE))] (big-bang INIT (on-tick suivant 1) (on-draw dessiner SIZE SIZE)))) (animation2)
8cc0b17e9a8753b76d39da7118de43cced344de349ce4f5c7bd375ac795f97ad
raymorgan/merl
support.erl
-module (merl.router.support). -author ("Ray Morgan"). -export ([split_path/1, atomize/1, bindings_from/1, is_var/1]). -import (string). -import (lists). split_path(Path) -> [P|_] = string:tokens(Path, [$?, $.]), atomize(string:tokens(P, [$/])). atomize([]) -> []; atomize([H|T]) -> [list_to_atom(H)|atomize(T)]. bindings_from(Path) -> P = split_path(Path), find_bindings(P, []). find_bindings([], Bindings) -> Bindings; find_bindings([H|T], Bindings) -> case atom_to_list(H) of [$:|V] -> find_bindings(T, lists:append(Bindings, [list_to_atom(V)])); _ -> find_bindings(T, Bindings) end. is_var(Route) -> R = atom_to_list(Route), [H|_] = R, H =:= $:.
null
https://raw.githubusercontent.com/raymorgan/merl/f71df567bc61b7b088d534df99ce8955dbfa5407/src/router/support.erl
erlang
-module (merl.router.support). -author ("Ray Morgan"). -export ([split_path/1, atomize/1, bindings_from/1, is_var/1]). -import (string). -import (lists). split_path(Path) -> [P|_] = string:tokens(Path, [$?, $.]), atomize(string:tokens(P, [$/])). atomize([]) -> []; atomize([H|T]) -> [list_to_atom(H)|atomize(T)]. bindings_from(Path) -> P = split_path(Path), find_bindings(P, []). find_bindings([], Bindings) -> Bindings; find_bindings([H|T], Bindings) -> case atom_to_list(H) of [$:|V] -> find_bindings(T, lists:append(Bindings, [list_to_atom(V)])); _ -> find_bindings(T, Bindings) end. is_var(Route) -> R = atom_to_list(Route), [H|_] = R, H =:= $:.
46b41a76037db6d8167e196274bd04b667c86b04f2752f1da8c8607540e1a1a7
fumieval/webauthn
TPM.hs
{-# LANGUAGE OverloadedStrings #-} | 8.3 . TPM Attestation Statement Format -- -- Work in progress. Do not use. module WebAuthn.Attestation.Statement.TPM where import Data.ByteString (ByteString) import Crypto.Hash (Digest, SHA256) import qualified Data.X509 as X509 import qualified Codec.CBOR.Term as CBOR import qualified Codec.CBOR.Decoding as CBOR import qualified Data.Map as Map import WebAuthn.Types (VerificationFailure(..), AuthenticatorData) import WebAuthn.Signature (verifyX509Sig) data Stmt = Stmt { alg :: Int , x5c :: X509.SignedExact X509.Certificate , sig :: ByteString , certInfo :: ByteString , pubArea :: ByteString } deriving stock (Show) decode :: CBOR.Term -> CBOR.Decoder s Stmt decode (CBOR.TMap xs) = do let m = Map.fromList xs CBOR.TInt alg <- Map.lookup (CBOR.TString "alg") m ??? "alg" CBOR.TBytes sig <- Map.lookup (CBOR.TString "sig") m ??? "sig" CBOR.TList (CBOR.TBytes certBS : _) <- Map.lookup (CBOR.TString "x5c") m ??? "x5c" x5c <- either fail pure $ X509.decodeSignedCertificate certBS CBOR.TBytes certInfo <- Map.lookup (CBOR.TString "certInfo") m ??? "certInfo" CBOR.TBytes pubArea <- Map.lookup (CBOR.TString "pubArea") m ??? "pubArea" pure $ Stmt {..} where Nothing ??? e = fail e Just a ??? _ = pure a decode _ = fail "TPM.decode: expected a Map" verify :: Stmt -> AuthenticatorData -> ByteString -> Digest SHA256 -> Either VerificationFailure () verify Stmt{..} _ad _adRaw _clientDataHash = do TODO Verify that the public key specified by the parameters and unique fields of pubArea is identical to the credentialPublicKey in the attestedCredentialData in authenticatorData . let pub = X509.certPubKey $ X509.getCertificate x5c let attToBeSigned = adRaw < > clientDataHash -- #algorithms case alg of -65535 -> verifyX509Sig (X509.SignatureALG X509.HashSHA1 X509.PubKeyALG_RSA) pub certInfo sig "TPM" _ -> Left $ UnsupportedAlgorithm alg
null
https://raw.githubusercontent.com/fumieval/webauthn/46343b0afc0b57bd78546765139265f5b3142b5d/webauthn/src/WebAuthn/Attestation/Statement/TPM.hs
haskell
# LANGUAGE OverloadedStrings # Work in progress. Do not use. #algorithms
| 8.3 . TPM Attestation Statement Format module WebAuthn.Attestation.Statement.TPM where import Data.ByteString (ByteString) import Crypto.Hash (Digest, SHA256) import qualified Data.X509 as X509 import qualified Codec.CBOR.Term as CBOR import qualified Codec.CBOR.Decoding as CBOR import qualified Data.Map as Map import WebAuthn.Types (VerificationFailure(..), AuthenticatorData) import WebAuthn.Signature (verifyX509Sig) data Stmt = Stmt { alg :: Int , x5c :: X509.SignedExact X509.Certificate , sig :: ByteString , certInfo :: ByteString , pubArea :: ByteString } deriving stock (Show) decode :: CBOR.Term -> CBOR.Decoder s Stmt decode (CBOR.TMap xs) = do let m = Map.fromList xs CBOR.TInt alg <- Map.lookup (CBOR.TString "alg") m ??? "alg" CBOR.TBytes sig <- Map.lookup (CBOR.TString "sig") m ??? "sig" CBOR.TList (CBOR.TBytes certBS : _) <- Map.lookup (CBOR.TString "x5c") m ??? "x5c" x5c <- either fail pure $ X509.decodeSignedCertificate certBS CBOR.TBytes certInfo <- Map.lookup (CBOR.TString "certInfo") m ??? "certInfo" CBOR.TBytes pubArea <- Map.lookup (CBOR.TString "pubArea") m ??? "pubArea" pure $ Stmt {..} where Nothing ??? e = fail e Just a ??? _ = pure a decode _ = fail "TPM.decode: expected a Map" verify :: Stmt -> AuthenticatorData -> ByteString -> Digest SHA256 -> Either VerificationFailure () verify Stmt{..} _ad _adRaw _clientDataHash = do TODO Verify that the public key specified by the parameters and unique fields of pubArea is identical to the credentialPublicKey in the attestedCredentialData in authenticatorData . let pub = X509.certPubKey $ X509.getCertificate x5c let attToBeSigned = adRaw < > clientDataHash case alg of -65535 -> verifyX509Sig (X509.SignatureALG X509.HashSHA1 X509.PubKeyALG_RSA) pub certInfo sig "TPM" _ -> Left $ UnsupportedAlgorithm alg
2d2bc1e3503d9fed7375c32f2fa4c5c68baa8355ed37888cfed3561a785ce898
ghilesZ/apronext
abox.ml
include Domain.Make (struct type t = Box.t let man = Box.manager_alloc () end) (** given a box, builds an iterator over triplets : variables, type, interval e.g: [let it = iterator b in it (); it (); it()]. @raise Exit when all dimension have been iterated on. *) let iterator b = let {box1_env; interval_array} = to_box1 b in let i = ref 0 in let len = Array.length interval_array in fun () -> if !i >= len then raise Exit else let v = E.var_of_dim box1_env !i in let typ = E.typ_of_var box1_env v in let itv = interval_array.(!i) in incr i ; (v, typ, itv) (** Difference operator for boxes. WARNING, real variable have a floatting point semantics, e.g [\[0.;1.\] - \[0.5; 1.\]= \[0.; 0.499999999\]] *) let diff_float (b1 : t) (b2 : t) : t list = let rec product f b = function | [] -> [] | hd :: tl -> List.rev_map (f hd) b |> List.rev_append (product f b tl) in if meet b1 b2 |> is_bottom then [b1] else let next = iterator b2 in let rec aux a (acc : t list) = match next () with | v, t, i_b -> let i_a = bound_variable a v in let d = if t = INT then I.diff_int i_a i_b else I.diff_float i_a i_b in let assign b i = assign_interval b v i in aux (assign_interval a v i_b) (product assign d acc) | exception Exit -> acc in aux b1 [b1] (** compact pretty printing *) let pp_print fmt b = let it = iterator b in let rec loop acc = match it () with | v, t, i -> loop ((v, t, i) :: acc) | exception Exit -> List.rev acc in let vars = loop [] in let print_itv_int fmt i = let zinf = Scalarext.to_mpqf i.I.inf |> Mpqf.to_mpzf2 |> fst and zsup = Scalarext.to_mpqf i.I.sup |> Mpqf.to_mpzf2 |> fst in Format.fprintf fmt "[%a; %a]" Mpz.print zinf Mpz.print zsup in let itv_print = function E.INT -> print_itv_int | E.REAL -> I.print in Format.fprintf fmt "[|%a|]" (Format.pp_print_list ~pp_sep:(fun fmt () -> Format.fprintf fmt "; ") (fun fmt (v, t, i) -> Format.fprintf fmt "%a ∊ %a" Apron.Var.print v (itv_print t) i)) vars
null
https://raw.githubusercontent.com/ghilesZ/apronext/4472f711ea4e54945cc91d469b852105a3f44343/src/abox.ml
ocaml
* given a box, builds an iterator over triplets : variables, type, interval e.g: [let it = iterator b in it (); it (); it()]. @raise Exit when all dimension have been iterated on. * Difference operator for boxes. WARNING, real variable have a floatting point semantics, e.g [\[0.;1.\] - \[0.5; 1.\]= \[0.; 0.499999999\]] * compact pretty printing
include Domain.Make (struct type t = Box.t let man = Box.manager_alloc () end) let iterator b = let {box1_env; interval_array} = to_box1 b in let i = ref 0 in let len = Array.length interval_array in fun () -> if !i >= len then raise Exit else let v = E.var_of_dim box1_env !i in let typ = E.typ_of_var box1_env v in let itv = interval_array.(!i) in incr i ; (v, typ, itv) let diff_float (b1 : t) (b2 : t) : t list = let rec product f b = function | [] -> [] | hd :: tl -> List.rev_map (f hd) b |> List.rev_append (product f b tl) in if meet b1 b2 |> is_bottom then [b1] else let next = iterator b2 in let rec aux a (acc : t list) = match next () with | v, t, i_b -> let i_a = bound_variable a v in let d = if t = INT then I.diff_int i_a i_b else I.diff_float i_a i_b in let assign b i = assign_interval b v i in aux (assign_interval a v i_b) (product assign d acc) | exception Exit -> acc in aux b1 [b1] let pp_print fmt b = let it = iterator b in let rec loop acc = match it () with | v, t, i -> loop ((v, t, i) :: acc) | exception Exit -> List.rev acc in let vars = loop [] in let print_itv_int fmt i = let zinf = Scalarext.to_mpqf i.I.inf |> Mpqf.to_mpzf2 |> fst and zsup = Scalarext.to_mpqf i.I.sup |> Mpqf.to_mpzf2 |> fst in Format.fprintf fmt "[%a; %a]" Mpz.print zinf Mpz.print zsup in let itv_print = function E.INT -> print_itv_int | E.REAL -> I.print in Format.fprintf fmt "[|%a|]" (Format.pp_print_list ~pp_sep:(fun fmt () -> Format.fprintf fmt "; ") (fun fmt (v, t, i) -> Format.fprintf fmt "%a ∊ %a" Apron.Var.print v (itv_print t) i)) vars
e9d98c632041d8c25d7ba0f78a40446c09bb34cbcb6fefff13ab7142737310d0
davexunit/guile-2d
audio.scm
;;; guile-2d Copyright ( C ) 2013 > ;;; ;;; Guile-2d 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. ;;; ;;; Guile-2d 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 this program. If not, see ;;; </>. ;;; Commentary: ;; Wrappers over SDL mixer . ;; ;;; Code: (define-module (2d audio) #:use-module (srfi srfi-9) #:use-module (srfi srfi-2) #:use-module ((sdl mixer) #:prefix SDL:)) Wrapper over SDL audio objects . (define-record-type <sample> (make-sample audio) sample? (audio sample-audio)) (define (load-sample filename) "Load audio sample from FILENAME. Return #f on failure." (let ((audio (SDL:load-wave filename))) (if audio (make-sample audio) #f))) (define (sample-play sample) "Play audio SAMPLE." (SDL:play-channel (sample-audio sample))) (define (sample-volume) "Return volume that samples are played at." (SDL:volume)) (define (set-sample-volume volume) "Set the volume that samples are played at to VOLUME." (SDL:volume volume)) (export make-sample load-sample sample? sample-audio sample-play sample-volume set-sample-volume) Wrapper over SDL music objects . (define-record-type <music> (make-music audio) music? (audio music-audio)) (define (load-music filename) "Load music from FILENAME. Return #f on failure." (let ((audio (SDL:load-music filename))) (if audio (make-music audio) #f))) (define (music-play music) "Play MUSIC." (SDL:play-music (music-audio music))) (define (music-volume) "Return the volume that music is played at." (SDL:music-volume)) (define (set-music-volume volume) "Set the volume that music is played at." (SDL:volume volume)) (export make-music load-music music? music-audio music-play music-volume set-music-volume) (re-export (SDL:pause-music . music-pause) (SDL:resume-music . music-resume) (SDL:rewind-music . music-rewind) (SDL:halt-music . music-stop) (SDL:paused-music? . music-paused?) (SDL:playing-music? . music-playing?))
null
https://raw.githubusercontent.com/davexunit/guile-2d/83d9dfab5b04a337565cb2798847b15e4fbd7786/2d/audio.scm
scheme
guile-2d Guile-2d is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as License, or (at your option) any later version. Guile-2d 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. License along with this program. If not, see </>. Commentary: Code:
Copyright ( C ) 2013 > published by the Free Software Foundation , either version 3 of the You should have received a copy of the GNU Lesser General Public Wrappers over SDL mixer . (define-module (2d audio) #:use-module (srfi srfi-9) #:use-module (srfi srfi-2) #:use-module ((sdl mixer) #:prefix SDL:)) Wrapper over SDL audio objects . (define-record-type <sample> (make-sample audio) sample? (audio sample-audio)) (define (load-sample filename) "Load audio sample from FILENAME. Return #f on failure." (let ((audio (SDL:load-wave filename))) (if audio (make-sample audio) #f))) (define (sample-play sample) "Play audio SAMPLE." (SDL:play-channel (sample-audio sample))) (define (sample-volume) "Return volume that samples are played at." (SDL:volume)) (define (set-sample-volume volume) "Set the volume that samples are played at to VOLUME." (SDL:volume volume)) (export make-sample load-sample sample? sample-audio sample-play sample-volume set-sample-volume) Wrapper over SDL music objects . (define-record-type <music> (make-music audio) music? (audio music-audio)) (define (load-music filename) "Load music from FILENAME. Return #f on failure." (let ((audio (SDL:load-music filename))) (if audio (make-music audio) #f))) (define (music-play music) "Play MUSIC." (SDL:play-music (music-audio music))) (define (music-volume) "Return the volume that music is played at." (SDL:music-volume)) (define (set-music-volume volume) "Set the volume that music is played at." (SDL:volume volume)) (export make-music load-music music? music-audio music-play music-volume set-music-volume) (re-export (SDL:pause-music . music-pause) (SDL:resume-music . music-resume) (SDL:rewind-music . music-rewind) (SDL:halt-music . music-stop) (SDL:paused-music? . music-paused?) (SDL:playing-music? . music-playing?))
69958a9ac3a294305401d54e41c29958d6f5b12756d5e336468a356977464f01
youscape/ebt
ebt_transform.erl
%%%------------------------------------------------------------------- @author zyuyou ( C ) 2015 , @doc 实现行为树节点的继承 %%% %%% @end %%%------------------------------------------------------------------- -module(ebt_transform). -include("ebt.hrl"). %% API -export([parse_transform/2]). -define(EBT_NODE_FUNCTIONS, [init, precondition, evaluate, do_evaluate, tick, clear]). -define(EBT_ACTION_FUNCTIONS, [do_enter, do_execute, do_exit | ?EBT_NODE_FUNCTIONS]). -define(EBT_EXTEND_TAG, ebt_extend). -define(EBT_UNDEF, undefined). %%==================================================================== %% transform %%==================================================================== -ifndef(EBT_TEST). -define(EBT_TEST, false). parse_transform(Forms0, _Options) -> transform(Forms0). -else. parse_transform([{attribute, 1, file, _FilePath}, {attribute, _L, module, ModuleName} | _Tail] = Forms0, _Options) -> Forms2 = transform(Forms0), case ?EBT_TEST of false -> Forms2; true -> file:write_file(io_lib:format("transforms/~w.txt", [ModuleName]), io_lib:format("~p", [Forms2])); Dir -> file:write_file(io_lib:format("~s/~w.txt", [Dir, ModuleName]), io_lib:format("~p", [Forms2])) end. -endif. transform(Forms) -> case get_inherit_funs(Forms) of no_need -> Forms; {BaseModule, InheritFuns} -> put(?EBT_EXTEND_TAG, BaseModule), {ExportAttrExpr, FunExprs} = gen_funs_expr(InheritFuns, {[], []}), BehaviourAttrExpr = {attribute, 0, behaviour, BaseModule}, Forms1 = add_attributes(Forms, [BehaviourAttrExpr, ExportAttrExpr]), erase(?EBT_EXTEND_TAG), add_new_funcs(Forms1, FunExprs) end. %% get base-module and inherit-funs get_inherit_funs(Forms) -> get_inherit_funs(Forms, {?EBT_UNDEF, ?EBT_NODE_FUNCTIONS}). get_inherit_funs(_Forms, {_BasedClass, []}) -> no_need; get_inherit_funs([], {?EBT_UNDEF, _Funs}) -> no_need; get_inherit_funs([], {BasedClass, InheritFuns}) -> {BasedClass, InheritFuns}; get_inherit_funs([{attribute,_L, ?EBT_EXTEND_TAG, BasedClassName} | Tail], {?EBT_UNDEF, InheritFuns}) -> get_inherit_funs(Tail, {BasedClassName, InheritFuns}); get_inherit_funs([{function, _L, Name, 1, _ClauseBody} | Tail], {BasedClass, InheritFuns}) -> get_inherit_funs(Tail, {BasedClass, InheritFuns -- [Name]}); get_inherit_funs([_H | Tail], {BasedClass, InheritFuns}) -> get_inherit_funs(Tail, {BasedClass, InheritFuns}). %% gen inherit-funs exprs gen_funs_expr([], {ExportAttrs, FunExprs}) -> {{attribute,0,export, ExportAttrs}, FunExprs}; gen_funs_expr([FunName | TailFuns], {ExportAttr, FunExprs}) -> FunExpr = {function,0,FunName, 1, [{clause,0, [{match,0, {record,0,?EBT_NODE_NAME,[]}, {var, 0,'Node'}}], [], [{call,0, {remote,0,{atom,0, get(?EBT_EXTEND_TAG)},{atom,0, FunName}}, [{var,0,'Node'}]}]}]}, gen_funs_expr(TailFuns, {[{FunName, 1} | ExportAttr], [FunExpr | FunExprs]}). add_attributes([{attribute,_,module,_}=F|Fs], Attrs) -> [F|Attrs++Fs]; add_attributes([F|Fs], Attrs) -> [F|add_attributes(Fs, Attrs)]. add_new_funcs([{eof,_}|_]=Fs, NewFs) -> NewFs ++ Fs; add_new_funcs([F|Fs], Es) -> [F|add_new_funcs(Fs, Es)]; add_new_funcs([], NewFs) -> NewFs.
null
https://raw.githubusercontent.com/youscape/ebt/546121bdfa24cb8cbd64ff4f842fd42ec7d50189/src/ebt_transform.erl
erlang
------------------------------------------------------------------- @end ------------------------------------------------------------------- API ==================================================================== transform ==================================================================== get base-module and inherit-funs gen inherit-funs exprs
@author zyuyou ( C ) 2015 , @doc 实现行为树节点的继承 -module(ebt_transform). -include("ebt.hrl"). -export([parse_transform/2]). -define(EBT_NODE_FUNCTIONS, [init, precondition, evaluate, do_evaluate, tick, clear]). -define(EBT_ACTION_FUNCTIONS, [do_enter, do_execute, do_exit | ?EBT_NODE_FUNCTIONS]). -define(EBT_EXTEND_TAG, ebt_extend). -define(EBT_UNDEF, undefined). -ifndef(EBT_TEST). -define(EBT_TEST, false). parse_transform(Forms0, _Options) -> transform(Forms0). -else. parse_transform([{attribute, 1, file, _FilePath}, {attribute, _L, module, ModuleName} | _Tail] = Forms0, _Options) -> Forms2 = transform(Forms0), case ?EBT_TEST of false -> Forms2; true -> file:write_file(io_lib:format("transforms/~w.txt", [ModuleName]), io_lib:format("~p", [Forms2])); Dir -> file:write_file(io_lib:format("~s/~w.txt", [Dir, ModuleName]), io_lib:format("~p", [Forms2])) end. -endif. transform(Forms) -> case get_inherit_funs(Forms) of no_need -> Forms; {BaseModule, InheritFuns} -> put(?EBT_EXTEND_TAG, BaseModule), {ExportAttrExpr, FunExprs} = gen_funs_expr(InheritFuns, {[], []}), BehaviourAttrExpr = {attribute, 0, behaviour, BaseModule}, Forms1 = add_attributes(Forms, [BehaviourAttrExpr, ExportAttrExpr]), erase(?EBT_EXTEND_TAG), add_new_funcs(Forms1, FunExprs) end. get_inherit_funs(Forms) -> get_inherit_funs(Forms, {?EBT_UNDEF, ?EBT_NODE_FUNCTIONS}). get_inherit_funs(_Forms, {_BasedClass, []}) -> no_need; get_inherit_funs([], {?EBT_UNDEF, _Funs}) -> no_need; get_inherit_funs([], {BasedClass, InheritFuns}) -> {BasedClass, InheritFuns}; get_inherit_funs([{attribute,_L, ?EBT_EXTEND_TAG, BasedClassName} | Tail], {?EBT_UNDEF, InheritFuns}) -> get_inherit_funs(Tail, {BasedClassName, InheritFuns}); get_inherit_funs([{function, _L, Name, 1, _ClauseBody} | Tail], {BasedClass, InheritFuns}) -> get_inherit_funs(Tail, {BasedClass, InheritFuns -- [Name]}); get_inherit_funs([_H | Tail], {BasedClass, InheritFuns}) -> get_inherit_funs(Tail, {BasedClass, InheritFuns}). gen_funs_expr([], {ExportAttrs, FunExprs}) -> {{attribute,0,export, ExportAttrs}, FunExprs}; gen_funs_expr([FunName | TailFuns], {ExportAttr, FunExprs}) -> FunExpr = {function,0,FunName, 1, [{clause,0, [{match,0, {record,0,?EBT_NODE_NAME,[]}, {var, 0,'Node'}}], [], [{call,0, {remote,0,{atom,0, get(?EBT_EXTEND_TAG)},{atom,0, FunName}}, [{var,0,'Node'}]}]}]}, gen_funs_expr(TailFuns, {[{FunName, 1} | ExportAttr], [FunExpr | FunExprs]}). add_attributes([{attribute,_,module,_}=F|Fs], Attrs) -> [F|Attrs++Fs]; add_attributes([F|Fs], Attrs) -> [F|add_attributes(Fs, Attrs)]. add_new_funcs([{eof,_}|_]=Fs, NewFs) -> NewFs ++ Fs; add_new_funcs([F|Fs], Es) -> [F|add_new_funcs(Fs, Es)]; add_new_funcs([], NewFs) -> NewFs.
8f38ac5178535243afed83aa70ec18e0a570e5f809b8c40e643b7dc6ca1e9f4b
FlowerWrong/mblog
clock.erl
%% --- Excerpted from " Programming Erlang , Second Edition " , published by The Pragmatic Bookshelf . %% Copyrights apply to this code. It may not be used to create training material, %% courses, books, articles, and the like. Contact us if you are in doubt. %% We make no guarantees that this code is fit for any purpose. %% Visit for more book information. %%--- -module(clock). -export([start/2, stop/0]). start(Time, Fun) -> register(clock, spawn(fun() -> tick(Time, Fun) end)). stop() -> clock ! stop. tick(Time, Fun) -> receive stop -> void after Time -> Fun(), tick(Time, Fun) end.
null
https://raw.githubusercontent.com/FlowerWrong/mblog/3233ede938d2019a7b57391405197ac19c805b27/categories/erlang/demo/jaerlang2_code/clock.erl
erlang
--- Copyrights apply to this code. It may not be used to create training material, courses, books, articles, and the like. Contact us if you are in doubt. We make no guarantees that this code is fit for any purpose. Visit for more book information. ---
Excerpted from " Programming Erlang , Second Edition " , published by The Pragmatic Bookshelf . -module(clock). -export([start/2, stop/0]). start(Time, Fun) -> register(clock, spawn(fun() -> tick(Time, Fun) end)). stop() -> clock ! stop. tick(Time, Fun) -> receive stop -> void after Time -> Fun(), tick(Time, Fun) end.
c3c6ee4a4be629332dcfcdc8ce7664846935f7431197d0ae73bcec269457dfb6
orbitz/oort
irc_lookup.erl
-module(irc_lookup). -author(""). -export([start/0, translate_command/1, loop/2, shutdown/0, test/0]). start() -> case whereis(irc_lookup_server) of undefined -> Symbols = dict:from_list([ {"RPL_UNAWAY", "305"}, {"ERR_TOOMANYTARGETS", "407"}, {"ERR_KEYSET", "467"}, {"RPL_INFO", "371"}, {"RPL_TRACECLASS", "209"}, {"RPL_AWAY", "301"}, {"ERR_RESTRICTED", "484"}, {"RPL_NOWAWAY", "306"}, {"RPL_ADMINME", "256"}, {"RPL_TRACESERVER", "206"}, {"ERR_NOPERMFORHOST", "463"}, {"ERR_NOTREGISTERED", "451"}, {"RPL_BANLIST", "367"}, {"RPL_ENDOFINFO", "374"}, {"RPL_TRACENEWTYPE", "208"}, {"RPL_LUSEROP", "252"}, {"RPL_WHOWASUSER", "314"}, {"RPL_LUSERCHANNELS", "254"}, {"RPL_LUSERUNKNOWN", "253"}, {"ERR_NOLOGIN", "444"}, {"ERR_NOTEXTTOSEND", "412"}, {"RPL_MYINFO", "004"}, {"ERR_INVITEONLYCHAN", "473"}, {"ERR_UNKNOWNMODE", "472"}, {"RPL_WHOISCHANNELS", "319"}, {"RPL_ENDOFUSERS", "394"}, {"RPL_TOPIC", "332"}, {"RPL_ADMINEMAIL", "259"}, {"RPL_STATSCOMMANDS", "212"}, {"RPL_ENDOFMOTD", "376"}, {"ERR_NOSUCHNICK", "401"}, {"ERR_TOOMANYCHANNELS", "405"}, {"RPL_TRACEUSER", "205"}, {"ERR_NOTONCHANNEL", "442"}, {"ERR_BADCHANMASK", "476"}, {"ERR_CANTKILLSERVER", "483"}, {"RPL_TRYAGAIN", "263"}, {"ERR_NORECIPIENT", "411"}, {"RPL_NOUSERS", "395"}, {"RPL_ENDOFLINKS", "365"}, {"ERR_BANLISTFULL", "478"}, {"RPL_SERVLIST", "234"}, {"RPL_STATSOLINE", "243"}, {"ERR_NOSUCHSERVER", "402"}, {"ERR_UNAVAILRESOURCE", "437"}, {"RPL_EXCEPTLIST", "348"}, {"ERR_NICKCOLLISION", "436"}, {"RPL_LIST", "322"}, {"ERR_ERRONEUSNICKNAME", "432"}, {"ERR_NOSUCHSERVICE", "408"}, {"RPL_TRACERECONNECT", "210"}, {"RPL_TRACEOPERATOR", "204"}, {"RPL_USERS", "393"}, {"RPL_ENDOFWHOIS", "318"}, {"ERR_USERSDISABLED", "446"}, {"ERR_ALREADYREGISTRED", "462"}, {"RPL_ENDOFNAMES", "366"}, {"RPL_WELCOME", "001"}, {"RPL_LUSERME", "255"}, {"ERR_USERONCHANNEL", "443"}, {"ERR_NOMOTD", "422"}, {"ERR_NOPRIVILEGES", "481"}, {"RPL_TRACELOG", "261"}, {"RPL_INVITELIST", "346"}, {"ERR_UNIQOPPRIVSNEEDED", "485"}, {"ERR_USERSDONTMATCH", "502"}, {"RPL_ENDOFINVITELIST", "347"}, {"RPL_CHANNELMODEIS", "324"}, {"ERR_NICKNAMEINUSE", "433"}, {"RPL_VERSION", "351"}, {"RPL_ENDOFEXCEPTLIST", "349"}, {"ERR_NOADMININFO", "423"}, {"RPL_USERHOST", "302"}, {"RPL_LUSERCLIENT", "251"}, {"RPL_LINKS", "364"}, {"ERR_PASSWDMISMATCH", "464"}, {"RPL_TIME", "391"}, {"ERR_YOUWILLBEBANNED", "466"}, {"RPL_TRACELINK", "200"}, {"ERR_BADCHANNELKEY", "475"}, {"RPL_ENDOFSTATS", "219"}, {"RPL_ADMINLOC", "258"}, {"RPL_NAMREPLY", "353"}, {"RPL_WHOISOPERATOR", "313"}, {"RPL_CREATED", "003"}, {"RPL_REHASHING", "382"}, {"ERR_NOCHANMODES", "477"}, {"ERR_NOSERVICEHOST", "492"}, {"RPL_TRACEEND", "262"}, {"ERR_NOTOPLEVEL", "413"}, {"ERR_NEEDMOREPARAMS", "461"}, {"ERR_CHANNELISFULL", "471"}, {"RPL_LISTSTART", "321"}, {"ERR_NONICKNAMEGIVEN", "431"}, {"ERR_NOOPERHOST", "491"}, {"ERR_WASNOSUCHNICK", "406"}, {"RPL_TRACEHANDSHAKE", "202"}, {"RPL_UNIQOPIS", "325"}, {"ERR_CANNOTSENDTOCHAN", "404"}, {"RPL_TRACESERVICE", "207"}, {"RPL_TRACEUNKNOWN", "203"}, {"RPL_WHOISSERVER", "312"}, {"RPL_USERSSTART", "392"}, {"RPL_LISTEND", "323"}, {"RPL_ENDOFWHOWAS", "369"}, {"RPL_ENDOFWHO", "315"}, {"RPL_ISON", "303"}, {"RPL_INVITING", "341"}, {"ERR_CHANOPRIVSNEEDED", "482"}, {"ERR_UNKNOWNCOMMAND", "421"}, {"ERR_UMODEUNKNOWNFLAG", "501"}, {"RPL_NOTOPIC", "331"}, {"ERR_SUMMONDISABLED", "445"}, {"ERR_NOORIGIN", "409"}, {"ERR_FILEERROR", "424"}, {"RPL_MOTDSTART", "375"}, {"RPL_WHOISUSER", "311"}, {"RPL_SUMMONING", "342"}, {"RPL_YOURHOST", "002"}, {"RPL_YOUREOPER", "381"}, {"RPL_ENDOFBANLIST", "368"}, {"RPL_MOTD", "372"}, {"ERR_USERNOTINCHANNEL", "441"}, {"ERR_BANNEDFROMCHAN", "474"}, {"ERR_NOSUCHCHANNEL", "403"}, {"RPL_STATSUPTIME", "242"}, {"RPL_WHOREPLY", "352"}, {"ERR_WILDTOPLEVEL", "414"}, {"ERR_YOUREBANNEDCREEP", "465"}, {"RPL_WHOISIDLE", "317"}, {"RPL_BOUNCE", "005"}, {"RPL_SERVLISTEND", "235"}, {"RPL_TRACECONNECTING", "201"}, {"RPL_UMODEIS", "221"}, {"ERR_BADMASK", "415"}, {"RPL_STATSLINKINFO", "211"}, {"RPL_YOURESERVICE", "383"}]), Codes = dict:from_list(lists:map(fun({K, V}) -> {V, K} end, dict:to_list(Symbols))), register(irc_lookup_server, spawn_link(?MODULE, loop, [Symbols, Codes])); _ -> ok end. loop(Symbols, Codes) -> receive {get_symbol, Pid, Code} -> case dict:find(Code, Codes) of {ok, Value} -> Pid ! {symbol, Value}; error -> Pid ! {irc_lookup_error, not_found} end, loop(Symbols, Codes); {get_code, Pid, Symbol} -> case dict:find(Symbol, Symbols) of {ok, Value} -> Pid ! {code, Value}; error -> Pid ! {irc_lookup_error, not_found} end, loop(Symbols, Codes); stop -> unregister(irc_lookup_server) end. translate_command(Command) -> irc_lookup_server ! {get_symbol, self(), Command}, receive {symbol, Value} -> Value; {irc_lookup_error, _} -> Command end. shutdown() -> irc_lookup_server ! stop. % Unit Tests test() -> start(), "ERR_CHANOPRIVSNEEDED" = translate_command("482"), "PLOP" = translate_command("PLOP"), shutdown().
null
https://raw.githubusercontent.com/orbitz/oort/a61ec85508917ae9a3f6672a0b708d47c23bb260/src/irc_lookup.erl
erlang
Unit Tests
-module(irc_lookup). -author(""). -export([start/0, translate_command/1, loop/2, shutdown/0, test/0]). start() -> case whereis(irc_lookup_server) of undefined -> Symbols = dict:from_list([ {"RPL_UNAWAY", "305"}, {"ERR_TOOMANYTARGETS", "407"}, {"ERR_KEYSET", "467"}, {"RPL_INFO", "371"}, {"RPL_TRACECLASS", "209"}, {"RPL_AWAY", "301"}, {"ERR_RESTRICTED", "484"}, {"RPL_NOWAWAY", "306"}, {"RPL_ADMINME", "256"}, {"RPL_TRACESERVER", "206"}, {"ERR_NOPERMFORHOST", "463"}, {"ERR_NOTREGISTERED", "451"}, {"RPL_BANLIST", "367"}, {"RPL_ENDOFINFO", "374"}, {"RPL_TRACENEWTYPE", "208"}, {"RPL_LUSEROP", "252"}, {"RPL_WHOWASUSER", "314"}, {"RPL_LUSERCHANNELS", "254"}, {"RPL_LUSERUNKNOWN", "253"}, {"ERR_NOLOGIN", "444"}, {"ERR_NOTEXTTOSEND", "412"}, {"RPL_MYINFO", "004"}, {"ERR_INVITEONLYCHAN", "473"}, {"ERR_UNKNOWNMODE", "472"}, {"RPL_WHOISCHANNELS", "319"}, {"RPL_ENDOFUSERS", "394"}, {"RPL_TOPIC", "332"}, {"RPL_ADMINEMAIL", "259"}, {"RPL_STATSCOMMANDS", "212"}, {"RPL_ENDOFMOTD", "376"}, {"ERR_NOSUCHNICK", "401"}, {"ERR_TOOMANYCHANNELS", "405"}, {"RPL_TRACEUSER", "205"}, {"ERR_NOTONCHANNEL", "442"}, {"ERR_BADCHANMASK", "476"}, {"ERR_CANTKILLSERVER", "483"}, {"RPL_TRYAGAIN", "263"}, {"ERR_NORECIPIENT", "411"}, {"RPL_NOUSERS", "395"}, {"RPL_ENDOFLINKS", "365"}, {"ERR_BANLISTFULL", "478"}, {"RPL_SERVLIST", "234"}, {"RPL_STATSOLINE", "243"}, {"ERR_NOSUCHSERVER", "402"}, {"ERR_UNAVAILRESOURCE", "437"}, {"RPL_EXCEPTLIST", "348"}, {"ERR_NICKCOLLISION", "436"}, {"RPL_LIST", "322"}, {"ERR_ERRONEUSNICKNAME", "432"}, {"ERR_NOSUCHSERVICE", "408"}, {"RPL_TRACERECONNECT", "210"}, {"RPL_TRACEOPERATOR", "204"}, {"RPL_USERS", "393"}, {"RPL_ENDOFWHOIS", "318"}, {"ERR_USERSDISABLED", "446"}, {"ERR_ALREADYREGISTRED", "462"}, {"RPL_ENDOFNAMES", "366"}, {"RPL_WELCOME", "001"}, {"RPL_LUSERME", "255"}, {"ERR_USERONCHANNEL", "443"}, {"ERR_NOMOTD", "422"}, {"ERR_NOPRIVILEGES", "481"}, {"RPL_TRACELOG", "261"}, {"RPL_INVITELIST", "346"}, {"ERR_UNIQOPPRIVSNEEDED", "485"}, {"ERR_USERSDONTMATCH", "502"}, {"RPL_ENDOFINVITELIST", "347"}, {"RPL_CHANNELMODEIS", "324"}, {"ERR_NICKNAMEINUSE", "433"}, {"RPL_VERSION", "351"}, {"RPL_ENDOFEXCEPTLIST", "349"}, {"ERR_NOADMININFO", "423"}, {"RPL_USERHOST", "302"}, {"RPL_LUSERCLIENT", "251"}, {"RPL_LINKS", "364"}, {"ERR_PASSWDMISMATCH", "464"}, {"RPL_TIME", "391"}, {"ERR_YOUWILLBEBANNED", "466"}, {"RPL_TRACELINK", "200"}, {"ERR_BADCHANNELKEY", "475"}, {"RPL_ENDOFSTATS", "219"}, {"RPL_ADMINLOC", "258"}, {"RPL_NAMREPLY", "353"}, {"RPL_WHOISOPERATOR", "313"}, {"RPL_CREATED", "003"}, {"RPL_REHASHING", "382"}, {"ERR_NOCHANMODES", "477"}, {"ERR_NOSERVICEHOST", "492"}, {"RPL_TRACEEND", "262"}, {"ERR_NOTOPLEVEL", "413"}, {"ERR_NEEDMOREPARAMS", "461"}, {"ERR_CHANNELISFULL", "471"}, {"RPL_LISTSTART", "321"}, {"ERR_NONICKNAMEGIVEN", "431"}, {"ERR_NOOPERHOST", "491"}, {"ERR_WASNOSUCHNICK", "406"}, {"RPL_TRACEHANDSHAKE", "202"}, {"RPL_UNIQOPIS", "325"}, {"ERR_CANNOTSENDTOCHAN", "404"}, {"RPL_TRACESERVICE", "207"}, {"RPL_TRACEUNKNOWN", "203"}, {"RPL_WHOISSERVER", "312"}, {"RPL_USERSSTART", "392"}, {"RPL_LISTEND", "323"}, {"RPL_ENDOFWHOWAS", "369"}, {"RPL_ENDOFWHO", "315"}, {"RPL_ISON", "303"}, {"RPL_INVITING", "341"}, {"ERR_CHANOPRIVSNEEDED", "482"}, {"ERR_UNKNOWNCOMMAND", "421"}, {"ERR_UMODEUNKNOWNFLAG", "501"}, {"RPL_NOTOPIC", "331"}, {"ERR_SUMMONDISABLED", "445"}, {"ERR_NOORIGIN", "409"}, {"ERR_FILEERROR", "424"}, {"RPL_MOTDSTART", "375"}, {"RPL_WHOISUSER", "311"}, {"RPL_SUMMONING", "342"}, {"RPL_YOURHOST", "002"}, {"RPL_YOUREOPER", "381"}, {"RPL_ENDOFBANLIST", "368"}, {"RPL_MOTD", "372"}, {"ERR_USERNOTINCHANNEL", "441"}, {"ERR_BANNEDFROMCHAN", "474"}, {"ERR_NOSUCHCHANNEL", "403"}, {"RPL_STATSUPTIME", "242"}, {"RPL_WHOREPLY", "352"}, {"ERR_WILDTOPLEVEL", "414"}, {"ERR_YOUREBANNEDCREEP", "465"}, {"RPL_WHOISIDLE", "317"}, {"RPL_BOUNCE", "005"}, {"RPL_SERVLISTEND", "235"}, {"RPL_TRACECONNECTING", "201"}, {"RPL_UMODEIS", "221"}, {"ERR_BADMASK", "415"}, {"RPL_STATSLINKINFO", "211"}, {"RPL_YOURESERVICE", "383"}]), Codes = dict:from_list(lists:map(fun({K, V}) -> {V, K} end, dict:to_list(Symbols))), register(irc_lookup_server, spawn_link(?MODULE, loop, [Symbols, Codes])); _ -> ok end. loop(Symbols, Codes) -> receive {get_symbol, Pid, Code} -> case dict:find(Code, Codes) of {ok, Value} -> Pid ! {symbol, Value}; error -> Pid ! {irc_lookup_error, not_found} end, loop(Symbols, Codes); {get_code, Pid, Symbol} -> case dict:find(Symbol, Symbols) of {ok, Value} -> Pid ! {code, Value}; error -> Pid ! {irc_lookup_error, not_found} end, loop(Symbols, Codes); stop -> unregister(irc_lookup_server) end. translate_command(Command) -> irc_lookup_server ! {get_symbol, self(), Command}, receive {symbol, Value} -> Value; {irc_lookup_error, _} -> Command end. shutdown() -> irc_lookup_server ! stop. test() -> start(), "ERR_CHANOPRIVSNEEDED" = translate_command("482"), "PLOP" = translate_command("PLOP"), shutdown().
c491fd0610f02f046940b99bb92931b25aeb27fab77eb5140488465ef7d54920
clojure-interop/java-jdk
DatatypeConverterInterface.clj
(ns javax.xml.bind.DatatypeConverterInterface " The DatatypeConverterInterface is for JAXB provider use only. A JAXB provider must supply a class that implements this interface. JAXB Providers are required to call the DatatypeConverter.setDatatypeConverter api at some point before the first marshal or unmarshal operation (perhaps during the call to JAXBContext.newInstance). This step is necessary to configure the converter that should be used to perform the print and parse functionality. Calling this api repeatedly will have no effect - the DatatypeConverter instance passed into the first invocation is the one that will be used from then on. This interface defines the parse and print methods. There is one parse and print method for each XML schema datatype specified in the the default binding Table 5-1 in the JAXB specification. The parse and print methods defined here are invoked by the static parse and print methods defined in the DatatypeConverter class. A parse method for a XML schema datatype must be capable of converting any lexical representation of the XML schema datatype ( specified by the XML Schema Part2: Datatypes specification into a value in the value space of the XML schema datatype. If an error is encountered during conversion, then an IllegalArgumentException or a subclass of IllegalArgumentException must be thrown by the method. A print method for a XML schema datatype can output any lexical representation that is valid with respect to the XML schema datatype. If an error is encountered during conversion, then an IllegalArgumentException, or a subclass of IllegalArgumentException must be thrown by the method. The prefix xsd: is used to refer to XML schema datatypes XML Schema Part2: Datatypes specification." (:refer-clojure :only [require comment defn ->]) (:import [javax.xml.bind DatatypeConverterInterface])) (defn parse-base-64-binary "Converts the string argument into an array of bytes. lexical-xsd-base-64-binary - A string containing lexical representation of xsd:base64Binary. - `java.lang.String` returns: An array of bytes represented by the string argument. - `byte[]` throws: java.lang.IllegalArgumentException - if string parameter does not conform to lexical value space defined in XML Schema Part 2: Datatypes for xsd:base64Binary" ([^DatatypeConverterInterface this ^java.lang.String lexical-xsd-base-64-binary] (-> this (.parseBase64Binary lexical-xsd-base-64-binary)))) (defn parse-date-time "Converts the string argument into a Calendar value. lexical-xsd-date-time - A string containing lexical representation of xsd:datetime. - `java.lang.String` returns: A Calendar object represented by the string argument. - `java.util.Calendar` throws: java.lang.IllegalArgumentException - if string parameter does not conform to lexical value space defined in XML Schema Part 2: Datatypes for xsd:dateTime." (^java.util.Calendar [^DatatypeConverterInterface this ^java.lang.String lexical-xsd-date-time] (-> this (.parseDateTime lexical-xsd-date-time)))) (defn print-unsigned-int "Converts a long value into a string. val - A long value - `long` returns: A string containing a lexical representation of xsd:unsignedInt - `java.lang.String`" (^java.lang.String [^DatatypeConverterInterface this ^Long val] (-> this (.printUnsignedInt val)))) (defn print-q-name "Converts a QName instance into a string. val - A QName value - `javax.xml.namespace.QName` nsc - A namespace context for interpreting a prefix within a QName. - `javax.xml.namespace.NamespaceContext` returns: A string containing a lexical representation of QName - `java.lang.String` throws: java.lang.IllegalArgumentException - if val is null or if nsc is non-null or nsc.getPrefix(nsprefixFromVal) is null." (^java.lang.String [^DatatypeConverterInterface this ^javax.xml.namespace.QName val ^javax.xml.namespace.NamespaceContext nsc] (-> this (.printQName val nsc)))) (defn parse-q-name "Converts the string argument into a QName value. String parameter lexicalXSDQname must conform to lexical value space specifed at XML Schema Part 2:Datatypes specification:QNames lexical-xsdq-name - A string containing lexical representation of xsd:QName. - `java.lang.String` nsc - A namespace context for interpreting a prefix within a QName. - `javax.xml.namespace.NamespaceContext` returns: A QName value represented by the string argument. - `javax.xml.namespace.QName` throws: java.lang.IllegalArgumentException - if string parameter does not conform to XML Schema Part 2 specification or if namespace prefix of lexicalXSDQname is not bound to a URI in NamespaceContext nsc." (^javax.xml.namespace.QName [^DatatypeConverterInterface this ^java.lang.String lexical-xsdq-name ^javax.xml.namespace.NamespaceContext nsc] (-> this (.parseQName lexical-xsdq-name nsc)))) (defn print-time "Converts a Calendar value into a string. val - A Calendar value - `java.util.Calendar` returns: A string containing a lexical representation of xsd:time - `java.lang.String` throws: java.lang.IllegalArgumentException - if val is null." (^java.lang.String [^DatatypeConverterInterface this ^java.util.Calendar val] (-> this (.printTime val)))) (defn print-short "Converts a short value into a string. val - A short value - `short` returns: A string containing a lexical representation of xsd:short - `java.lang.String`" (^java.lang.String [^DatatypeConverterInterface this ^Short val] (-> this (.printShort val)))) (defn print-any-simple-type "Converts a string value into a string. val - A string value - `java.lang.String` returns: A string containing a lexical representation of xsd:AnySimpleType - `java.lang.String`" (^java.lang.String [^DatatypeConverterInterface this ^java.lang.String val] (-> this (.printAnySimpleType val)))) (defn parse-string "Convert the string argument into a string. lexical-xsd-string - A lexical representation of the XML Schema datatype xsd:string - `java.lang.String` returns: A string that is the same as the input string. - `java.lang.String`" (^java.lang.String [^DatatypeConverterInterface this ^java.lang.String lexical-xsd-string] (-> this (.parseString lexical-xsd-string)))) (defn parse-short "Converts the string argument into a short value. lexical-xsd-short - A string containing lexical representation of xsd:short. - `java.lang.String` returns: A short value represented by the string argument. - `short` throws: java.lang.NumberFormatException - lexicalXSDShort is not a valid string representation of a short value." (^Short [^DatatypeConverterInterface this ^java.lang.String lexical-xsd-short] (-> this (.parseShort lexical-xsd-short)))) (defn parse-time "Converts the string argument into a Calendar value. lexical-xsd-time - A string containing lexical representation of xsd:Time. - `java.lang.String` returns: A Calendar value represented by the string argument. - `java.util.Calendar` throws: java.lang.IllegalArgumentException - if string parameter does not conform to lexical value space defined in XML Schema Part 2: Datatypes for xsd:Time." (^java.util.Calendar [^DatatypeConverterInterface this ^java.lang.String lexical-xsd-time] (-> this (.parseTime lexical-xsd-time)))) (defn parse-hex-binary "Converts the string argument into an array of bytes. lexical-xsd-hex-binary - A string containing lexical representation of xsd:hexBinary. - `java.lang.String` returns: An array of bytes represented by the string argument. - `byte[]` throws: java.lang.IllegalArgumentException - if string parameter does not conform to lexical value space defined in XML Schema Part 2: Datatypes for xsd:hexBinary." ([^DatatypeConverterInterface this ^java.lang.String lexical-xsd-hex-binary] (-> this (.parseHexBinary lexical-xsd-hex-binary)))) (defn print-unsigned-short "Converts an int value into a string. val - An int value - `int` returns: A string containing a lexical representation of xsd:unsignedShort - `java.lang.String`" (^java.lang.String [^DatatypeConverterInterface this ^Integer val] (-> this (.printUnsignedShort val)))) (defn parse-float "Converts the string argument into a float value. lexical-xsd-float - A string containing lexical representation of xsd:float. - `java.lang.String` returns: A float value represented by the string argument. - `float` throws: java.lang.NumberFormatException - lexicalXSDFloat is not a valid string representation of a float value." (^Float [^DatatypeConverterInterface this ^java.lang.String lexical-xsd-float] (-> this (.parseFloat lexical-xsd-float)))) (defn print-base-64-binary "Converts an array of bytes into a string. val - an array of bytes - `byte[]` returns: A string containing a lexical representation of xsd:base64Binary - `java.lang.String` throws: java.lang.IllegalArgumentException - if val is null." (^java.lang.String [^DatatypeConverterInterface this val] (-> this (.printBase64Binary val)))) (defn parse-date "Converts the string argument into a Calendar value. lexical-xsd-date - A string containing lexical representation of xsd:Date. - `java.lang.String` returns: A Calendar value represented by the string argument. - `java.util.Calendar` throws: java.lang.IllegalArgumentException - if string parameter does not conform to lexical value space defined in XML Schema Part 2: Datatypes for xsd:Date." (^java.util.Calendar [^DatatypeConverterInterface this ^java.lang.String lexical-xsd-date] (-> this (.parseDate lexical-xsd-date)))) (defn parse-integer "Convert the string argument into a BigInteger value. lexical-xsd-integer - A string containing a lexical representation of xsd:integer. - `java.lang.String` returns: A BigInteger value represented by the string argument. - `java.math.BigInteger` throws: java.lang.NumberFormatException - lexicalXSDInteger is not a valid string representation of a BigInteger value." (^java.math.BigInteger [^DatatypeConverterInterface this ^java.lang.String lexical-xsd-integer] (-> this (.parseInteger lexical-xsd-integer)))) (defn print-string "Converts the string argument into a string. val - A string value. - `java.lang.String` returns: A string containing a lexical representation of xsd:string - `java.lang.String`" (^java.lang.String [^DatatypeConverterInterface this ^java.lang.String val] (-> this (.printString val)))) (defn parse-decimal "Converts the string argument into a BigDecimal value. lexical-xsd-decimal - A string containing lexical representation of xsd:decimal. - `java.lang.String` returns: A BigDecimal value represented by the string argument. - `java.math.BigDecimal` throws: java.lang.NumberFormatException - lexicalXSDDecimal is not a valid string representation of BigDecimal." (^java.math.BigDecimal [^DatatypeConverterInterface this ^java.lang.String lexical-xsd-decimal] (-> this (.parseDecimal lexical-xsd-decimal)))) (defn print-decimal "Converts a BigDecimal value into a string. val - A BigDecimal value - `java.math.BigDecimal` returns: A string containing a lexical representation of xsd:decimal - `java.lang.String` throws: java.lang.IllegalArgumentException - val is null." (^java.lang.String [^DatatypeConverterInterface this ^java.math.BigDecimal val] (-> this (.printDecimal val)))) (defn print-date-time "Converts a Calendar value into a string. val - A Calendar value - `java.util.Calendar` returns: A string containing a lexical representation of xsd:dateTime - `java.lang.String` throws: java.lang.IllegalArgumentException - if val is null." (^java.lang.String [^DatatypeConverterInterface this ^java.util.Calendar val] (-> this (.printDateTime val)))) (defn print-date "Converts a Calendar value into a string. val - A Calendar value - `java.util.Calendar` returns: A string containing a lexical representation of xsd:date - `java.lang.String` throws: java.lang.IllegalArgumentException - if val is null." (^java.lang.String [^DatatypeConverterInterface this ^java.util.Calendar val] (-> this (.printDate val)))) (defn print-long "Converts a long value into a string. val - A long value - `long` returns: A string containing a lexical representation of xsd:long - `java.lang.String`" (^java.lang.String [^DatatypeConverterInterface this ^Long val] (-> this (.printLong val)))) (defn print-float "Converts a float value into a string. val - A float value - `float` returns: A string containing a lexical representation of xsd:float - `java.lang.String`" (^java.lang.String [^DatatypeConverterInterface this ^Float val] (-> this (.printFloat val)))) (defn print-byte "Converts a byte value into a string. val - A byte value - `byte` returns: A string containing a lexical representation of xsd:byte - `java.lang.String`" (^java.lang.String [^DatatypeConverterInterface this ^Byte val] (-> this (.printByte val)))) (defn parse-boolean "Converts the string argument into a boolean value. lexical-xsd-boolean - A string containing lexical representation of xsd:boolean. - `java.lang.String` returns: A boolean value represented by the string argument. - `boolean` throws: java.lang.IllegalArgumentException - if string parameter does not conform to lexical value space defined in XML Schema Part 2: Datatypes for xsd:boolean." (^Boolean [^DatatypeConverterInterface this ^java.lang.String lexical-xsd-boolean] (-> this (.parseBoolean lexical-xsd-boolean)))) (defn print-integer "Converts a BigInteger value into a string. val - A BigInteger value - `java.math.BigInteger` returns: A string containing a lexical representation of xsd:integer - `java.lang.String` throws: java.lang.IllegalArgumentException - val is null." (^java.lang.String [^DatatypeConverterInterface this ^java.math.BigInteger val] (-> this (.printInteger val)))) (defn parse-double "Converts the string argument into a double value. lexical-xsd-double - A string containing lexical representation of xsd:double. - `java.lang.String` returns: A double value represented by the string argument. - `double` throws: java.lang.NumberFormatException - lexicalXSDDouble is not a valid string representation of a double value." (^Double [^DatatypeConverterInterface this ^java.lang.String lexical-xsd-double] (-> this (.parseDouble lexical-xsd-double)))) (defn parse-long "Converts the string argument into a long value. lexical-xsd-long - A string containing lexical representation of xsd:long. - `java.lang.String` returns: A long value represented by the string argument. - `long` throws: java.lang.NumberFormatException - lexicalXSDLong is not a valid string representation of a long value." (^Long [^DatatypeConverterInterface this ^java.lang.String lexical-xsd-long] (-> this (.parseLong lexical-xsd-long)))) (defn print-int "Converts an int value into a string. val - An int value - `int` returns: A string containing a lexical representation of xsd:int - `java.lang.String`" (^java.lang.String [^DatatypeConverterInterface this ^Integer val] (-> this (.printInt val)))) (defn parse-any-simple-type "Return a string containing the lexical representation of the simple type. lexical-xsd-any-simple-type - A string containing lexical representation of the simple type. - `java.lang.String` returns: A string containing the lexical representation of the simple type. - `java.lang.String`" (^java.lang.String [^DatatypeConverterInterface this ^java.lang.String lexical-xsd-any-simple-type] (-> this (.parseAnySimpleType lexical-xsd-any-simple-type)))) (defn print-double "Converts a double value into a string. val - A double value - `double` returns: A string containing a lexical representation of xsd:double - `java.lang.String`" (^java.lang.String [^DatatypeConverterInterface this ^Double val] (-> this (.printDouble val)))) (defn parse-unsigned-short "Converts the string argument into an int value. lexical-xsd-unsigned-short - A string containing lexical representation of xsd:unsignedShort. - `java.lang.String` returns: An int value represented by the string argument. - `int` throws: java.lang.NumberFormatException - if string parameter can not be parsed into an int value." (^Integer [^DatatypeConverterInterface this ^java.lang.String lexical-xsd-unsigned-short] (-> this (.parseUnsignedShort lexical-xsd-unsigned-short)))) (defn parse-byte "Converts the string argument into a byte value. lexical-xsd-byte - A string containing lexical representation of xsd:byte. - `java.lang.String` returns: A byte value represented by the string argument. - `byte` throws: java.lang.NumberFormatException - lexicalXSDByte does not contain a parseable byte." (^Byte [^DatatypeConverterInterface this ^java.lang.String lexical-xsd-byte] (-> this (.parseByte lexical-xsd-byte)))) (defn print-boolean "Converts a boolean value into a string. val - A boolean value - `boolean` returns: A string containing a lexical representation of xsd:boolean - `java.lang.String`" (^java.lang.String [^DatatypeConverterInterface this ^Boolean val] (-> this (.printBoolean val)))) (defn print-hex-binary "Converts an array of bytes into a string. val - an array of bytes - `byte[]` returns: A string containing a lexical representation of xsd:hexBinary - `java.lang.String` throws: java.lang.IllegalArgumentException - if val is null." (^java.lang.String [^DatatypeConverterInterface this val] (-> this (.printHexBinary val)))) (defn parse-unsigned-int "Converts the string argument into a long value. lexical-xsd-unsigned-int - A string containing lexical representation of xsd:unsignedInt. - `java.lang.String` returns: A long value represented by the string argument. - `long` throws: java.lang.NumberFormatException - if string parameter can not be parsed into a long value." (^Long [^DatatypeConverterInterface this ^java.lang.String lexical-xsd-unsigned-int] (-> this (.parseUnsignedInt lexical-xsd-unsigned-int)))) (defn parse-int "Convert the string argument into an int value. lexical-xsd-int - A string containing a lexical representation of xsd:int. - `java.lang.String` returns: An int value represented byte the string argument. - `int` throws: java.lang.NumberFormatException - lexicalXSDInt is not a valid string representation of an int value." (^Integer [^DatatypeConverterInterface this ^java.lang.String lexical-xsd-int] (-> this (.parseInt lexical-xsd-int))))
null
https://raw.githubusercontent.com/clojure-interop/java-jdk/8d7a223e0f9a0965eb0332fad595cf7649d9d96e/javax.xml/src/javax/xml/bind/DatatypeConverterInterface.clj
clojure
(ns javax.xml.bind.DatatypeConverterInterface " The DatatypeConverterInterface is for JAXB provider use only. A JAXB provider must supply a class that implements this interface. JAXB Providers are required to call the DatatypeConverter.setDatatypeConverter api at some point before the first marshal or unmarshal operation (perhaps during the call to JAXBContext.newInstance). This step is necessary to configure the converter that should be used to perform the print and parse functionality. Calling this api repeatedly will have no effect - the DatatypeConverter instance passed into the first invocation is the one that will be used from then on. This interface defines the parse and print methods. There is one parse and print method for each XML schema datatype specified in the the default binding Table 5-1 in the JAXB specification. The parse and print methods defined here are invoked by the static parse and print methods defined in the DatatypeConverter class. A parse method for a XML schema datatype must be capable of converting any lexical representation of the XML schema datatype ( specified by the XML Schema Part2: Datatypes specification into a value in the value space of the XML schema datatype. If an error is encountered during conversion, then an IllegalArgumentException or a subclass of IllegalArgumentException must be thrown by the method. A print method for a XML schema datatype can output any lexical representation that is valid with respect to the XML schema datatype. If an error is encountered during conversion, then an IllegalArgumentException, or a subclass of IllegalArgumentException must be thrown by the method. The prefix xsd: is used to refer to XML schema datatypes XML Schema Part2: Datatypes specification." (:refer-clojure :only [require comment defn ->]) (:import [javax.xml.bind DatatypeConverterInterface])) (defn parse-base-64-binary "Converts the string argument into an array of bytes. lexical-xsd-base-64-binary - A string containing lexical representation of xsd:base64Binary. - `java.lang.String` returns: An array of bytes represented by the string argument. - `byte[]` throws: java.lang.IllegalArgumentException - if string parameter does not conform to lexical value space defined in XML Schema Part 2: Datatypes for xsd:base64Binary" ([^DatatypeConverterInterface this ^java.lang.String lexical-xsd-base-64-binary] (-> this (.parseBase64Binary lexical-xsd-base-64-binary)))) (defn parse-date-time "Converts the string argument into a Calendar value. lexical-xsd-date-time - A string containing lexical representation of xsd:datetime. - `java.lang.String` returns: A Calendar object represented by the string argument. - `java.util.Calendar` throws: java.lang.IllegalArgumentException - if string parameter does not conform to lexical value space defined in XML Schema Part 2: Datatypes for xsd:dateTime." (^java.util.Calendar [^DatatypeConverterInterface this ^java.lang.String lexical-xsd-date-time] (-> this (.parseDateTime lexical-xsd-date-time)))) (defn print-unsigned-int "Converts a long value into a string. val - A long value - `long` returns: A string containing a lexical representation of xsd:unsignedInt - `java.lang.String`" (^java.lang.String [^DatatypeConverterInterface this ^Long val] (-> this (.printUnsignedInt val)))) (defn print-q-name "Converts a QName instance into a string. val - A QName value - `javax.xml.namespace.QName` nsc - A namespace context for interpreting a prefix within a QName. - `javax.xml.namespace.NamespaceContext` returns: A string containing a lexical representation of QName - `java.lang.String` throws: java.lang.IllegalArgumentException - if val is null or if nsc is non-null or nsc.getPrefix(nsprefixFromVal) is null." (^java.lang.String [^DatatypeConverterInterface this ^javax.xml.namespace.QName val ^javax.xml.namespace.NamespaceContext nsc] (-> this (.printQName val nsc)))) (defn parse-q-name "Converts the string argument into a QName value. String parameter lexicalXSDQname must conform to lexical value space specifed at XML Schema Part 2:Datatypes specification:QNames lexical-xsdq-name - A string containing lexical representation of xsd:QName. - `java.lang.String` nsc - A namespace context for interpreting a prefix within a QName. - `javax.xml.namespace.NamespaceContext` returns: A QName value represented by the string argument. - `javax.xml.namespace.QName` throws: java.lang.IllegalArgumentException - if string parameter does not conform to XML Schema Part 2 specification or if namespace prefix of lexicalXSDQname is not bound to a URI in NamespaceContext nsc." (^javax.xml.namespace.QName [^DatatypeConverterInterface this ^java.lang.String lexical-xsdq-name ^javax.xml.namespace.NamespaceContext nsc] (-> this (.parseQName lexical-xsdq-name nsc)))) (defn print-time "Converts a Calendar value into a string. val - A Calendar value - `java.util.Calendar` returns: A string containing a lexical representation of xsd:time - `java.lang.String` throws: java.lang.IllegalArgumentException - if val is null." (^java.lang.String [^DatatypeConverterInterface this ^java.util.Calendar val] (-> this (.printTime val)))) (defn print-short "Converts a short value into a string. val - A short value - `short` returns: A string containing a lexical representation of xsd:short - `java.lang.String`" (^java.lang.String [^DatatypeConverterInterface this ^Short val] (-> this (.printShort val)))) (defn print-any-simple-type "Converts a string value into a string. val - A string value - `java.lang.String` returns: A string containing a lexical representation of xsd:AnySimpleType - `java.lang.String`" (^java.lang.String [^DatatypeConverterInterface this ^java.lang.String val] (-> this (.printAnySimpleType val)))) (defn parse-string "Convert the string argument into a string. lexical-xsd-string - A lexical representation of the XML Schema datatype xsd:string - `java.lang.String` returns: A string that is the same as the input string. - `java.lang.String`" (^java.lang.String [^DatatypeConverterInterface this ^java.lang.String lexical-xsd-string] (-> this (.parseString lexical-xsd-string)))) (defn parse-short "Converts the string argument into a short value. lexical-xsd-short - A string containing lexical representation of xsd:short. - `java.lang.String` returns: A short value represented by the string argument. - `short` throws: java.lang.NumberFormatException - lexicalXSDShort is not a valid string representation of a short value." (^Short [^DatatypeConverterInterface this ^java.lang.String lexical-xsd-short] (-> this (.parseShort lexical-xsd-short)))) (defn parse-time "Converts the string argument into a Calendar value. lexical-xsd-time - A string containing lexical representation of xsd:Time. - `java.lang.String` returns: A Calendar value represented by the string argument. - `java.util.Calendar` throws: java.lang.IllegalArgumentException - if string parameter does not conform to lexical value space defined in XML Schema Part 2: Datatypes for xsd:Time." (^java.util.Calendar [^DatatypeConverterInterface this ^java.lang.String lexical-xsd-time] (-> this (.parseTime lexical-xsd-time)))) (defn parse-hex-binary "Converts the string argument into an array of bytes. lexical-xsd-hex-binary - A string containing lexical representation of xsd:hexBinary. - `java.lang.String` returns: An array of bytes represented by the string argument. - `byte[]` throws: java.lang.IllegalArgumentException - if string parameter does not conform to lexical value space defined in XML Schema Part 2: Datatypes for xsd:hexBinary." ([^DatatypeConverterInterface this ^java.lang.String lexical-xsd-hex-binary] (-> this (.parseHexBinary lexical-xsd-hex-binary)))) (defn print-unsigned-short "Converts an int value into a string. val - An int value - `int` returns: A string containing a lexical representation of xsd:unsignedShort - `java.lang.String`" (^java.lang.String [^DatatypeConverterInterface this ^Integer val] (-> this (.printUnsignedShort val)))) (defn parse-float "Converts the string argument into a float value. lexical-xsd-float - A string containing lexical representation of xsd:float. - `java.lang.String` returns: A float value represented by the string argument. - `float` throws: java.lang.NumberFormatException - lexicalXSDFloat is not a valid string representation of a float value." (^Float [^DatatypeConverterInterface this ^java.lang.String lexical-xsd-float] (-> this (.parseFloat lexical-xsd-float)))) (defn print-base-64-binary "Converts an array of bytes into a string. val - an array of bytes - `byte[]` returns: A string containing a lexical representation of xsd:base64Binary - `java.lang.String` throws: java.lang.IllegalArgumentException - if val is null." (^java.lang.String [^DatatypeConverterInterface this val] (-> this (.printBase64Binary val)))) (defn parse-date "Converts the string argument into a Calendar value. lexical-xsd-date - A string containing lexical representation of xsd:Date. - `java.lang.String` returns: A Calendar value represented by the string argument. - `java.util.Calendar` throws: java.lang.IllegalArgumentException - if string parameter does not conform to lexical value space defined in XML Schema Part 2: Datatypes for xsd:Date." (^java.util.Calendar [^DatatypeConverterInterface this ^java.lang.String lexical-xsd-date] (-> this (.parseDate lexical-xsd-date)))) (defn parse-integer "Convert the string argument into a BigInteger value. lexical-xsd-integer - A string containing a lexical representation of xsd:integer. - `java.lang.String` returns: A BigInteger value represented by the string argument. - `java.math.BigInteger` throws: java.lang.NumberFormatException - lexicalXSDInteger is not a valid string representation of a BigInteger value." (^java.math.BigInteger [^DatatypeConverterInterface this ^java.lang.String lexical-xsd-integer] (-> this (.parseInteger lexical-xsd-integer)))) (defn print-string "Converts the string argument into a string. val - A string value. - `java.lang.String` returns: A string containing a lexical representation of xsd:string - `java.lang.String`" (^java.lang.String [^DatatypeConverterInterface this ^java.lang.String val] (-> this (.printString val)))) (defn parse-decimal "Converts the string argument into a BigDecimal value. lexical-xsd-decimal - A string containing lexical representation of xsd:decimal. - `java.lang.String` returns: A BigDecimal value represented by the string argument. - `java.math.BigDecimal` throws: java.lang.NumberFormatException - lexicalXSDDecimal is not a valid string representation of BigDecimal." (^java.math.BigDecimal [^DatatypeConverterInterface this ^java.lang.String lexical-xsd-decimal] (-> this (.parseDecimal lexical-xsd-decimal)))) (defn print-decimal "Converts a BigDecimal value into a string. val - A BigDecimal value - `java.math.BigDecimal` returns: A string containing a lexical representation of xsd:decimal - `java.lang.String` throws: java.lang.IllegalArgumentException - val is null." (^java.lang.String [^DatatypeConverterInterface this ^java.math.BigDecimal val] (-> this (.printDecimal val)))) (defn print-date-time "Converts a Calendar value into a string. val - A Calendar value - `java.util.Calendar` returns: A string containing a lexical representation of xsd:dateTime - `java.lang.String` throws: java.lang.IllegalArgumentException - if val is null." (^java.lang.String [^DatatypeConverterInterface this ^java.util.Calendar val] (-> this (.printDateTime val)))) (defn print-date "Converts a Calendar value into a string. val - A Calendar value - `java.util.Calendar` returns: A string containing a lexical representation of xsd:date - `java.lang.String` throws: java.lang.IllegalArgumentException - if val is null." (^java.lang.String [^DatatypeConverterInterface this ^java.util.Calendar val] (-> this (.printDate val)))) (defn print-long "Converts a long value into a string. val - A long value - `long` returns: A string containing a lexical representation of xsd:long - `java.lang.String`" (^java.lang.String [^DatatypeConverterInterface this ^Long val] (-> this (.printLong val)))) (defn print-float "Converts a float value into a string. val - A float value - `float` returns: A string containing a lexical representation of xsd:float - `java.lang.String`" (^java.lang.String [^DatatypeConverterInterface this ^Float val] (-> this (.printFloat val)))) (defn print-byte "Converts a byte value into a string. val - A byte value - `byte` returns: A string containing a lexical representation of xsd:byte - `java.lang.String`" (^java.lang.String [^DatatypeConverterInterface this ^Byte val] (-> this (.printByte val)))) (defn parse-boolean "Converts the string argument into a boolean value. lexical-xsd-boolean - A string containing lexical representation of xsd:boolean. - `java.lang.String` returns: A boolean value represented by the string argument. - `boolean` throws: java.lang.IllegalArgumentException - if string parameter does not conform to lexical value space defined in XML Schema Part 2: Datatypes for xsd:boolean." (^Boolean [^DatatypeConverterInterface this ^java.lang.String lexical-xsd-boolean] (-> this (.parseBoolean lexical-xsd-boolean)))) (defn print-integer "Converts a BigInteger value into a string. val - A BigInteger value - `java.math.BigInteger` returns: A string containing a lexical representation of xsd:integer - `java.lang.String` throws: java.lang.IllegalArgumentException - val is null." (^java.lang.String [^DatatypeConverterInterface this ^java.math.BigInteger val] (-> this (.printInteger val)))) (defn parse-double "Converts the string argument into a double value. lexical-xsd-double - A string containing lexical representation of xsd:double. - `java.lang.String` returns: A double value represented by the string argument. - `double` throws: java.lang.NumberFormatException - lexicalXSDDouble is not a valid string representation of a double value." (^Double [^DatatypeConverterInterface this ^java.lang.String lexical-xsd-double] (-> this (.parseDouble lexical-xsd-double)))) (defn parse-long "Converts the string argument into a long value. lexical-xsd-long - A string containing lexical representation of xsd:long. - `java.lang.String` returns: A long value represented by the string argument. - `long` throws: java.lang.NumberFormatException - lexicalXSDLong is not a valid string representation of a long value." (^Long [^DatatypeConverterInterface this ^java.lang.String lexical-xsd-long] (-> this (.parseLong lexical-xsd-long)))) (defn print-int "Converts an int value into a string. val - An int value - `int` returns: A string containing a lexical representation of xsd:int - `java.lang.String`" (^java.lang.String [^DatatypeConverterInterface this ^Integer val] (-> this (.printInt val)))) (defn parse-any-simple-type "Return a string containing the lexical representation of the simple type. lexical-xsd-any-simple-type - A string containing lexical representation of the simple type. - `java.lang.String` returns: A string containing the lexical representation of the simple type. - `java.lang.String`" (^java.lang.String [^DatatypeConverterInterface this ^java.lang.String lexical-xsd-any-simple-type] (-> this (.parseAnySimpleType lexical-xsd-any-simple-type)))) (defn print-double "Converts a double value into a string. val - A double value - `double` returns: A string containing a lexical representation of xsd:double - `java.lang.String`" (^java.lang.String [^DatatypeConverterInterface this ^Double val] (-> this (.printDouble val)))) (defn parse-unsigned-short "Converts the string argument into an int value. lexical-xsd-unsigned-short - A string containing lexical representation of xsd:unsignedShort. - `java.lang.String` returns: An int value represented by the string argument. - `int` throws: java.lang.NumberFormatException - if string parameter can not be parsed into an int value." (^Integer [^DatatypeConverterInterface this ^java.lang.String lexical-xsd-unsigned-short] (-> this (.parseUnsignedShort lexical-xsd-unsigned-short)))) (defn parse-byte "Converts the string argument into a byte value. lexical-xsd-byte - A string containing lexical representation of xsd:byte. - `java.lang.String` returns: A byte value represented by the string argument. - `byte` throws: java.lang.NumberFormatException - lexicalXSDByte does not contain a parseable byte." (^Byte [^DatatypeConverterInterface this ^java.lang.String lexical-xsd-byte] (-> this (.parseByte lexical-xsd-byte)))) (defn print-boolean "Converts a boolean value into a string. val - A boolean value - `boolean` returns: A string containing a lexical representation of xsd:boolean - `java.lang.String`" (^java.lang.String [^DatatypeConverterInterface this ^Boolean val] (-> this (.printBoolean val)))) (defn print-hex-binary "Converts an array of bytes into a string. val - an array of bytes - `byte[]` returns: A string containing a lexical representation of xsd:hexBinary - `java.lang.String` throws: java.lang.IllegalArgumentException - if val is null." (^java.lang.String [^DatatypeConverterInterface this val] (-> this (.printHexBinary val)))) (defn parse-unsigned-int "Converts the string argument into a long value. lexical-xsd-unsigned-int - A string containing lexical representation of xsd:unsignedInt. - `java.lang.String` returns: A long value represented by the string argument. - `long` throws: java.lang.NumberFormatException - if string parameter can not be parsed into a long value." (^Long [^DatatypeConverterInterface this ^java.lang.String lexical-xsd-unsigned-int] (-> this (.parseUnsignedInt lexical-xsd-unsigned-int)))) (defn parse-int "Convert the string argument into an int value. lexical-xsd-int - A string containing a lexical representation of xsd:int. - `java.lang.String` returns: An int value represented byte the string argument. - `int` throws: java.lang.NumberFormatException - lexicalXSDInt is not a valid string representation of an int value." (^Integer [^DatatypeConverterInterface this ^java.lang.String lexical-xsd-int] (-> this (.parseInt lexical-xsd-int))))
1d4de149d758c9844fe22417343233ab146eb46daa41f744dc1aae3aad721940
huangjs/cl
numeric.lisp
Copyright ( c ) 1987 ;;; Permission is given to freely modify and distribute this code ;;; so long as this copyright notice is retained. ;;;; Basic numeric operators are defined here. CL functions implemented here : ;;; + * - / ;;; + has variable # of args, does constant folding (define-ps + (let ((const-part 0) (pending-arg nil)) (for (:in arg (cdr ps-form)) (:do (compile-1 arg) (if (numeric-constant) (setf const-part (+ (remove-number) const-part)) (progn (when pending-arg (emit 'add)) (setf pending-arg t))))) (if pending-arg (when (/= const-part 0) (ps-compile const-part) (emit 'add)) (ps-compile const-part))) 1) ;;; like + (define-ps * (let ((const-part 1) (pending-arg nil)) (for (:in arg (cdr ps-form)) (:do (compile-1 arg) (if (numeric-constant) (setf const-part (* (remove-number) const-part)) (progn (when pending-arg (emit 'mul)) (setf pending-arg t))))) (if pending-arg (when (/= const-part 1) (ps-compile const-part) (emit 'mul)) (ps-compile const-part))) 1) ;;; Like + (define-ps - (if (null (cddr ps-form)) (ps-negate ps-form) (let ((const-part 0) (pending-arg nil)) (for (:in arg (cdr ps-form)) (:do (compile-1 arg) (if (and pending-arg (numeric-constant)) (setf const-part (+ (remove-number) const-part)) (progn (when pending-arg (emit 'sub)) (setf pending-arg t))))) (when (/= const-part 0) (if (numeric-constant) (ps-compile (- (remove-number) const-part)) (progn (ps-compile const-part) (emit 'sub)))))) 1) Unary - (defun ps-negate (ps-form) (compile-1 (cadr ps-form)) (if (numeric-constant) (ps-compile (- (remove-number))) (emit 'neg)) 1) ;;; / is a little hairier for constant folding. (define-ps / (if (null (cddr ps-form)) (ps-recip ps-form) (let ((const-part 1.0) (pending-arg nil)) (for (:in arg (cdr ps-form)) (:do (compile-1 arg) (if (and pending-arg (numeric-constant)) (setf const-part (* (remove-number) const-part)) (progn (when pending-arg (emit 'div)) (setf pending-arg t))))) (when (/= const-part 1.0) (if (numeric-constant) (ps-compile (/ (remove-number) const-part)) (progn (ps-compile const-part) (emit 'div)))))) 1) Unary / (defun ps-recip (ps-form) (compile-1 (cadr ps-form)) (if (numeric-constant) (ps-compile (/ 1.0 (remove-number))) (progn (emit 1) (emit 'exch) (emit 'div))) 1)
null
https://raw.githubusercontent.com/huangjs/cl/96158b3f82f82a6b7d53ef04b3b29c5c8de2dbf7/lib/plisp/compiler/common-lisp/numeric.lisp
lisp
Permission is given to freely modify and distribute this code so long as this copyright notice is retained. Basic numeric operators are defined here. + * - / + has variable # of args, does constant folding like + Like + / is a little hairier for constant folding.
Copyright ( c ) 1987 CL functions implemented here : (define-ps + (let ((const-part 0) (pending-arg nil)) (for (:in arg (cdr ps-form)) (:do (compile-1 arg) (if (numeric-constant) (setf const-part (+ (remove-number) const-part)) (progn (when pending-arg (emit 'add)) (setf pending-arg t))))) (if pending-arg (when (/= const-part 0) (ps-compile const-part) (emit 'add)) (ps-compile const-part))) 1) (define-ps * (let ((const-part 1) (pending-arg nil)) (for (:in arg (cdr ps-form)) (:do (compile-1 arg) (if (numeric-constant) (setf const-part (* (remove-number) const-part)) (progn (when pending-arg (emit 'mul)) (setf pending-arg t))))) (if pending-arg (when (/= const-part 1) (ps-compile const-part) (emit 'mul)) (ps-compile const-part))) 1) (define-ps - (if (null (cddr ps-form)) (ps-negate ps-form) (let ((const-part 0) (pending-arg nil)) (for (:in arg (cdr ps-form)) (:do (compile-1 arg) (if (and pending-arg (numeric-constant)) (setf const-part (+ (remove-number) const-part)) (progn (when pending-arg (emit 'sub)) (setf pending-arg t))))) (when (/= const-part 0) (if (numeric-constant) (ps-compile (- (remove-number) const-part)) (progn (ps-compile const-part) (emit 'sub)))))) 1) Unary - (defun ps-negate (ps-form) (compile-1 (cadr ps-form)) (if (numeric-constant) (ps-compile (- (remove-number))) (emit 'neg)) 1) (define-ps / (if (null (cddr ps-form)) (ps-recip ps-form) (let ((const-part 1.0) (pending-arg nil)) (for (:in arg (cdr ps-form)) (:do (compile-1 arg) (if (and pending-arg (numeric-constant)) (setf const-part (* (remove-number) const-part)) (progn (when pending-arg (emit 'div)) (setf pending-arg t))))) (when (/= const-part 1.0) (if (numeric-constant) (ps-compile (/ (remove-number) const-part)) (progn (ps-compile const-part) (emit 'div)))))) 1) Unary / (defun ps-recip (ps-form) (compile-1 (cadr ps-form)) (if (numeric-constant) (ps-compile (/ 1.0 (remove-number))) (progn (emit 1) (emit 'exch) (emit 'div))) 1)
3d18028ce22c03d1d19521502e35bdfddb92d07bcf6022b7aaedef80aacfeff6
coord-e/mlml
resolve.ml
(* resolve paths and convert them into string *) (* TODO: use more clear ways to resolve paths *) module Path = Tree.Path module Expr = Tree.Expression module Mod = Tree.Module module TyExpr = Tree.Type_expression module Pat = Tree.Pattern module NS = Tree.Namespace module SS = Tree.Simple_set type 'a value = | Entity of 'a (* absolute path *) | Alias of Path.t and module_env = { vars : (string, unit value) Hashtbl.t ; types : (string, unit value) Hashtbl.t ; ctors : (string, unit value) Hashtbl.t ; fields : (string, unit value) Hashtbl.t ; modules : (string, module_env value) Hashtbl.t } let create_module_env () = { vars = Hashtbl.create 32 ; types = Hashtbl.create 32 ; ctors = Hashtbl.create 32 ; fields = Hashtbl.create 32 ; modules = Hashtbl.create 32 } ;; let find_name_local env name = let or_else optb = function None -> optb | v -> v in Hashtbl.find_opt env.ctors name |> or_else (Hashtbl.find_opt env.vars name) |> or_else (Hashtbl.find_opt env.fields name) |> or_else (Hashtbl.find_opt env.types name) ;; let find_module_local env name = Hashtbl.find_opt env.modules name (* find a provided path in env and returns canonical path and `module_env` if found *) let rec find_aux root_env path = (* same as `find_module_local`, but resolves the aliases *) (* returns `module_env` and canonical path if name is alias *) let find_module_env_local env name = match find_module_local env name with | Some (Entity v) -> Some (v, None) | Some (Alias path) -> (match find_aux root_env path with | Some (p, Some m) -> Some (m, Some p) | _ -> None) | None -> None in let rec aux env path resolved = match Path.extract path with | [head] -> let current_resolved = Path.join resolved (Path.single head) in (match find_module_env_local env head with | Some (e, Some p) -> Some (p, Some e) | Some (e, None) -> Some (current_resolved, Some e) | None -> (* not a module *) (match find_name_local env head with | Some (Entity ()) -> Some (current_resolved, None) | Some (Alias path) -> find_aux root_env path | None -> None)) | head :: tail -> (match find_module_env_local env head with | Some (e, None) -> aux e (Path.of_list tail) (Path.join resolved (Path.single head)) | Some (e, Some p) -> aux e (Path.of_list tail) p | _ -> None) | [] -> None in aux root_env path Path.root and find_module_opt env path = match find_aux env path with Some (_, Some m) -> Some m | _ -> None ;; let find_module env path = match find_module_opt env path with Some v -> v | None -> failwith "NotFound" ;; let canonical_opt env path = match find_aux env path with Some (p, _) -> Some p | None -> None ;; (* `canonical env path` returns canonical form of `path` in `env` *) let canonical env path = match canonical_opt env path with | Some p -> p | None -> failwith @@ Printf.sprintf "could not canonicalize path %s" (Path.string_of_path path) ;; (* `mem env path` checks if `path` is reachable in `env` *) let mem env path = match find_aux env path with Some _ -> true | None -> false (* conversion context *) (* TODO: Replace list with some other generic mutable set type *) type context = {primary : Path.t} let create_context () = {primary = Path.root} let absolute ctx path = Path.join ctx.primary path let absolute_name ctx name = absolute ctx (Path.single name) let resolve env ctx path = let candidates = Path.subpaths ctx.primary in let make_abs c = Path.join c path in match List.find_opt (mem env) (List.map make_abs candidates) with | Some p -> canonical env p | None -> failwith @@ Printf.sprintf "could not resolve path %s" (Path.string_of_path path) ;; (* convert a path to a pair of `module_env` and local name in returned env *) let to_env_and_name env path = match Path.init_last path with | [], name -> env, name | init, last -> let m = find_module env (Path.of_list init) in m, last ;; let add_local_with_ns env name v ns = let f = match ns with | NS.Var -> Hashtbl.add env.vars | NS.Ctor -> Hashtbl.add env.ctors | NS.Field -> Hashtbl.add env.fields | NS.Type -> Hashtbl.add env.types in f name v ;; let add_local_name_with_ns env name ns = add_local_with_ns env name (Entity ()) ns let add_local_alias_with_ns env name path ns = add_local_with_ns env name (Alias path) ns let add_with_ns env path ns = let m, name = to_env_and_name env path in add_local_name_with_ns m name ns ;; let mem_local_with_ns env name = function | NS.Var -> Hashtbl.mem env.vars name | NS.Ctor -> Hashtbl.mem env.ctors name | NS.Field -> Hashtbl.mem env.fields name | NS.Type -> Hashtbl.mem env.types name ;; let mem_with_ns env path ns = let m, name = to_env_and_name env path in mem_local_with_ns m name ns ;; let insert_alias env path target = let m, name = to_env_and_name env path in Hashtbl.add m.modules name (Alias target) ;; let iter_names f env = let apply ns k _ = f k ns in Hashtbl.iter (apply NS.Var) env.vars; Hashtbl.iter (apply NS.Ctor) env.ctors; Hashtbl.iter (apply NS.Field) env.fields; Hashtbl.iter (apply NS.Type) env.types ;; let alias_names from_path from to_ = let adder v ns = let abs = Path.join from_path (Path.single v) in add_local_alias_with_ns to_ v abs ns in iter_names adder from; let adder_module k _ = let abs = Path.join from_path (Path.single k) in Hashtbl.add to_.modules k (Alias abs) in Hashtbl.iter adder_module from.modules ;; let open_path env ctx path = let from = find_module env path in let to_ = find_module env ctx.primary in alias_names path from to_ ;; let in_new_module env ctx name f = let path = absolute_name ctx name in let m, name = to_env_and_name env path in Hashtbl.add m.modules name (Entity (create_module_env ())); f {primary = path} ;; (* expression-local environment *) (* TODO: Replace this with some other generic mutable set type *) type local_env = {mutable local_vars : string SS.t} let create_local_env () = {local_vars = SS.empty} (* the main conversion *) let apply_binds local_env x = function | NS.Var -> local_env.local_vars <- SS.add x local_env.local_vars; x | _ -> failwith "unexpected binding" ;; let apply_vars local_env env ctx path ns = let path = match ns, Path.extract path with (* locally-bound variables *) | NS.Var, [head] when SS.mem head local_env.local_vars -> path | _ -> resolve env ctx path in Path.string_of_path path ;; let convert_expr' local_env env ctx expr = Expr.apply_on_names (apply_vars local_env env ctx) (apply_binds local_env) expr ;; let convert_expr env ctx expr = convert_expr' (create_local_env ()) env ctx expr let convert_type_expr env ctx expr = let binds x _ = x in let vars x _ = let path = resolve env ctx x in Path.string_of_path path in TyExpr.apply_on_names vars binds expr ;; let convert_type_def env ctx defn = match defn with | Mod.Variant l -> let aux (ctor_name, expr_opt) = let ctor_name = absolute_name ctx ctor_name in add_with_ns env ctor_name NS.Ctor; let expr_opt = match expr_opt with Some e -> Some (convert_type_expr env ctx e) | None -> None in Path.string_of_path ctor_name, expr_opt in Mod.Variant (List.map aux l) | Mod.Record l -> let aux (is_mut, field_name, expr) = let field_name = absolute_name ctx field_name in add_with_ns env field_name NS.Field; let expr = convert_type_expr env ctx expr in is_mut, Path.string_of_path field_name, expr in Mod.Record (List.map aux l) | Mod.Alias expr -> let expr = convert_type_expr env ctx expr in Mod.Alias expr ;; let rec convert_defn env ctx defn = match defn with | Mod.LetAnd (is_rec, l) -> let local_env = create_local_env () in let binds is_local x ns = match is_local with | true -> apply_binds local_env x ns | false -> let path = absolute_name ctx x in add_with_ns env path ns; Path.string_of_path path in let l = Expr.apply_on_let_bindings (apply_vars local_env env ctx) binds is_rec l in [Mod.Definition (Mod.LetAnd (is_rec, l))] | Mod.TypeDef l -> let intros (tyvars, bind, def) = let bind = absolute_name ctx bind in add_with_ns env bind NS.Type; tyvars, bind, def in let aux (tyvars, bind, def) = let def = convert_type_def env ctx def in tyvars, Path.string_of_path bind, def in let l = List.map intros l |> List.map aux in [Mod.Definition (Mod.TypeDef l)] | Mod.Module (name, Mod.Path path) -> let t = absolute_name ctx name in let path = resolve env ctx path in insert_alias env t path; [] | Mod.Module (name, Mod.Struct l) -> let f ctx = List.map (convert_module_item env ctx) l |> List.flatten in in_new_module env ctx name f | Mod.Open path -> let path = resolve env ctx path in open_path env ctx path; [] | Mod.External (name, ty, decl) -> let path = absolute_name ctx name in add_with_ns env path NS.Var; let name = Path.string_of_path path in let ty = convert_type_expr env ctx ty in [Mod.Definition (Mod.External (name, ty, decl))] and convert_module_item env ctx = function | Mod.Expression expr -> [Mod.Expression (convert_expr env ctx expr)] | Mod.Definition defn -> convert_defn env ctx defn ;; let add_primitives env = let types = ["unit"; "int"; "bool"; "char"; "string"; "bytes"; "array"; "list"; "in_channel"] in let adder x = add_local_name_with_ns env x NS.Type in List.iter adder types ;; let f l = let env = create_module_env () in let ctx = create_context () in add_primitives env; List.map (convert_module_item env ctx) l |> List.flatten ;;
null
https://raw.githubusercontent.com/coord-e/mlml/ec34b1fe8766901fab6842b790267f32b77a2861/mlml/analysis/resolve.ml
ocaml
resolve paths and convert them into string TODO: use more clear ways to resolve paths absolute path find a provided path in env and returns canonical path and `module_env` if found same as `find_module_local`, but resolves the aliases returns `module_env` and canonical path if name is alias not a module `canonical env path` returns canonical form of `path` in `env` `mem env path` checks if `path` is reachable in `env` conversion context TODO: Replace list with some other generic mutable set type convert a path to a pair of `module_env` and local name in returned env expression-local environment TODO: Replace this with some other generic mutable set type the main conversion locally-bound variables
module Path = Tree.Path module Expr = Tree.Expression module Mod = Tree.Module module TyExpr = Tree.Type_expression module Pat = Tree.Pattern module NS = Tree.Namespace module SS = Tree.Simple_set type 'a value = | Entity of 'a | Alias of Path.t and module_env = { vars : (string, unit value) Hashtbl.t ; types : (string, unit value) Hashtbl.t ; ctors : (string, unit value) Hashtbl.t ; fields : (string, unit value) Hashtbl.t ; modules : (string, module_env value) Hashtbl.t } let create_module_env () = { vars = Hashtbl.create 32 ; types = Hashtbl.create 32 ; ctors = Hashtbl.create 32 ; fields = Hashtbl.create 32 ; modules = Hashtbl.create 32 } ;; let find_name_local env name = let or_else optb = function None -> optb | v -> v in Hashtbl.find_opt env.ctors name |> or_else (Hashtbl.find_opt env.vars name) |> or_else (Hashtbl.find_opt env.fields name) |> or_else (Hashtbl.find_opt env.types name) ;; let find_module_local env name = Hashtbl.find_opt env.modules name let rec find_aux root_env path = let find_module_env_local env name = match find_module_local env name with | Some (Entity v) -> Some (v, None) | Some (Alias path) -> (match find_aux root_env path with | Some (p, Some m) -> Some (m, Some p) | _ -> None) | None -> None in let rec aux env path resolved = match Path.extract path with | [head] -> let current_resolved = Path.join resolved (Path.single head) in (match find_module_env_local env head with | Some (e, Some p) -> Some (p, Some e) | Some (e, None) -> Some (current_resolved, Some e) | None -> (match find_name_local env head with | Some (Entity ()) -> Some (current_resolved, None) | Some (Alias path) -> find_aux root_env path | None -> None)) | head :: tail -> (match find_module_env_local env head with | Some (e, None) -> aux e (Path.of_list tail) (Path.join resolved (Path.single head)) | Some (e, Some p) -> aux e (Path.of_list tail) p | _ -> None) | [] -> None in aux root_env path Path.root and find_module_opt env path = match find_aux env path with Some (_, Some m) -> Some m | _ -> None ;; let find_module env path = match find_module_opt env path with Some v -> v | None -> failwith "NotFound" ;; let canonical_opt env path = match find_aux env path with Some (p, _) -> Some p | None -> None ;; let canonical env path = match canonical_opt env path with | Some p -> p | None -> failwith @@ Printf.sprintf "could not canonicalize path %s" (Path.string_of_path path) ;; let mem env path = match find_aux env path with Some _ -> true | None -> false type context = {primary : Path.t} let create_context () = {primary = Path.root} let absolute ctx path = Path.join ctx.primary path let absolute_name ctx name = absolute ctx (Path.single name) let resolve env ctx path = let candidates = Path.subpaths ctx.primary in let make_abs c = Path.join c path in match List.find_opt (mem env) (List.map make_abs candidates) with | Some p -> canonical env p | None -> failwith @@ Printf.sprintf "could not resolve path %s" (Path.string_of_path path) ;; let to_env_and_name env path = match Path.init_last path with | [], name -> env, name | init, last -> let m = find_module env (Path.of_list init) in m, last ;; let add_local_with_ns env name v ns = let f = match ns with | NS.Var -> Hashtbl.add env.vars | NS.Ctor -> Hashtbl.add env.ctors | NS.Field -> Hashtbl.add env.fields | NS.Type -> Hashtbl.add env.types in f name v ;; let add_local_name_with_ns env name ns = add_local_with_ns env name (Entity ()) ns let add_local_alias_with_ns env name path ns = add_local_with_ns env name (Alias path) ns let add_with_ns env path ns = let m, name = to_env_and_name env path in add_local_name_with_ns m name ns ;; let mem_local_with_ns env name = function | NS.Var -> Hashtbl.mem env.vars name | NS.Ctor -> Hashtbl.mem env.ctors name | NS.Field -> Hashtbl.mem env.fields name | NS.Type -> Hashtbl.mem env.types name ;; let mem_with_ns env path ns = let m, name = to_env_and_name env path in mem_local_with_ns m name ns ;; let insert_alias env path target = let m, name = to_env_and_name env path in Hashtbl.add m.modules name (Alias target) ;; let iter_names f env = let apply ns k _ = f k ns in Hashtbl.iter (apply NS.Var) env.vars; Hashtbl.iter (apply NS.Ctor) env.ctors; Hashtbl.iter (apply NS.Field) env.fields; Hashtbl.iter (apply NS.Type) env.types ;; let alias_names from_path from to_ = let adder v ns = let abs = Path.join from_path (Path.single v) in add_local_alias_with_ns to_ v abs ns in iter_names adder from; let adder_module k _ = let abs = Path.join from_path (Path.single k) in Hashtbl.add to_.modules k (Alias abs) in Hashtbl.iter adder_module from.modules ;; let open_path env ctx path = let from = find_module env path in let to_ = find_module env ctx.primary in alias_names path from to_ ;; let in_new_module env ctx name f = let path = absolute_name ctx name in let m, name = to_env_and_name env path in Hashtbl.add m.modules name (Entity (create_module_env ())); f {primary = path} ;; type local_env = {mutable local_vars : string SS.t} let create_local_env () = {local_vars = SS.empty} let apply_binds local_env x = function | NS.Var -> local_env.local_vars <- SS.add x local_env.local_vars; x | _ -> failwith "unexpected binding" ;; let apply_vars local_env env ctx path ns = let path = match ns, Path.extract path with | NS.Var, [head] when SS.mem head local_env.local_vars -> path | _ -> resolve env ctx path in Path.string_of_path path ;; let convert_expr' local_env env ctx expr = Expr.apply_on_names (apply_vars local_env env ctx) (apply_binds local_env) expr ;; let convert_expr env ctx expr = convert_expr' (create_local_env ()) env ctx expr let convert_type_expr env ctx expr = let binds x _ = x in let vars x _ = let path = resolve env ctx x in Path.string_of_path path in TyExpr.apply_on_names vars binds expr ;; let convert_type_def env ctx defn = match defn with | Mod.Variant l -> let aux (ctor_name, expr_opt) = let ctor_name = absolute_name ctx ctor_name in add_with_ns env ctor_name NS.Ctor; let expr_opt = match expr_opt with Some e -> Some (convert_type_expr env ctx e) | None -> None in Path.string_of_path ctor_name, expr_opt in Mod.Variant (List.map aux l) | Mod.Record l -> let aux (is_mut, field_name, expr) = let field_name = absolute_name ctx field_name in add_with_ns env field_name NS.Field; let expr = convert_type_expr env ctx expr in is_mut, Path.string_of_path field_name, expr in Mod.Record (List.map aux l) | Mod.Alias expr -> let expr = convert_type_expr env ctx expr in Mod.Alias expr ;; let rec convert_defn env ctx defn = match defn with | Mod.LetAnd (is_rec, l) -> let local_env = create_local_env () in let binds is_local x ns = match is_local with | true -> apply_binds local_env x ns | false -> let path = absolute_name ctx x in add_with_ns env path ns; Path.string_of_path path in let l = Expr.apply_on_let_bindings (apply_vars local_env env ctx) binds is_rec l in [Mod.Definition (Mod.LetAnd (is_rec, l))] | Mod.TypeDef l -> let intros (tyvars, bind, def) = let bind = absolute_name ctx bind in add_with_ns env bind NS.Type; tyvars, bind, def in let aux (tyvars, bind, def) = let def = convert_type_def env ctx def in tyvars, Path.string_of_path bind, def in let l = List.map intros l |> List.map aux in [Mod.Definition (Mod.TypeDef l)] | Mod.Module (name, Mod.Path path) -> let t = absolute_name ctx name in let path = resolve env ctx path in insert_alias env t path; [] | Mod.Module (name, Mod.Struct l) -> let f ctx = List.map (convert_module_item env ctx) l |> List.flatten in in_new_module env ctx name f | Mod.Open path -> let path = resolve env ctx path in open_path env ctx path; [] | Mod.External (name, ty, decl) -> let path = absolute_name ctx name in add_with_ns env path NS.Var; let name = Path.string_of_path path in let ty = convert_type_expr env ctx ty in [Mod.Definition (Mod.External (name, ty, decl))] and convert_module_item env ctx = function | Mod.Expression expr -> [Mod.Expression (convert_expr env ctx expr)] | Mod.Definition defn -> convert_defn env ctx defn ;; let add_primitives env = let types = ["unit"; "int"; "bool"; "char"; "string"; "bytes"; "array"; "list"; "in_channel"] in let adder x = add_local_name_with_ns env x NS.Type in List.iter adder types ;; let f l = let env = create_module_env () in let ctx = create_context () in add_primitives env; List.map (convert_module_item env ctx) l |> List.flatten ;;
011dc2e32a9d28f0bc86a9dd738a4f4389a9daac60138b98de62cf7f1226f311
robert-strandh/SICL
packages.lisp
(cl:in-package #:common-lisp-user) (defpackage #:sicl-call-site-manager (:use #:common-lisp) (:local-nicknames (#:env #:sicl-environment)) (:export #:create-trampoline-snippet))
null
https://raw.githubusercontent.com/robert-strandh/SICL/59d8fa94811a0eac4ac747333ad9ecd976652c41/Code/Call-site-manager/packages.lisp
lisp
(cl:in-package #:common-lisp-user) (defpackage #:sicl-call-site-manager (:use #:common-lisp) (:local-nicknames (#:env #:sicl-environment)) (:export #:create-trampoline-snippet))
b1b73c9d990d5814e69d4d2e5ce2b573edc834c6ed2fc52e0c0c266b972323d3
unclebob/spacewar
protocols.cljc
(ns spacewar.ui.protocols #?(:cljs (:refer-clojure :exclude [clone])) (:require [clojure.spec.alpha :as s])) ;update-state returns [new-drawable [events]] (defprotocol Drawable (draw [this]) (setup [this]) (update-state [this world]) (get-state [this]) (clone [this state])) (s/def ::elements (s/coll-of keyword?)) (s/def ::drawable-state (s/keys :opt-un [::elements])) (s/def ::event keyword?) (s/def ::event-map (s/keys :req-un [::event])) (s/def ::updated-elements-and-events (s/tuple ::drawable-state (s/coll-of ::event-map))) (s/def ::world map?) (s/def ::game-state (s/keys :req-un [::world])) (defn update-elements [container-state world] ;{:pre [ ; (s/valid? ::drawable-state container-state) ; ] ; :post [ ; (s/valid? ::updated-elements-and-events %) ; ]} (let [elements (:elements container-state)] (if (nil? elements) [container-state []] (loop [elements elements key-vals [] cum-events []] (if (empty? elements) [(apply assoc container-state (flatten key-vals)) (flatten cum-events)] (let [element-tag (first elements) element (element-tag container-state) [updated-drawable events] (update-state element world)] (recur (rest elements) (conj key-vals [element-tag updated-drawable]) (conj cum-events events)))))))) (defn draw-elements [state] (doseq [e (:elements state)] (draw (e state)))) (defn pack-update ([new-drawable] [new-drawable []]) ([new-drawable event] (if (some? event) [new-drawable [event]] [new-drawable []]))) (defn change-element [container element key value] (let [drawable-element (element container) element-state (get-state drawable-element)] (assoc container element (clone drawable-element (assoc element-state key value))))) (defn change-elements [container changes] (loop [container container changes changes] (if (empty? changes) container (let [[element key value] (first changes)] (recur (change-element container element key value) (rest changes))))))
null
https://raw.githubusercontent.com/unclebob/spacewar/71c3195b050c4fdb7e643f53556ab580d70f27ba/src/spacewar/ui/protocols.cljc
clojure
update-state returns [new-drawable [events]] {:pre [ (s/valid? ::drawable-state container-state) ] :post [ (s/valid? ::updated-elements-and-events %) ]}
(ns spacewar.ui.protocols #?(:cljs (:refer-clojure :exclude [clone])) (:require [clojure.spec.alpha :as s])) (defprotocol Drawable (draw [this]) (setup [this]) (update-state [this world]) (get-state [this]) (clone [this state])) (s/def ::elements (s/coll-of keyword?)) (s/def ::drawable-state (s/keys :opt-un [::elements])) (s/def ::event keyword?) (s/def ::event-map (s/keys :req-un [::event])) (s/def ::updated-elements-and-events (s/tuple ::drawable-state (s/coll-of ::event-map))) (s/def ::world map?) (s/def ::game-state (s/keys :req-un [::world])) (defn update-elements [container-state world] (let [elements (:elements container-state)] (if (nil? elements) [container-state []] (loop [elements elements key-vals [] cum-events []] (if (empty? elements) [(apply assoc container-state (flatten key-vals)) (flatten cum-events)] (let [element-tag (first elements) element (element-tag container-state) [updated-drawable events] (update-state element world)] (recur (rest elements) (conj key-vals [element-tag updated-drawable]) (conj cum-events events)))))))) (defn draw-elements [state] (doseq [e (:elements state)] (draw (e state)))) (defn pack-update ([new-drawable] [new-drawable []]) ([new-drawable event] (if (some? event) [new-drawable [event]] [new-drawable []]))) (defn change-element [container element key value] (let [drawable-element (element container) element-state (get-state drawable-element)] (assoc container element (clone drawable-element (assoc element-state key value))))) (defn change-elements [container changes] (loop [container container changes changes] (if (empty? changes) container (let [[element key value] (first changes)] (recur (change-element container element key value) (rest changes))))))
ea19c3b126c8c2036371a89bdaee05be1f03cfbc739a38262268886143f8b109
juxt/bolt
cookie_session_store.clj
;; TODO: This is misnamed. The cookie only contains a UUID, which keys ;; into a token store containing the material. (ns bolt.session.cookie-session-store (:require [clojure.tools.logging :refer :all] [com.stuartsierra.component :refer (using)] [bolt.session :refer (session)] [bolt.session.protocols :refer (SessionStore)] [bolt.authentication.protocols :refer (RequestAuthenticator)] [bolt.token-store :refer (get-token-by-id merge-token! create-token! purge-token!)] [ring.middleware.cookies :refer (cookies-request cookies-response)] [schema.core :as s] [plumbing.core :refer (<-)])) (defn ->cookie [session] {:value (:bolt/token-id session) :expires (.toGMTString (doto (new java.util.Date) (.setTime (.getTime (:bolt/expiry session))))) :path "/"}) ;(doto (new java.util.Date) (.setTime (.getTime (:c {:c (new java.util.Date)})))) (def delete-cookie {:value "" :expires (.toGMTString (java.util.Date. 70 0 1)) :path "/"}) (defn cookies-response-with-session [response id-cookie session] ;; Use of cookies-response mean it is non-destructive - existing ;; cookies are preserved (but existing :cookies entries are not) (cookies-response (merge-with merge response {:cookies {id-cookie (->cookie session)}}))) This record satisfies SessionStore , indexed by a specific ;; cookie-id. This design allows us to encapsulate the cookie-id, rather ;; than have to pass it through numerous function calls. (defrecord CookieSessionStore [cookie-id token-store] SessionStore (session [component request] In case the underlying token store accepts nils , we should avoid ;; retrieving a nil-indexed token, so we wrap in a 'when-let'. (when-let [tokid (-> request cookies-request :cookies (get cookie-id) :value)] (get-token-by-id token-store tokid))) (assoc-session-data! [component request m] (when-let [tokid (-> request cookies-request :cookies (get cookie-id) :value)] (merge-token! token-store tokid m))) (respond-with-new-session! [component request data response] TODO Create a HMAC'd identifier , not just a random UUID that ;; could be predicted and therefore allow session forgery. (let [id (str (java.util.UUID/randomUUID)) token (create-token! token-store id data)] (debugf "Creating new session (%s) cookie %s tied to token %s" (:token-type token-store) id token) (cookies-response-with-session response cookie-id token))) (respond-close-session! [component request response] (when-let [tokid (-> request cookies-request :cookies (get cookie-id) :value)] (purge-token! token-store tokid)) (cookies-response (merge-with merge response {:cookies {cookie-id delete-cookie}}))) RequestAuthenticator (authenticate [component req] (session component req))) (def new-cookie-session-store-schema {:cookie-id s/Str}) (defn new-cookie-session-store [& {:as opts}] (->> opts (merge {:cookie-id "session-id"}) (s/validate new-cookie-session-store-schema) map->CookieSessionStore (<- (using [:token-store]))))
null
https://raw.githubusercontent.com/juxt/bolt/f77be416f82c1ca19d5dc20a15942375edc9b740/src/bolt/session/cookie_session_store.clj
clojure
TODO: This is misnamed. The cookie only contains a UUID, which keys into a token store containing the material. (doto (new java.util.Date) (.setTime (.getTime (:c {:c (new java.util.Date)})))) Use of cookies-response mean it is non-destructive - existing cookies are preserved (but existing :cookies entries are not) cookie-id. This design allows us to encapsulate the cookie-id, rather than have to pass it through numerous function calls. retrieving a nil-indexed token, so we wrap in a 'when-let'. could be predicted and therefore allow session forgery.
(ns bolt.session.cookie-session-store (:require [clojure.tools.logging :refer :all] [com.stuartsierra.component :refer (using)] [bolt.session :refer (session)] [bolt.session.protocols :refer (SessionStore)] [bolt.authentication.protocols :refer (RequestAuthenticator)] [bolt.token-store :refer (get-token-by-id merge-token! create-token! purge-token!)] [ring.middleware.cookies :refer (cookies-request cookies-response)] [schema.core :as s] [plumbing.core :refer (<-)])) (defn ->cookie [session] {:value (:bolt/token-id session) :expires (.toGMTString (doto (new java.util.Date) (.setTime (.getTime (:bolt/expiry session))))) :path "/"}) (def delete-cookie {:value "" :expires (.toGMTString (java.util.Date. 70 0 1)) :path "/"}) (defn cookies-response-with-session [response id-cookie session] (cookies-response (merge-with merge response {:cookies {id-cookie (->cookie session)}}))) This record satisfies SessionStore , indexed by a specific (defrecord CookieSessionStore [cookie-id token-store] SessionStore (session [component request] In case the underlying token store accepts nils , we should avoid (when-let [tokid (-> request cookies-request :cookies (get cookie-id) :value)] (get-token-by-id token-store tokid))) (assoc-session-data! [component request m] (when-let [tokid (-> request cookies-request :cookies (get cookie-id) :value)] (merge-token! token-store tokid m))) (respond-with-new-session! [component request data response] TODO Create a HMAC'd identifier , not just a random UUID that (let [id (str (java.util.UUID/randomUUID)) token (create-token! token-store id data)] (debugf "Creating new session (%s) cookie %s tied to token %s" (:token-type token-store) id token) (cookies-response-with-session response cookie-id token))) (respond-close-session! [component request response] (when-let [tokid (-> request cookies-request :cookies (get cookie-id) :value)] (purge-token! token-store tokid)) (cookies-response (merge-with merge response {:cookies {cookie-id delete-cookie}}))) RequestAuthenticator (authenticate [component req] (session component req))) (def new-cookie-session-store-schema {:cookie-id s/Str}) (defn new-cookie-session-store [& {:as opts}] (->> opts (merge {:cookie-id "session-id"}) (s/validate new-cookie-session-store-schema) map->CookieSessionStore (<- (using [:token-store]))))
737cd9b18ce1ccaea373132d175bce45420a26bd872874fe8217cba29fcdafab
mirage/mirage-vnetif
vnetif.mli
* Copyright ( c ) 2015 < > * Copyright ( c ) 2011 - 2013 Anil Madhavapeddy < > * * Permission to use , copy , modify , and distribute this software for any * purpose with or without fee is hereby granted , provided that the above * copyright notice and this permission notice appear in all copies . * * THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN * ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE . * Copyright (c) 2015 Magnus Skjegstad <> * Copyright (c) 2011-2013 Anil Madhavapeddy <> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. *) open Mirage_net module type BACKEND = sig type 'a io = 'a Lwt.t type buffer = Cstruct.t type id = int type macaddr = Macaddr.t type t val register : t -> (id, Net.error) result val unregister : t -> id -> unit io val mac : t -> id -> macaddr val write : t -> id -> size:int -> (buffer -> int) -> (unit, Net.error) result io val set_listen_fn : t -> id -> (buffer -> unit io) -> unit val unregister_and_flush : t -> id -> unit io end (** Dummy interface for software bridge. *) module Make(B : BACKEND) : sig include Mirage_net.S val connect : ?size_limit:int -> ?flush_on_disconnect:bool -> ?monitor_fn:(B.buffer -> unit Lwt.t) -> ?unlock_on_listen:Lwt_mutex.t -> B.t -> t Lwt.t val disconnect : t -> unit Lwt.t end
null
https://raw.githubusercontent.com/mirage/mirage-vnetif/e33e44c987289b31571dbb5f836d43a3a6485120/src/vnetif/vnetif.mli
ocaml
* Dummy interface for software bridge.
* Copyright ( c ) 2015 < > * Copyright ( c ) 2011 - 2013 Anil Madhavapeddy < > * * Permission to use , copy , modify , and distribute this software for any * purpose with or without fee is hereby granted , provided that the above * copyright notice and this permission notice appear in all copies . * * THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN * ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE . * Copyright (c) 2015 Magnus Skjegstad <> * Copyright (c) 2011-2013 Anil Madhavapeddy <> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. *) open Mirage_net module type BACKEND = sig type 'a io = 'a Lwt.t type buffer = Cstruct.t type id = int type macaddr = Macaddr.t type t val register : t -> (id, Net.error) result val unregister : t -> id -> unit io val mac : t -> id -> macaddr val write : t -> id -> size:int -> (buffer -> int) -> (unit, Net.error) result io val set_listen_fn : t -> id -> (buffer -> unit io) -> unit val unregister_and_flush : t -> id -> unit io end module Make(B : BACKEND) : sig include Mirage_net.S val connect : ?size_limit:int -> ?flush_on_disconnect:bool -> ?monitor_fn:(B.buffer -> unit Lwt.t) -> ?unlock_on_listen:Lwt_mutex.t -> B.t -> t Lwt.t val disconnect : t -> unit Lwt.t end
29048970df8ca5fbd44152231acd0d94f1448b6165ba41e92fe07151aacf5e63
hlprmnky/ion-appsync-example
handlers.cljs
(ns pages.handlers (:require [cljs.pprint :refer [pprint]] [goog.string :as gstring] [goog.string.format] [goog.crypt.base64 :as base64] [clojure.string :as str] ["request" :as req] ["request-promise-native" :as reqp] [pages.views :as views])) (defn ->clj "parse a json string into a cljs map" [json-string] (js->clj (js/JSON.parse json-string) :keywordize-keys true)) (defn -js->clj+ "For cases when built-in js->clj doesn't work. Source: " [x] (into {} (for [k (js-keys x)] [k (aget x k)]))) (defn requestp "send a request returning a promise" [url-or-opts] (reqp (clj->js url-or-opts))) (defn cognito-config [event] (let [event (js->clj event :keywordize-keys true) env (-js->clj+ (.-env js/process)) cognito-domain (get env "CognitoDomain") api-id (get-in event [:requestContext :apiId]) api-stage (get-in event [:requestContext :stage]) region (get env "AWS_REGION")] {:aws-region region :api-server (gstring/format "-api.%s.amazonaws.com/%s" api-id region api-stage) :api-stage api-stage :cognito-domain cognito-domain :cognito-server (gstring/format "" cognito-domain region) :cognito-pool (get env "CognitoPool") TODO can IAM provide access to the service without the secret in the env ? :client-id (get env "CognitoClientId") :client-secret (get env "CognitoClientSecret")})) (defn app-url [{:keys [api-server] :as config}] (str api-server "/app")) (defn home-url [{:keys [api-server]}] (str api-server "/home")) (defn login-url [{:keys [client-id cognito-server] :as config}] (gstring/format "%s/login?client_id=%s&response_type=code&redirect_uri=%s" cognito-server client-id (app-url config))) (defn logout-url [{:keys [client-id cognito-server] :as config}] (gstring/format "%s/logout?client_id=%s&logout_uri=%s" cognito-server client-id (home-url config))) (defn home-page [event context callback] (let [markup (views/home {:urls {:login (login-url (cognito-config event))}})] (callback nil (clj->js {:body markup :statusCode 200 :headers {:Content-Type "text/html"}})))) (defn jwt-data "checks structure and returns parsed data from a Cognito JWT token" [token] (let [parts (str/split token #"\.")] (when (not= 3 (count parts)) (throw (ex-info "invalid JWT token" {:count (count parts)}))) (let [[header payload signature] parts] {:header (-> header base64/decodeString ->clj) :payload (-> payload base64/decodeString ->clj) :signature signature}))) -center/decode-verify-cognito-json-token/ ; -jsonwebtoken (defn validate-token ; TODO !!!! [token-data] (let [])) (defn app-page [event context callback] (let [event-map (js->clj event :keywordize-keys true) auth-code (get-in event-map [:queryStringParameters :code]) {:keys [aws-region cognito-pool api-stage client-id client-secret cognito-domain cognito-server] :as config} (cognito-config event) token-request {:method "POST" :url (str cognito-server "/oauth2/token/") ; trailing / is important! :headers {:Authorization (str "Basic " (base64/encodeString (str client-id ":" client-secret)))} form data also sets Content - Type = application / x - www - form - urlencoded :form {:grant_type "authorization_code" :client_id client-id :code auth-code :redirect_uri (app-url config)}} env (-js->clj+ (.-env js/process))] (-> (requestp token-request) (.then (fn [body] (pprint (str "stage: " api-stage)) (let [{:keys [access_token refresh_token]} (->clj body) token-data (jwt-data access_token) markup (views/app (cond-> {:username (get-in token-data [:payload :username]) :token token-data :token-row access_token :stage api-stage :urls {:logout (logout-url config)}} ; only provide env data when in "dev" stage (= "dev" api-stage) (merge {:event event :context context :env env})))] (validate-token token-data) (callback nil (clj->js {:body markup :statusCode 200 :headers {:Content-Type "text/html"}}))))) (.catch (fn [error] ;(js/console.log error) ;(js/console.log (.-body (.-response error))) (callback error (clj->js {:body (views/error {}) :statusCode 500 :headers {:Content-Type "text/html"}})))))))
null
https://raw.githubusercontent.com/hlprmnky/ion-appsync-example/76a3dcfcf2d09c066a8d4dac7f1e930f79fb1237/src-pages/pages/handlers.cljs
clojure
-jsonwebtoken TODO !!!! trailing / is important! only provide env data when in "dev" stage (js/console.log error) (js/console.log (.-body (.-response error)))
(ns pages.handlers (:require [cljs.pprint :refer [pprint]] [goog.string :as gstring] [goog.string.format] [goog.crypt.base64 :as base64] [clojure.string :as str] ["request" :as req] ["request-promise-native" :as reqp] [pages.views :as views])) (defn ->clj "parse a json string into a cljs map" [json-string] (js->clj (js/JSON.parse json-string) :keywordize-keys true)) (defn -js->clj+ "For cases when built-in js->clj doesn't work. Source: " [x] (into {} (for [k (js-keys x)] [k (aget x k)]))) (defn requestp "send a request returning a promise" [url-or-opts] (reqp (clj->js url-or-opts))) (defn cognito-config [event] (let [event (js->clj event :keywordize-keys true) env (-js->clj+ (.-env js/process)) cognito-domain (get env "CognitoDomain") api-id (get-in event [:requestContext :apiId]) api-stage (get-in event [:requestContext :stage]) region (get env "AWS_REGION")] {:aws-region region :api-server (gstring/format "-api.%s.amazonaws.com/%s" api-id region api-stage) :api-stage api-stage :cognito-domain cognito-domain :cognito-server (gstring/format "" cognito-domain region) :cognito-pool (get env "CognitoPool") TODO can IAM provide access to the service without the secret in the env ? :client-id (get env "CognitoClientId") :client-secret (get env "CognitoClientSecret")})) (defn app-url [{:keys [api-server] :as config}] (str api-server "/app")) (defn home-url [{:keys [api-server]}] (str api-server "/home")) (defn login-url [{:keys [client-id cognito-server] :as config}] (gstring/format "%s/login?client_id=%s&response_type=code&redirect_uri=%s" cognito-server client-id (app-url config))) (defn logout-url [{:keys [client-id cognito-server] :as config}] (gstring/format "%s/logout?client_id=%s&logout_uri=%s" cognito-server client-id (home-url config))) (defn home-page [event context callback] (let [markup (views/home {:urls {:login (login-url (cognito-config event))}})] (callback nil (clj->js {:body markup :statusCode 200 :headers {:Content-Type "text/html"}})))) (defn jwt-data "checks structure and returns parsed data from a Cognito JWT token" [token] (let [parts (str/split token #"\.")] (when (not= 3 (count parts)) (throw (ex-info "invalid JWT token" {:count (count parts)}))) (let [[header payload signature] parts] {:header (-> header base64/decodeString ->clj) :payload (-> payload base64/decodeString ->clj) :signature signature}))) -center/decode-verify-cognito-json-token/ [token-data] (let [])) (defn app-page [event context callback] (let [event-map (js->clj event :keywordize-keys true) auth-code (get-in event-map [:queryStringParameters :code]) {:keys [aws-region cognito-pool api-stage client-id client-secret cognito-domain cognito-server] :as config} (cognito-config event) token-request {:method "POST" :headers {:Authorization (str "Basic " (base64/encodeString (str client-id ":" client-secret)))} form data also sets Content - Type = application / x - www - form - urlencoded :form {:grant_type "authorization_code" :client_id client-id :code auth-code :redirect_uri (app-url config)}} env (-js->clj+ (.-env js/process))] (-> (requestp token-request) (.then (fn [body] (pprint (str "stage: " api-stage)) (let [{:keys [access_token refresh_token]} (->clj body) token-data (jwt-data access_token) markup (views/app (cond-> {:username (get-in token-data [:payload :username]) :token token-data :token-row access_token :stage api-stage :urls {:logout (logout-url config)}} (= "dev" api-stage) (merge {:event event :context context :env env})))] (validate-token token-data) (callback nil (clj->js {:body markup :statusCode 200 :headers {:Content-Type "text/html"}}))))) (.catch (fn [error] (callback error (clj->js {:body (views/error {}) :statusCode 500 :headers {:Content-Type "text/html"}})))))))
56b51e610806caa09d8a0e3bdd108ee5f79a66dab3af761b3d1fae167c698c20
hjwylde/werewolf
Engine.hs
| Module : Game . Werewolf . Engine Description : Engine functions . Copyright : ( c ) , 2016 License : : Engine functions . Module : Game.Werewolf.Engine Description : Engine functions. Copyright : (c) Henry J. Wylde, 2016 License : BSD3 Maintainer : Engine functions. -} {-# LANGUAGE FlexibleContexts #-} # LANGUAGE MultiParamTypeClasses # module Game.Werewolf.Engine ( -- * Loop checkStage, checkGameOver, ) where import Control.Lens.Extra import Control.Monad.Except import Control.Monad.Extra import Control.Monad.Random import Control.Monad.State import Control.Monad.Writer import Data.List.Extra import qualified Data.Map as Map import Data.Maybe TODO ( hjw ): remove Message . Command import Game.Werewolf.Game hiding (hasAnyoneWon, hasEveryoneLost) import Game.Werewolf.Message.Command import Game.Werewolf.Message.Engine import Game.Werewolf.Player import Game.Werewolf.Response import Game.Werewolf.Role hiding (name) import Game.Werewolf.Util import Prelude hiding (round) checkStage :: (MonadRandom m, MonadState Game m, MonadWriter [Message] m) => m () checkStage = do game <- get checkBoots >> checkStage' game' <- get when (game /= game') checkStage checkBoots :: (MonadState Game m, MonadWriter [Message] m) => m () checkBoots = do alivePlayerCount <- length . toListOf (players . traverse . alive) <$> get booteeNames <- uses boots $ Map.keys . Map.filter (\voters -> length voters > alivePlayerCount `div` 2) bootees <- mapM (findPlayerBy_ name) booteeNames forM_ (filter (is alive) bootees) $ \bootee -> do tell . (:[]) . playerBootedMessage bootee =<< get removePlayer (bootee ^. name) checkStage' :: (MonadRandom m, MonadState Game m, MonadWriter [Message] m) => m () checkStage' = use stage >>= \stage' -> case stage' of DruidsTurn -> do druid <- findPlayerBy_ role druidRole players' <- filter (isn't alphaWolf) <$> getAdjacentAlivePlayers (druid ^. name) when (has werewolves players' || has lycans players') $ tell [ferinaGruntsMessage] advanceStage GameOver -> return () HuntersTurn1 -> whenM (use hunterRetaliated) advanceStage HuntersTurn2 -> whenM (use hunterRetaliated) advanceStage Lynching -> do unlessM (Map.null <$> use votes) $ lynchVotee =<< preuse votee chosenVoters .= [] votes .= Map.empty advanceStage NecromancersTurn -> do whenM (hasuse $ players . necromancers . dead) advanceStage whenM (use deadRaised) advanceStage whenM (use passed) advanceStage OraclesTurn -> do whenM (hasuse $ players . oracles . dead) advanceStage whenM (isJust <$> use divine) advanceStage OrphansTurn -> do whenM (hasuse $ players . orphans . dead) advanceStage whenM (isJust <$> use roleModel) advanceStage ProtectorsTurn -> do whenM (hasuse $ players . protectors . dead) advanceStage whenM (isJust <$> use protect) advanceStage ScapegoatsTurn -> unlessM (use scapegoatBlamed) $ do game <- get tell [scapegoatChoseAllowedVotersMessage game] advanceStage SeersTurn -> do whenM (hasuse $ players . seers . dead) advanceStage whenM (isJust <$> use see) advanceStage Sunrise -> do round += 1 devourVotee =<< preuse votee whenJustM (use poison) $ \targetName -> do target <- findPlayerBy_ name targetName killPlayer targetName tell . (:[]) . playerPoisonedMessage target =<< get whenJustM (preuse $ players . seers . alive) $ \seer -> do target <- use see >>= findPlayerBy_ name . fromJust when (is alive target) $ tell [playerSeenMessage (seer ^. name) target] whenJustM (preuse $ players . oracles . alive) $ \oracle -> do target <- use divine >>= findPlayerBy_ name . fromJust when (is alive target) $ tell [playerDivinedMessage (oracle ^. name) target] divine .= Nothing poison .= Nothing protect .= Nothing see .= Nothing votes .= Map.empty advanceStage Sunset -> do whenJustM (use roleModel) $ \roleModelsName -> do orphan <- findPlayerBy_ role orphanRole whenM (isPlayerDead roleModelsName &&^ return (is alive orphan) &&^ return (is villager orphan)) $ do setPlayerAllegiance (orphan ^. name) Werewolves tell . orphanJoinedPackMessages (orphan ^. name) =<< get advanceStage VillageDrunksTurn -> do randomAllegiance <- getRandomAllegiance players . villageDrunks . role . allegiance .= randomAllegiance villageDrunk <- findPlayerBy_ role villageDrunkRole if is villager villageDrunk then tell [villageDrunkJoinedVillageMessage $ villageDrunk ^. name] else tell . villageDrunkJoinedPackMessages (villageDrunk ^. name) =<< get advanceStage VillagesTurn -> whenM (hasn'tuse pendingVoters) $ do uses votes Map.toList >>= mapM_ (\(voterName, voteeName) -> do voter <- findPlayerBy_ name voterName votee <- findPlayerBy_ name voteeName tell [playerMadeLynchVoteMessage Nothing voter votee] ) advanceStage WerewolvesTurn -> whenM (hasn'tuse pendingVoters) $ do whenM (liftM2 (==) (use protect) (preuses votee $ view name)) $ votes .= Map.empty advanceStage WitchsTurn -> do whenM (hasuse $ players . witches . dead) advanceStage whenM (use healUsed &&^ use poisonUsed) advanceStage whenM (use passed) advanceStage lynchVotee :: (MonadState Game m, MonadWriter [Message] m) => Maybe Player -> m () lynchVotee (Just votee) | is jester votee = do jesterRevealed .= True tell . (:[]) . jesterLynchedMessage =<< get | is fallenAngel votee = do fallenAngelLynched .= True tell . (:[]) . playerLynchedMessage votee =<< get | is saint votee = do tell . (:[]) . playerLynchedMessage votee =<< get killPlayer (votee ^. name) voterNames <- uses votes (filter (/= votee ^. name) . Map.keys . Map.filter (== votee ^. name)) forM_ voterNames killPlayer voters <- mapM (findPlayerBy_ name) voterNames tell . (:[]) . saintLynchedMessage voters =<< get | is werewolf votee = do tell . (:[]) . werewolfLynchedMessage votee =<< get killPlayer (votee ^. name) | otherwise = do tell . (:[]) . playerLynchedMessage votee =<< get killPlayer (votee ^. name) lynchVotee _ = preuse (players . scapegoats . alive) >>= \mScapegoat -> case mScapegoat of Just scapegoat -> do scapegoatBlamed .= True killPlayer (scapegoat ^. name) tell . (:[]) . scapegoatLynchedMessage =<< get _ -> tell [noPlayerLynchedMessage] devourVotee :: (MonadState Game m, MonadWriter [Message] m) => Maybe Player -> m () devourVotee Nothing = tell [noPlayerDevouredMessage] devourVotee (Just votee) = do killPlayer (votee ^. name) tell . (:[]) . playerDevouredMessage votee =<< get when (is medusa votee) . whenJustM (getFirstAdjacentAliveWerewolf $ votee ^. name) $ \werewolf -> do killPlayer (werewolf ^. name) tell . (:[]) . playerTurnedToStoneMessage werewolf =<< get advanceStage :: (MonadState Game m, MonadWriter [Message] m) => m () advanceStage = do game <- get nextStage <- ifM (hasAnyoneWon ||^ hasEveryoneLost) (return GameOver) (return . head $ filter (stageAvailable game) (drop1 $ dropWhile (game ^. stage /=) stageCycle)) stage .= nextStage boots .= Map.empty passed .= False tell . stageMessages =<< get checkGameOver :: (MonadState Game m, MonadWriter [Message] m) => m () checkGameOver = whenM (hasAnyoneWon ||^ hasEveryoneLost) $ stage .= GameOver >> get >>= tell . gameOverMessages
null
https://raw.githubusercontent.com/hjwylde/werewolf/d22a941120a282127fc3e2db52e7c86b5d238344/app/Game/Werewolf/Engine.hs
haskell
# LANGUAGE FlexibleContexts # * Loop
| Module : Game . Werewolf . Engine Description : Engine functions . Copyright : ( c ) , 2016 License : : Engine functions . Module : Game.Werewolf.Engine Description : Engine functions. Copyright : (c) Henry J. Wylde, 2016 License : BSD3 Maintainer : Engine functions. -} # LANGUAGE MultiParamTypeClasses # module Game.Werewolf.Engine ( checkStage, checkGameOver, ) where import Control.Lens.Extra import Control.Monad.Except import Control.Monad.Extra import Control.Monad.Random import Control.Monad.State import Control.Monad.Writer import Data.List.Extra import qualified Data.Map as Map import Data.Maybe TODO ( hjw ): remove Message . Command import Game.Werewolf.Game hiding (hasAnyoneWon, hasEveryoneLost) import Game.Werewolf.Message.Command import Game.Werewolf.Message.Engine import Game.Werewolf.Player import Game.Werewolf.Response import Game.Werewolf.Role hiding (name) import Game.Werewolf.Util import Prelude hiding (round) checkStage :: (MonadRandom m, MonadState Game m, MonadWriter [Message] m) => m () checkStage = do game <- get checkBoots >> checkStage' game' <- get when (game /= game') checkStage checkBoots :: (MonadState Game m, MonadWriter [Message] m) => m () checkBoots = do alivePlayerCount <- length . toListOf (players . traverse . alive) <$> get booteeNames <- uses boots $ Map.keys . Map.filter (\voters -> length voters > alivePlayerCount `div` 2) bootees <- mapM (findPlayerBy_ name) booteeNames forM_ (filter (is alive) bootees) $ \bootee -> do tell . (:[]) . playerBootedMessage bootee =<< get removePlayer (bootee ^. name) checkStage' :: (MonadRandom m, MonadState Game m, MonadWriter [Message] m) => m () checkStage' = use stage >>= \stage' -> case stage' of DruidsTurn -> do druid <- findPlayerBy_ role druidRole players' <- filter (isn't alphaWolf) <$> getAdjacentAlivePlayers (druid ^. name) when (has werewolves players' || has lycans players') $ tell [ferinaGruntsMessage] advanceStage GameOver -> return () HuntersTurn1 -> whenM (use hunterRetaliated) advanceStage HuntersTurn2 -> whenM (use hunterRetaliated) advanceStage Lynching -> do unlessM (Map.null <$> use votes) $ lynchVotee =<< preuse votee chosenVoters .= [] votes .= Map.empty advanceStage NecromancersTurn -> do whenM (hasuse $ players . necromancers . dead) advanceStage whenM (use deadRaised) advanceStage whenM (use passed) advanceStage OraclesTurn -> do whenM (hasuse $ players . oracles . dead) advanceStage whenM (isJust <$> use divine) advanceStage OrphansTurn -> do whenM (hasuse $ players . orphans . dead) advanceStage whenM (isJust <$> use roleModel) advanceStage ProtectorsTurn -> do whenM (hasuse $ players . protectors . dead) advanceStage whenM (isJust <$> use protect) advanceStage ScapegoatsTurn -> unlessM (use scapegoatBlamed) $ do game <- get tell [scapegoatChoseAllowedVotersMessage game] advanceStage SeersTurn -> do whenM (hasuse $ players . seers . dead) advanceStage whenM (isJust <$> use see) advanceStage Sunrise -> do round += 1 devourVotee =<< preuse votee whenJustM (use poison) $ \targetName -> do target <- findPlayerBy_ name targetName killPlayer targetName tell . (:[]) . playerPoisonedMessage target =<< get whenJustM (preuse $ players . seers . alive) $ \seer -> do target <- use see >>= findPlayerBy_ name . fromJust when (is alive target) $ tell [playerSeenMessage (seer ^. name) target] whenJustM (preuse $ players . oracles . alive) $ \oracle -> do target <- use divine >>= findPlayerBy_ name . fromJust when (is alive target) $ tell [playerDivinedMessage (oracle ^. name) target] divine .= Nothing poison .= Nothing protect .= Nothing see .= Nothing votes .= Map.empty advanceStage Sunset -> do whenJustM (use roleModel) $ \roleModelsName -> do orphan <- findPlayerBy_ role orphanRole whenM (isPlayerDead roleModelsName &&^ return (is alive orphan) &&^ return (is villager orphan)) $ do setPlayerAllegiance (orphan ^. name) Werewolves tell . orphanJoinedPackMessages (orphan ^. name) =<< get advanceStage VillageDrunksTurn -> do randomAllegiance <- getRandomAllegiance players . villageDrunks . role . allegiance .= randomAllegiance villageDrunk <- findPlayerBy_ role villageDrunkRole if is villager villageDrunk then tell [villageDrunkJoinedVillageMessage $ villageDrunk ^. name] else tell . villageDrunkJoinedPackMessages (villageDrunk ^. name) =<< get advanceStage VillagesTurn -> whenM (hasn'tuse pendingVoters) $ do uses votes Map.toList >>= mapM_ (\(voterName, voteeName) -> do voter <- findPlayerBy_ name voterName votee <- findPlayerBy_ name voteeName tell [playerMadeLynchVoteMessage Nothing voter votee] ) advanceStage WerewolvesTurn -> whenM (hasn'tuse pendingVoters) $ do whenM (liftM2 (==) (use protect) (preuses votee $ view name)) $ votes .= Map.empty advanceStage WitchsTurn -> do whenM (hasuse $ players . witches . dead) advanceStage whenM (use healUsed &&^ use poisonUsed) advanceStage whenM (use passed) advanceStage lynchVotee :: (MonadState Game m, MonadWriter [Message] m) => Maybe Player -> m () lynchVotee (Just votee) | is jester votee = do jesterRevealed .= True tell . (:[]) . jesterLynchedMessage =<< get | is fallenAngel votee = do fallenAngelLynched .= True tell . (:[]) . playerLynchedMessage votee =<< get | is saint votee = do tell . (:[]) . playerLynchedMessage votee =<< get killPlayer (votee ^. name) voterNames <- uses votes (filter (/= votee ^. name) . Map.keys . Map.filter (== votee ^. name)) forM_ voterNames killPlayer voters <- mapM (findPlayerBy_ name) voterNames tell . (:[]) . saintLynchedMessage voters =<< get | is werewolf votee = do tell . (:[]) . werewolfLynchedMessage votee =<< get killPlayer (votee ^. name) | otherwise = do tell . (:[]) . playerLynchedMessage votee =<< get killPlayer (votee ^. name) lynchVotee _ = preuse (players . scapegoats . alive) >>= \mScapegoat -> case mScapegoat of Just scapegoat -> do scapegoatBlamed .= True killPlayer (scapegoat ^. name) tell . (:[]) . scapegoatLynchedMessage =<< get _ -> tell [noPlayerLynchedMessage] devourVotee :: (MonadState Game m, MonadWriter [Message] m) => Maybe Player -> m () devourVotee Nothing = tell [noPlayerDevouredMessage] devourVotee (Just votee) = do killPlayer (votee ^. name) tell . (:[]) . playerDevouredMessage votee =<< get when (is medusa votee) . whenJustM (getFirstAdjacentAliveWerewolf $ votee ^. name) $ \werewolf -> do killPlayer (werewolf ^. name) tell . (:[]) . playerTurnedToStoneMessage werewolf =<< get advanceStage :: (MonadState Game m, MonadWriter [Message] m) => m () advanceStage = do game <- get nextStage <- ifM (hasAnyoneWon ||^ hasEveryoneLost) (return GameOver) (return . head $ filter (stageAvailable game) (drop1 $ dropWhile (game ^. stage /=) stageCycle)) stage .= nextStage boots .= Map.empty passed .= False tell . stageMessages =<< get checkGameOver :: (MonadState Game m, MonadWriter [Message] m) => m () checkGameOver = whenM (hasAnyoneWon ||^ hasEveryoneLost) $ stage .= GameOver >> get >>= tell . gameOverMessages
281a6cd70469b81c7557e0bed3505934949cd7cb916ab3d13ad724b224241d6a
rtoy/ansi-cl-tests
format-tilde.lsp
;-*- Mode: Lisp -*- Author : Created : We d Jul 28 00:27:00 2004 ;;;; Contains: Tests of format directive ~~ (in-package :cl-test) (compile-and-load "printer-aux.lsp") (def-format-test format.~.1 "~~" nil "~") (deftest format.~.2 (loop for i from 0 to 100 for s = (make-string i :initial-element #\~) for format-string = (format nil "~~~D~~" i) for s2 = (format nil format-string) unless (string= s s2) collect (list i s s2)) nil) (deftest formatter.~.2 (loop for i from 0 to 100 for s = (make-string i :initial-element #\~) for format-string = (format nil "~~~D~~" i) for fn = (eval `(formatter ,format-string)) for s2 = (formatter-call-to-string fn) unless (string= s s2) collect (list i s s2)) nil) (def-format-test format.~.3 "~v~" (0) "") (deftest format.~.4 (loop for i from 0 to 100 for s = (make-string i :initial-element #\~) for s2 = (format nil "~V~" i) unless (string= s s2) collect (list i s s2)) nil) (deftest formatter.~.4 (let ((fn (formatter "~v~"))) (loop for i from 0 to 100 for s = (make-string i :initial-element #\~) for s2 = (formatter-call-to-string fn i) unless (string= s s2) collect (list i s s2))) nil) (deftest format.~.5 (loop for i from 0 to (min (- call-arguments-limit 3) 100) for s = (make-string i :initial-element #\~) for args = (make-list i) for s2 = (apply #'format nil "~#~" args) unless (string= s s2) collect (list i s s2)) nil) (deftest formatter.~.5 (let ((fn (formatter "~#~"))) (loop for i from 0 to (min (- call-arguments-limit 3) 100) for s = (make-string i :initial-element #\~) for args = (make-list i) for s2 = (with-output-to-string (stream) (assert (equal (apply fn stream args) args))) unless (string= s s2) collect (list i s s2))) nil)
null
https://raw.githubusercontent.com/rtoy/ansi-cl-tests/9708f3977220c46def29f43bb237e97d62033c1d/format-tilde.lsp
lisp
-*- Mode: Lisp -*- Contains: Tests of format directive ~~
Author : Created : We d Jul 28 00:27:00 2004 (in-package :cl-test) (compile-and-load "printer-aux.lsp") (def-format-test format.~.1 "~~" nil "~") (deftest format.~.2 (loop for i from 0 to 100 for s = (make-string i :initial-element #\~) for format-string = (format nil "~~~D~~" i) for s2 = (format nil format-string) unless (string= s s2) collect (list i s s2)) nil) (deftest formatter.~.2 (loop for i from 0 to 100 for s = (make-string i :initial-element #\~) for format-string = (format nil "~~~D~~" i) for fn = (eval `(formatter ,format-string)) for s2 = (formatter-call-to-string fn) unless (string= s s2) collect (list i s s2)) nil) (def-format-test format.~.3 "~v~" (0) "") (deftest format.~.4 (loop for i from 0 to 100 for s = (make-string i :initial-element #\~) for s2 = (format nil "~V~" i) unless (string= s s2) collect (list i s s2)) nil) (deftest formatter.~.4 (let ((fn (formatter "~v~"))) (loop for i from 0 to 100 for s = (make-string i :initial-element #\~) for s2 = (formatter-call-to-string fn i) unless (string= s s2) collect (list i s s2))) nil) (deftest format.~.5 (loop for i from 0 to (min (- call-arguments-limit 3) 100) for s = (make-string i :initial-element #\~) for args = (make-list i) for s2 = (apply #'format nil "~#~" args) unless (string= s s2) collect (list i s s2)) nil) (deftest formatter.~.5 (let ((fn (formatter "~#~"))) (loop for i from 0 to (min (- call-arguments-limit 3) 100) for s = (make-string i :initial-element #\~) for args = (make-list i) for s2 = (with-output-to-string (stream) (assert (equal (apply fn stream args) args))) unless (string= s s2) collect (list i s s2))) nil)
0577e5129e08cdc61a55637e93598a4b33eae6faa40440109209d030a84d7f4e
jimcrayne/jhc
tc235.hs
{-# OPTIONS -fglasgow-exts #-} # LANGUAGE UndecidableInstances # -- Trac #1564 module Foo where import Text.PrettyPrint import Prelude hiding(head,tail) class FooBar m k l | m -> k l where a :: m graphtype instance FooBar [] Bool Bool where a = error "urk" instance FooBar Maybe Int Int where a = error "urk" class (Monad m)=>Gr g ep m | g -> ep where x:: m Int v:: m Int instance (Monad m, FooBar m x z) => Gr g ep m where x = error "urk" v = error "urk" Old GHC claims for y : y : : ( , FooBar m GHC.Prim . Any GHC.Prim . Any ) -- => m Int (which is wrong) -- The uses in foo and bar show if that happens y () = x foo :: [Int] foo = y () bar :: Maybe Int bar = y ()
null
https://raw.githubusercontent.com/jimcrayne/jhc/1ff035af3d697f9175f8761c8d08edbffde03b4e/regress/tests/1_typecheck/2_pass/ghc/uncat/tc235.hs
haskell
# OPTIONS -fglasgow-exts # Trac #1564 => m Int (which is wrong) The uses in foo and bar show if that happens
# LANGUAGE UndecidableInstances # module Foo where import Text.PrettyPrint import Prelude hiding(head,tail) class FooBar m k l | m -> k l where a :: m graphtype instance FooBar [] Bool Bool where a = error "urk" instance FooBar Maybe Int Int where a = error "urk" class (Monad m)=>Gr g ep m | g -> ep where x:: m Int v:: m Int instance (Monad m, FooBar m x z) => Gr g ep m where x = error "urk" v = error "urk" Old GHC claims for y : y : : ( , FooBar m GHC.Prim . Any GHC.Prim . Any ) y () = x foo :: [Int] foo = y () bar :: Maybe Int bar = y ()
9054516c48fbc7a5f19a8267689069bfb662a475f2abf48ef6a0c5005fe1a239
finnishtransportagency/harja
toteumat_test.clj
(ns harja.palvelin.palvelut.toteumat-test (:require [clojure.test :refer :all] [clojure.java.io :as io] [com.stuartsierra.component :as component] [harja [pvm :as pvm] [testi :refer :all]] [harja.kyselyt.konversio :as konv] [harja.kyselyt.toteumat :as toteumat-q] [harja.palvelin.komponentit.tietokanta :as tietokanta] [harja.palvelin.palvelut.toteumat :refer :all] [harja.tyokalut.functor :refer [fmap]] [taoensso.timbre :as log] [org.httpkit.fake :refer [with-fake-http]] [harja.palvelin.palvelut.toteumat :as toteumat] [harja.palvelin.palvelut.tehtavamaarat :as tehtavamaarat] [harja.palvelin.palvelut.karttakuvat :as karttakuvat] [harja.palvelin.integraatiot.integraatioloki :as integraatioloki] [harja.palvelin.integraatiot.tierekisteri.tierekisteri-komponentti :as tierekisteri] [harja.domain.tierekisteri.varusteet :as varusteet-domain])) (def +testi-tierekisteri-url+ "harja.testi.tierekisteri") (def +oikea-testi-tierekisteri-url+ "-test.solitaservices.fi/harja/integraatiotesti/tierekisteri") (defn jarjestelma-fixture [testit] (alter-var-root #'jarjestelma (fn [_] (let [tietokanta (tietokanta/luo-tietokanta testitietokanta)] (component/start (component/system-map :db tietokanta :db-replica tietokanta :http-palvelin (testi-http-palvelin) :karttakuvat (component/using (karttakuvat/luo-karttakuvat) [:http-palvelin :db]) :integraatioloki (component/using (integraatioloki/->Integraatioloki nil) [:db]) :tierekisteri (component/using (tierekisteri/->Tierekisteri +testi-tierekisteri-url+ nil) [:db :integraatioloki]) :toteumat (component/using (toteumat/->Toteumat) [:http-palvelin :db :db-replica :karttakuvat :tierekisteri]) :tehtavamaarat (component/using (tehtavamaarat/->Tehtavamaarat) [:http-palvelin :db])))))) (testit) (alter-var-root #'jarjestelma component/stop)) (use-fixtures :once (compose-fixtures jarjestelma-fixture urakkatieto-fixture)) käyttää testidata.sql : (deftest erilliskustannukset-haettu-oikein (let [alkupvm (pvm/luo-pvm 2005 9 1) loppupvm (pvm/luo-pvm 2006 10 30) res (kutsu-palvelua (:http-palvelin jarjestelma) :urakan-erilliskustannukset +kayttaja-jvh+ {:urakka-id @oulun-alueurakan-2005-2010-id :alkupvm alkupvm :loppupvm loppupvm}) oulun-alueurakan-toiden-lkm (ffirst (q (str "SELECT count(*) FROM erilliskustannus WHERE sopimus IN (SELECT id FROM sopimus WHERE urakka = " @oulun-alueurakan-2005-2010-id ") AND pvm >= '2005-10-01' AND pvm <= '2006-09-30'")))] (is (= (count res) oulun-alueurakan-toiden-lkm) "Erilliskustannusten määrä"))) (deftest tallenna-erilliskustannus-testi 1.10.2005 30.9.2006 toteuman-pvm (pvm/luo-pvm 2005 11 12) toteuman-lisatieto "Testikeissin lisätieto" ek {:urakka-id @oulun-alueurakan-2005-2010-id :alkupvm hoitokauden-alkupvm :loppupvm hoitokauden-loppupvm :pvm toteuman-pvm :rahasumma 20000.0 :indeksin_nimi "MAKU 2005" :toimenpideinstanssi 1 :sopimus 1 :tyyppi "asiakastyytyvaisyysbonus" :lisatieto toteuman-lisatieto} maara-ennen-lisaysta (ffirst (q (str "SELECT count(*) FROM erilliskustannus WHERE sopimus IN (SELECT id FROM sopimus WHERE urakka = " @oulun-alueurakan-2005-2010-id ") AND pvm >= '2005-10-01' AND pvm <= '2006-09-30'"))) vastaus (kutsu-palvelua (:http-palvelin jarjestelma) :tallenna-erilliskustannus +kayttaja-jvh+ ek) lisatty (first (filter #(and (= (:pvm %) toteuman-pvm) (= (:lisatieto %) toteuman-lisatieto)) vastaus))] (is (= (:pvm lisatty) toteuman-pvm) "Tallennetun erilliskustannuksen pvm") (is (= (:lisatieto lisatty) toteuman-lisatieto) "Tallennetun erilliskustannuksen lisätieto") (is (= (:indeksin_nimi lisatty) "MAKU 2005") "Tallennetun erilliskustannuksen indeksin nimi") (is (= (:rahasumma lisatty) 20000.0) "Tallennetun erilliskustannuksen pvm") (is (= (:urakka lisatty) @oulun-alueurakan-2005-2010-id) "Oikea urakka") (is (= (:toimenpideinstanssi lisatty) 1) "Tallennetun erilliskustannuksen tp") (is (= (count vastaus) (+ 1 maara-ennen-lisaysta)) "Tallennuksen jälkeen erilliskustannusten määrä") ;; Testaa päivittämistä (let [ek-id (:id lisatty) vastaus (kutsu-palvelua (:http-palvelin jarjestelma) :tallenna-erilliskustannus +kayttaja-jvh+ (assoc ek :id ek-id :indeksin_nimi "MAKU 2010")) paivitetty (first (filter #(= (:id %) ek-id) vastaus))] (is (= (:indeksin_nimi paivitetty) "MAKU 2010") "Tallennetun erilliskustannuksen indeksin nimi")) Testaa virheellinen urakka (let [ek-id (:id lisatty) _ (is (thrown? SecurityException (kutsu-palvelua (:http-palvelin jarjestelma) :tallenna-erilliskustannus +kayttaja-jvh+ (assoc ek :id ek-id :indeksin_nimi "MAKSU 2015" :urakka-id @oulun-alueurakan-2014-2019-id)))) urakka (ffirst (q (str "SELECT urakka FROM erilliskustannus WHERE id = " ek-id ";"))) indeksin-nimi (ffirst (q (str "SELECT indeksin_nimi FROM erilliskustannus WHERE id = " ek-id ";")))] (is (= urakka @oulun-alueurakan-2005-2010-id) "Virheellistä urakkaa ei päivitetty") (is (= indeksin-nimi "MAKU 2010") "Virheellistä indeksiä ei päivitetty")) ;; Testaa poistetuksi merkitsemistä (let [ek-id (:id lisatty) poistettu-id (kutsu-palvelua (:http-palvelin jarjestelma) :poista-erilliskustannus +kayttaja-jvh+ {:id ek-id :urakka-id @oulun-alueurakan-2005-2010-id}) poistettu? (ffirst (q (str "SELECT poistettu FROM erilliskustannus WHERE id = " ek-id ";")))] (is (= poistettu-id ek-id) "Poistetun erilliskustannuksen id") (is (= poistettu? true))) (u (str "DELETE FROM erilliskustannus WHERE pvm = '2005-12-12' AND lisatieto = '" toteuman-lisatieto "'")))) (deftest tallenna-muut-tyot-toteuma-testi 24.12.2005 1.10.2005 30.9.2006 toteuman-lisatieto "Testikeissin lisätieto2" tyo {:urakka-id @oulun-alueurakan-2005-2010-id :sopimus-id @oulun-alueurakan-2005-2010-paasopimuksen-id :alkanut tyon-pvm :paattynyt tyon-pvm :hoitokausi-aloituspvm hoitokausi-aloituspvm :hoitokausi-lopetuspvm hoitokausi-lopetuspvm :suorittajan-nimi "Alihankkijapaja Ky" :suorittajan-ytunnus "123456-Y" :tyyppi :muutostyo :lisatieto toteuman-lisatieto :tehtava {:paivanhinta 456, :maara 2, :toimenpidekoodi 1368}} maara-ennen-lisaysta (ffirst (q (str "SELECT count(*) FROM toteuma WHERE urakka = " @oulun-alueurakan-2005-2010-id " AND sopimus = " @oulun-alueurakan-2005-2010-paasopimuksen-id " AND tyyppi IN ('muutostyo', 'lisatyo', 'akillinen-hoitotyo', 'vahinkojen-korjaukset') AND alkanut >= to_date('1-10-2005', 'DD-MM-YYYY') AND paattynyt <= to_date('30-09-2006', 'DD-MM-YYYY');;"))) vastaus (kutsu-palvelua (:http-palvelin jarjestelma) :tallenna-muiden-toiden-toteuma +kayttaja-jvh+ tyo) lisatty (first (filter #(and (= (:lisatieto %) toteuman-lisatieto)) vastaus))] (is (= (count vastaus) (+ 1 maara-ennen-lisaysta)) "Tallennuksen jälkeen muiden töiden määrä") (is (= (:alkanut lisatty) tyon-pvm) "Tallennetun muun työn alkanut pvm") (is (= (:paattynyt lisatty) tyon-pvm) "Tallennetun muun työn paattynyt pvm") (is (= (:tyyppi lisatty) :muutostyo) "Tallennetun muun työn tyyppi") (is (= (:lisatieto lisatty) toteuman-lisatieto) "Tallennetun erilliskustannuksen lisätieto") (is (= (get-in lisatty [:tehtava :paivanhinta]) 456.0) "Tallennetun muun työn päivänhinta") (is (= (get-in lisatty [:tehtava :maara]) 2.0) "Tallennetun muun työn määrä") (is (= (get-in lisatty [:tehtava :toimenpidekoodi]) 1368) "Tallennetun muun työn toimenpidekoodi") ;; Testaa päivitys (let [toteuma-id (get-in lisatty [:toteuma :id]) vastaus (kutsu-palvelua (:http-palvelin jarjestelma) :tallenna-muiden-toiden-toteuma +kayttaja-jvh+ (assoc tyo :toteuma {:id toteuma-id} :lisatieto "Testikeissi")) paivitetty (first (filter #(= (get-in % [:toteuma :id]) toteuma-id) vastaus))] (is (= (:lisatieto paivitetty) "Testikeissi") "Päivitetyn erilliskustannuksen lisätieto")) Testaa virheellinen urakka (try (let [toteuma-id (get-in lisatty [:toteuma :id]) _ (kutsu-palvelua (:http-palvelin jarjestelma) :tallenna-muiden-toiden-toteuma +kayttaja-jvh+ (assoc tyo :toteuma {:id toteuma-id} :urakka-id @oulun-alueurakan-2014-2019-id))]) (is false "Päivitys sallittiin virheellisesti") (catch Exception e (is true "Päivitystä ei sallittu"))) lisätyt rivit pois (u (str "DELETE FROM toteuma_tehtava WHERE toteuma = " (get-in lisatty [:toteuma :id]))) (u (str "DELETE FROM toteuma WHERE id = " (get-in lisatty [:toteuma :id]))))) (deftest tallenna-yksikkohintainen-toteuma-testi 24.12.2005 1.10.2005 30.9.2006 urakka-id @oulun-alueurakan-2005-2010-id toteuman-lisatieto "Testikeissin lisätieto4" tyo {:urakka-id urakka-id :sopimus-id @oulun-alueurakan-2005-2010-paasopimuksen-id :alkanut tyon-pvm :paattynyt tyon-pvm :hoitokausi-aloituspvm hoitokausi-aloituspvm :hoitokausi-lopetuspvm hoitokausi-lopetuspvm :suorittajan-nimi "Alihankkijapaja Ky" :suorittajan-ytunnus "123456-Y" :tyyppi :yksikkohintainen :toteuma-id nil :lisatieto toteuman-lisatieto :tehtavat [{:toimenpidekoodi 1368 :maara 333}]} hae-summat #(->> (kutsu-palvelua (:http-palvelin jarjestelma) :urakan-toteumien-tehtavien-summat +kayttaja-jvh+ {:urakka-id urakka-id :sopimus-id @oulun-alueurakan-2005-2010-paasopimuksen-id :alkupvm hoitokausi-aloituspvm :loppupvm hoitokausi-lopetuspvm :tyyppi :yksikkohintainen}) (group-by :tpk_id) (fmap first)) summat-ennen-lisaysta (hae-summat)] (is (not (contains? summat-ennen-lisaysta 1368))) (let [_ (println "tyo ::::::::::::::::." (pr-str tyo)) lisatty (kutsu-palvelua (:http-palvelin jarjestelma) :tallenna-urakan-toteuma-ja-yksikkohintaiset-tehtavat +kayttaja-jvh+ tyo) summat-lisayksen-jalkeen (hae-summat)] (is (= (get-in lisatty [:toteuma :alkanut]) tyon-pvm) "Tallennetun työn alkanut pvm") (is (= (get-in lisatty [:toteuma :paattynyt]) tyon-pvm) "Tallennetun työn paattynyt pvm") (is (= (get-in lisatty [:toteuma :lisatieto]) toteuman-lisatieto) "Tallennetun työn lisätieto") (is (= (get-in lisatty [:toteuma :suorittajan-nimi]) "Alihankkijapaja Ky") "Tallennetun työn suorittajan nimi") (is (= (get-in lisatty [:toteuma :suorittajan-ytunnus]) "123456-Y") "Tallennetun työn suorittajan y-tunnus") (is (= (get-in lisatty [:toteuma :urakka-id]) urakka-id) "Tallennetun työn urakan id") (is (= (get-in lisatty [:toteuma :sopimus-id]) @oulun-alueurakan-2005-2010-paasopimuksen-id) "Tallennetun työn pääsopimuksen id") (is (= (get-in lisatty [:toteuma :tehtavat 0 :toimenpidekoodi]) 1368) "Tallennetun työn tehtävän toimenpidekoodi") (is (= (get-in lisatty [:toteuma :tehtavat 0 :maara]) 333) "Tallennetun työn tehtävän määrä") (is (= (get-in lisatty [:toteuma :tyyppi]) :yksikkohintainen) "Tallennetun työn toteuman tyyppi") (is (== 333 (get-in summat-lisayksen-jalkeen [1368 :maara]))) ;; Testaa päivitys (let [toteuma-id (get-in lisatty [:toteuma :toteuma-id]) toteuma (kutsu-palvelua (:http-palvelin jarjestelma) :urakan-toteuma +kayttaja-jvh+ {:urakka-id urakka-id :toteuma-id toteuma-id}) muokattu-tyo (assoc tyo :toteuma-id toteuma-id :tehtavat [{:toimenpidekoodi 1369 :maara 666 :tehtava-id (get-in toteuma [:tehtavat 0 :tehtava-id])}]) muokattu (kutsu-palvelua (:http-palvelin jarjestelma) :tallenna-urakan-toteuma-ja-yksikkohintaiset-tehtavat +kayttaja-jvh+ muokattu-tyo) summat-muokkauksen-jalkeen (hae-summat)] (is (= (get-in muokattu [:toteuma :tehtavat 0 :toimenpidekoodi]) 1369)) (is (= (get-in muokattu [:toteuma :tehtavat 0 :maara]) 666)) (is (= 1 (count (get-in muokattu [:toteuma :tehtavat])))) (is (not (contains? summat-muokkauksen-jalkeen 1368))) (is (== 666 (get-in summat-muokkauksen-jalkeen [1369 :maara]))) Testaa päivitys (try (kutsu-palvelua (:http-palvelin jarjestelma) :tallenna-urakan-toteuma-ja-yksikkohintaiset-tehtavat +kayttaja-jvh+ (assoc muokattu-tyo :urakka-id @muhoksen-paallystysurakan-id)) (is false "Virheellisesti sallittiin päivittää väärällä urakka-id:llä") (catch Exception e (is true "Ei sallittu päivittää väärällä urakka-id:llä"))) (u (str "DELETE FROM toteuma_tehtava WHERE toteuma = " toteuma-id ";")) (u (str "DELETE FROM toteuma WHERE id = " toteuma-id)))))) (deftest tallenna-yksikkohintainen-toteuma-ja-poista-tehtava-testi 24.12.2005 1.10.2005 30.9.2006 urakka-id @oulun-alueurakan-2005-2010-id toteuman-lisatieto "Testikeissin lisätieto4" tyo {:urakka-id urakka-id :sopimus-id @oulun-alueurakan-2005-2010-paasopimuksen-id :alkanut tyon-pvm :paattynyt tyon-pvm :hoitokausi-aloituspvm hoitokausi-aloituspvm :hoitokausi-lopetuspvm hoitokausi-lopetuspvm :suorittajan-nimi "Alihankkijapaja Ky" :suorittajan-ytunnus "123456-Y" :tyyppi :yksikkohintainen :toteuma-id nil :lisatieto toteuman-lisatieto :tehtavat [{:toimenpidekoodi 1368 :maara 333}]} hae-summat #(->> (kutsu-palvelua (:http-palvelin jarjestelma) :urakan-toteumien-tehtavien-summat +kayttaja-jvh+ {:urakka-id urakka-id :sopimus-id @oulun-alueurakan-2005-2010-paasopimuksen-id :alkupvm hoitokausi-aloituspvm :loppupvm hoitokausi-lopetuspvm :tyyppi :yksikkohintainen}) (group-by :tpk_id) (fmap first)) summat-ennen-lisaysta (hae-summat)] (is (not (contains? summat-ennen-lisaysta 1368))) (let [_ (println "tyo ::::::::::::::::." (pr-str tyo)) lisatty (kutsu-palvelua (:http-palvelin jarjestelma) :tallenna-urakan-toteuma-ja-yksikkohintaiset-tehtavat +kayttaja-jvh+ tyo) summat-lisayksen-jalkeen (hae-summat)] (is (= (get-in lisatty [:toteuma :alkanut]) tyon-pvm) "Tallennetun työn alkanut pvm") (is (= (get-in lisatty [:toteuma :paattynyt]) tyon-pvm) "Tallennetun työn paattynyt pvm") (is (= (get-in lisatty [:toteuma :lisatieto]) toteuman-lisatieto) "Tallennetun työn lisätieto") (is (= (get-in lisatty [:toteuma :suorittajan-nimi]) "Alihankkijapaja Ky") "Tallennetun työn suorittajan nimi") (is (= (get-in lisatty [:toteuma :suorittajan-ytunnus]) "123456-Y") "Tallennetun työn suorittajan y-tunnus") (is (= (get-in lisatty [:toteuma :urakka-id]) urakka-id) "Tallennetun työn urakan id") (is (= (get-in lisatty [:toteuma :sopimus-id]) @oulun-alueurakan-2005-2010-paasopimuksen-id) "Tallennetun työn pääsopimuksen id") (is (= (get-in lisatty [:toteuma :tehtavat 0 :toimenpidekoodi]) 1368) "Tallennetun työn tehtävän toimenpidekoodi") (is (= (get-in lisatty [:toteuma :tehtavat 0 :maara]) 333) "Tallennetun työn tehtävän määrä") (is (= (get-in lisatty [:toteuma :tyyppi]) :yksikkohintainen) "Tallennetun työn toteuman tyyppi") (is (== 333 (get-in summat-lisayksen-jalkeen [1368 :maara]))) Testaa (let [toteuma-id (get-in lisatty [:toteuma :toteuma-id]) toteuma (kutsu-palvelua (:http-palvelin jarjestelma) :urakan-toteuma +kayttaja-jvh+ {:urakka-id urakka-id :toteuma-id toteuma-id}) muokattu-tyo (assoc tyo :toteuma-id toteuma-id :tehtavat [{:toimenpidekoodi 1368 :maara 333 :poistettu true :tehtava-id (get-in toteuma [:tehtavat 0 :tehtava-id])} {:toimenpidekoodi 1369 :maara 333}]) muokattu (kutsu-palvelua (:http-palvelin jarjestelma) :tallenna-urakan-toteuma-ja-yksikkohintaiset-tehtavat +kayttaja-jvh+ muokattu-tyo) summat-muokkauksen-jalkeen (hae-summat)] (is (= (get-in muokattu [:toteuma :tehtavat 1 :toimenpidekoodi]) 1369)) (is (= (get-in muokattu [:toteuma :tehtavat 1 :maara]) 333)) (is (not (contains? summat-muokkauksen-jalkeen 1368))) (is (== 333 (get-in summat-muokkauksen-jalkeen [1369 :maara]))) (u (str "DELETE FROM toteuma_tehtava WHERE toteuma = " toteuma-id ";")) (u (str "DELETE FROM toteuma WHERE id = " toteuma-id)))))) (deftest tallenna-kokonaishintainen-toteuma-testi 24.12.2020 hoitokausi-aloituspvm (pvm/luo-pvm 2020 9 1) ; 1.10.2020 hoitokausi-lopetuspvm (pvm/luo-pvm 2021 8 30) ;30.9.2021 urakka-id (hae-oulun-alueurakan-2014-2019-id) tyo {:urakka-id urakka-id :sopimus-id (hae-oulun-alueurakan-2014-2019-paasopimuksen-id) :alkanut tyon-pvm :paattynyt tyon-pvm :reitti {:type :multiline :lines [{:type :line, :points [[426948.180407029 7212765.48225361] [430650.8691 7212578.8262]]}]} :hoitokausi-aloituspvm hoitokausi-aloituspvm :hoitokausi-lopetuspvm hoitokausi-lopetuspvm :suorittajan-nimi "Alihankkijapaja Ky" :suorittajan-ytunnus "123456-Y" :tyyppi :kokonaishintainen :toteuma-id nil :tehtavat [{:toimenpidekoodi 1368 :maara 333}]} lisatty (some #(when (= (:toimenpidekoodi %) 1368) %) (kutsu-palvelua (:http-palvelin jarjestelma) :tallenna-urakan-toteuma-ja-kokonaishintaiset-tehtavat +kayttaja-jvh+ {:toteuma tyo :hakuparametrit {:urakka-id urakka-id :sopimus-id (hae-oulun-alueurakan-2014-2019-paasopimuksen-id) :alkupvm hoitokausi-aloituspvm :loppupvm hoitokausi-lopetuspvm :toimenpide nil :tehtava nil}}))] (is (= (get-in lisatty [:pvm]) tyon-pvm) "Tallennetun työn alkanut pvm") (is (= (get-in lisatty [:jarjestelmanlisaama]) false)) (is (= (get-in lisatty [:nimi]) "Pistehiekoitus")) (is (= (get-in lisatty [:yksikko]) "tiekm") "Yksikkö") (is (= (get-in lisatty [:toimenpidekoodi]) 1368) "Tallennetun työn tehtävän toimenpidekoodi") (is (= (get-in lisatty [:maara]) 333M) "Tallennetun työn tehtävän määrä"))) (deftest hae-urakan-toteuma-kun-toteuma-ei-kuulu-urakkaan (let [toteuma-id (ffirst (q "SELECT id FROM toteuma WHERE urakka != " @oulun-alueurakan-2014-2019-id " AND tyyppi = 'yksikkohintainen' LIMIT 1;"))] (is (thrown? SecurityException (kutsu-palvelua (:http-palvelin jarjestelma) :urakan-toteuma +kayttaja-jvh+ {:urakka-id @oulun-alueurakan-2014-2019-id :toteuma-id toteuma-id}))))) (deftest tallenna-toteuma-ja-toteumamateriaalit-test (let [[urakka sopimus] (first (q (str "SELECT urakka, id FROM sopimus WHERE urakka=" @oulun-alueurakan-2005-2010-id))) toteuma (atom {:id -5, :urakka urakka :sopimus sopimus :alkanut (pvm/luo-pvm 2005 11 24) :paattynyt (pvm/luo-pvm 2005 11 24) :tyyppi "yksikkohintainen" :suorittajan-nimi "UNIT TEST" :suorittajan-ytunnus 1234 :lisatieto "Unit test teki tämän"}) tmt (atom [{:id -1 :materiaalikoodi 1 :maara 192837} {:materiaalikoodi 1 :maara 192837}]) sopimuksen-kaytetty-materiaali-ennen (q (str "SELECT alkupvm, materiaalikoodi, maara FROM sopimuksen_kaytetty_materiaali WHERE sopimus = " sopimus))] tarkistetaan että kaikki cachesta palautetut expected - setistä (is (= true (every? #(some? ((set [[#inst "2005-09-30T21:00:00.000-00:00" 1 7M] [#inst "2005-09-30T21:00:00.000-00:00" 4 9M] [#inst "2005-09-30T21:00:00.000-00:00" 2 4M] [#inst "2005-09-30T21:00:00.000-00:00" 3 3M] [#inst "2004-10-19T21:00:00.000-00:00" 5 25M]]) %)) sopimuksen-kaytetty-materiaali-ennen))) (is (= 0 (ffirst (q "SELECT count(*) FROM toteuma_materiaali WHERE maara=192837 AND poistettu IS NOT TRUE")))) (is (= 0 (ffirst (q "SELECT count(*) FROM toteuma WHERE suorittajan_nimi='UNIT TEST' AND poistettu IS NOT TRUE")))) (is (nil? (kutsu-palvelua (:http-palvelin jarjestelma) :tallenna-toteuma-ja-toteumamateriaalit +kayttaja-jvh+ {:toteuma @toteuma :toteumamateriaalit @tmt pvm / luo - pvm 2006 8 30 ) ] :sopimus sopimus}))) (let [tmidt (flatten (q "SELECT id FROM toteuma_materiaali WHERE maara=192837")) tid (ffirst (q "SELECT id from toteuma WHERE suorittajan_nimi='UNIT TEST'")) uusi-lisatieto "NYT PITÄIS OLLA MUUTTUNUT." sopimuksen-kaytetty-materiaali-jalkeen (q (str "SELECT alkupvm, materiaalikoodi, maara FROM sopimuksen_kaytetty_materiaali WHERE sopimus = " sopimus))] tarkistetaan että kaikki cachesta palautetut expected - setistä (is (= true (every? #(some? ((set [[#inst "2005-09-30T21:00:00.000-00:00" 1 7M] [#inst "2005-09-30T21:00:00.000-00:00" 4 9M] [#inst "2005-09-30T21:00:00.000-00:00" 2 4M] [#inst "2005-09-30T21:00:00.000-00:00" 3 3M] [#inst "2004-10-19T21:00:00.000-00:00" 5 25M] [#inst "2005-12-23T22:00:00.000-00:00" 1 385674M]]) %)) sopimuksen-kaytetty-materiaali-jalkeen))) (is (= 2 (ffirst (q "SELECT count(*) FROM toteuma_materiaali WHERE maara=192837 AND poistettu IS NOT TRUE")))) (is (= 1 (ffirst (q "SELECT count(*) FROM toteuma WHERE suorittajan_nimi='UNIT TEST' AND poistettu IS NOT TRUE")))) (reset! tmt [(-> (assoc (first @tmt) :id (first tmidt)) (assoc :poistettu true)) (-> (assoc (second @tmt) :id (second tmidt)) (assoc :maara 8712))]) (reset! toteuma (-> (assoc @toteuma :id tid) (assoc :lisatieto uusi-lisatieto))) (is (not (nil? (kutsu-palvelua (:http-palvelin jarjestelma) :tallenna-toteuma-ja-toteumamateriaalit +kayttaja-jvh+ {:toteuma @toteuma :toteumamateriaalit @tmt :hoitokausi [(pvm/luo-pvm 2005 9 1) (pvm/luo-pvm 2006 8 30)] :sopimus sopimus})))) (is (= 1 (ffirst (q "SELECT count(*) FROM toteuma WHERE suorittajan_nimi='UNIT TEST' AND poistettu IS NOT TRUE")))) (is (= 1 (ffirst (q "SELECT count(*) FROM toteuma_materiaali WHERE maara=192837 AND poistettu IS TRUE")))) (is (= 1 (ffirst (q "SELECT count(*) FROM toteuma_materiaali WHERE maara=8712 AND poistettu IS NOT TRUE")))) (is (= uusi-lisatieto (ffirst (q "SELECT lisatieto FROM toteuma WHERE id=" tid)))) (is (= 8712 (int (ffirst (q "SELECT maara FROM toteuma_materiaali WHERE id=" (second tmidt)))))) (u "DELETE FROM toteuma_materiaali WHERE id in (" (clojure.string/join "," tmidt) ")") (u "DELETE FROM toteuma WHERE id=" tid)))) (deftest materiaalin-pvm-muuttuu-cachet-pysyy-jiirissa (let [urakka-id (hae-oulun-alueurakan-2014-2019-id) sopimus-id (hae-oulun-alueurakan-2014-2019-paasopimuksen-id) sopimuksen-kaytetty-mat-ennen-odotettu (set [[2 #inst "2015-02-17T22:00:00.000-00:00" 1 1800M] [2 #inst "2015-02-18T22:00:00.000-00:00" 7 200M] [2 #inst "2015-02-18T22:00:00.000-00:00" 16 2000M]]) sopimuksen-kaytetty-mat-jalkeen-odotettu (set [[2 #inst "2015-02-17T22:00:00.000-00:00" 1 1800M] [2 #inst "2015-02-18T22:00:00.000-00:00" 7 200M] [2 #inst "2015-02-13T22:00:00.000-00:00" 16 2100M]]) hoitoluokittaiset-ennen-odotettu (set [[#inst "2015-02-17T22:00:00.000-00:00" 1 99 4 1800M] [#inst "2015-02-18T22:00:00.000-00:00" 7 99 4 200M] [#inst "2015-02-18T22:00:00.000-00:00" 16 99 4 2000M]]) hoitoluokittaiset-jalkeen-odotettu (set [[#inst "2015-02-17T22:00:00.000-00:00" 1 99 4 1800M] [#inst "2015-02-18T22:00:00.000-00:00" 7 99 4 200M] [#inst "2015-02-13T22:00:00.000-00:00" 16 99 4 2100M]]) sopimuksen-mat-kaytto-ennen (set (q (str "SELECT sopimus, alkupvm, materiaalikoodi, maara FROM sopimuksen_kaytetty_materiaali WHERE sopimus = " sopimus-id (pvm-vali-sql-tekstina "alkupvm" "'2015-02-01' AND '2015-02-28'") ";"))) hoitoluokittaiset-ennen (set (q (str "SELECT pvm, materiaalikoodi, talvihoitoluokka, urakka, maara FROM urakan_materiaalin_kaytto_hoitoluokittain WHERE urakka = " urakka-id (pvm-vali-sql-tekstina "pvm" "'2015-02-01' AND '2015-02-28'") ";"))) toteuman-id (ffirst (q (str "SELECT id FROM toteuma WHERE lisatieto = 'LYV-toteuma Natriumformiaatti';"))) tm-id (ffirst (q (str "SELECT id FROM toteuma_materiaali WHERE toteuma = " toteuman-id ";"))) toteuma {:id toteuman-id, :urakka urakka-id :sopimus sopimus-id :alkanut (pvm/->pvm "14.02.2015") :paattynyt (pvm/->pvm "14.02.2015") :tyyppi "materiaali" :suorittajan-nimi "Ahkera hommailija" :suorittajan-ytunnus 1234 :lisatieto "Pvm muutos ja cachet toimii"} tmt [{:id tm-id :materiaalikoodi 16 :maara 2100 :toteuma toteuman-id}]] tarkistetaan että kaikki cachesta palautetut expected - setistä (is (= sopimuksen-kaytetty-mat-ennen-odotettu sopimuksen-mat-kaytto-ennen ) "sopimuksen materiaalin käyttö cache ennen muutosta") (is (= hoitoluokittaiset-ennen-odotettu hoitoluokittaiset-ennen ) "hoitoluokittaisten cache ennen muutosta") kyseessä päivitys , palvelukutsua (is (= 1 (ffirst (q (str "SELECT count(*) FROM toteuma_materiaali WHERE toteuma = " toteuman-id " AND poistettu IS NOT TRUE;"))))) (is (= 1 (ffirst (q (str "SELECT count(*) FROM toteuma WHERE id=" toteuman-id " AND poistettu IS NOT TRUE;"))))) (kutsu-palvelua (:http-palvelin jarjestelma) :tallenna-toteuma-ja-toteumamateriaalit +kayttaja-jvh+ {:toteuma toteuma :toteumamateriaalit tmt :hoitokausi [#inst "2014-09-30T21:00:00.000-00:00" #inst "2015-09-30T20:59:59.000-00:00"] :sopimus sopimus-id}) lisäyksen yhden kerran ... (is (= 1 (ffirst (q (str "SELECT count(*) FROM toteuma_materiaali WHERE toteuma = " toteuman-id ";"))))) (is (= 1 (ffirst (q (str "SELECT count(*) FROM toteuma WHERE id=" toteuman-id " AND poistettu IS NOT TRUE;"))))) (let [sopimuksen-mat-kaytto-jalkeen (set (q (str "SELECT sopimus, alkupvm, materiaalikoodi, maara FROM sopimuksen_kaytetty_materiaali WHERE sopimus = " sopimus-id (pvm-vali-sql-tekstina "alkupvm" "'2015-02-01' AND '2015-02-28'") ";"))) hoitoluokittaiset-jalkeen (set (q (str "SELECT pvm, materiaalikoodi, talvihoitoluokka, urakka, maara FROM urakan_materiaalin_kaytto_hoitoluokittain WHERE urakka = " urakka-id (pvm-vali-sql-tekstina "pvm" "'2015-02-01' AND '2015-02-28'") ";")))] lisäyksen jälkeen cachet päivittyvät oikein , vanhalla pvm : , päivällä (is (= sopimuksen-kaytetty-mat-jalkeen-odotettu sopimuksen-mat-kaytto-jalkeen ) "sopimuksen materiaalin käyttö cache jalkeen muutoksen") (is (= hoitoluokittaiset-jalkeen-odotettu hoitoluokittaiset-jalkeen ) "hoitoluokittaisten cache jalkeen muutoksen")))) (deftest uusi-materliaali-cachet-pysyy-jiirissa (let [urakka-id (hae-oulun-alueurakan-2014-2019-id) sopimus-id (hae-oulun-alueurakan-2014-2019-paasopimuksen-id) sopimuksen-kaytetty-mat-ennen-odotettu (set []) sopimuksen-kaytetty-mat-jalkeen-odotettu (set [[2 #inst "2011-02-13T22:00:00.000-00:00" 16 200M]]) hoitoluokittaiset-ennen-odotettu (set []) hoitoluokittaiset-jalkeen-odotettu (set [[#inst "2011-02-13T22:00:00.000-00:00" 16 99 4 200M]]) sopimuksen-mat-kaytto-ennen (set (q (str "SELECT sopimus, alkupvm, materiaalikoodi, maara FROM sopimuksen_kaytetty_materiaali WHERE sopimus = " sopimus-id (pvm-vali-sql-tekstina "alkupvm" "'2011-02-01' AND '2011-02-28'") ";"))) hoitoluokittaiset-ennen (set (q (str "SELECT pvm, materiaalikoodi, talvihoitoluokka, urakka, maara FROM urakan_materiaalin_kaytto_hoitoluokittain WHERE urakka = " urakka-id (pvm-vali-sql-tekstina "pvm" "'2011-02-01' AND '2011-02-28'") ";"))) koska uusi koska uusi toteuma {:id toteuman-id, :urakka urakka-id :sopimus sopimus-id :alkanut (pvm/->pvm "14.02.2011") :paattynyt (pvm/->pvm "14.02.2011") :tyyppi "materiaali" :suorittajan-nimi "Ahkera hommailija" :suorittajan-ytunnus 1234 :lisatieto "Täysin uusi jiirijutska"} tmt [{:id tm-id :materiaalikoodi 16 :maara 200 :toteuma toteuman-id}]] tarkistetaan että kaikki cachesta palautetut expected - setistä (is (= sopimuksen-kaytetty-mat-ennen-odotettu sopimuksen-mat-kaytto-ennen ) "sopimuksen materiaalin käyttö cache ennen muutosta") (is (= hoitoluokittaiset-ennen-odotettu hoitoluokittaiset-ennen ) "hoitoluokittaisten cache ennen muutosta") (kutsu-palvelua (:http-palvelin jarjestelma) :tallenna-toteuma-ja-toteumamateriaalit +kayttaja-jvh+ {:toteuma toteuma :toteumamateriaalit tmt :hoitokausi [#inst "2010-09-30T21:00:00.000-00:00" #inst "2011-09-30T20:59:59.000-00:00"] :sopimus sopimus-id}) (let [toteuman-id-jalkeen (ffirst (q (str "SELECT id FROM toteuma WHERE lisatieto='Täysin uusi jiirijutska';")))] (is (= 1 (ffirst (q (str "SELECT count(*) FROM toteuma_materiaali WHERE toteuma = " toteuman-id-jalkeen ";"))))) (is (= 1 (ffirst (q (str "SELECT count(*) FROM toteuma WHERE id=" toteuman-id-jalkeen " AND poistettu IS NOT TRUE;")))))) (let [sopimuksen-mat-kaytto-jalkeen (set (q (str "SELECT sopimus, alkupvm, materiaalikoodi, maara FROM sopimuksen_kaytetty_materiaali WHERE sopimus = " sopimus-id (pvm-vali-sql-tekstina "alkupvm" "'2011-02-01' AND '2011-02-28'") ";"))) hoitoluokittaiset-jalkeen (set (q (str "SELECT pvm, materiaalikoodi, talvihoitoluokka, urakka, maara FROM urakan_materiaalin_kaytto_hoitoluokittain WHERE urakka = " urakka-id (pvm-vali-sql-tekstina "pvm" "'2011-02-01' AND '2011-02-28'") ";")))] lisäyksen jälkeen cachet päivittyvät oikein , vanhalla pvm : , päivällä (is (= sopimuksen-kaytetty-mat-jalkeen-odotettu sopimuksen-mat-kaytto-jalkeen ) "sopimuksen materiaalin käyttö cache jalkeen muutoksen") (is (= hoitoluokittaiset-jalkeen-odotettu hoitoluokittaiset-jalkeen ) "hoitoluokittaisten cache jalkeen muutoksen")))) (deftest varustetoteumat-haettu-oikein (let [alkupvm (pvm/luo-pvm 2005 9 1) loppupvm (pvm/luo-pvm 2017 10 30) hae-tietolaji-xml (slurp (io/resource "xsd/tierekisteri/esimerkit/hae-tietolaji-response.xml")) varustetoteumat (with-fake-http [(str +testi-tierekisteri-url+ "/haetietolaji") hae-tietolaji-xml] (kutsu-palvelua (:http-palvelin jarjestelma) :urakan-varustetoteumat +kayttaja-jvh+ {:urakka-id @oulun-alueurakan-2005-2010-id :sopimus-id @oulun-alueurakan-2005-2010-paasopimuksen-id :alkupvm alkupvm :loppupvm loppupvm :tietolajit (into #{} (keys varusteet-domain/tietolaji->selitys))}))] (is (>= (count varustetoteumat) 3)) (is (contains? (first varustetoteumat) :sijainti)))) circleci : stä ei saane yhteyttä + oikea - testi - tierekisteri - url+ Otetaan pois , että on saatu muutokset tierekisteriin liittyen tuotantoon asti - myöskään jenkinsistä ei saada yhteyttä joten disabloitu kunnes (when false ;; (not (circleci?)) (deftest varusteiden-testit Tässä . , niin tallennuksen aikana ei tarvitse enään tehdä uutta kutsua ( , niin se epäonnistuisi , koska annetun tierekisterikomponentin url ;; on tekaistu) (tierekisteri/hae-tietolaji (assoc (:tierekisteri jarjestelma) :tierekisteri-api-url +oikea-testi-tierekisteri-url+) "tl506" nil) (let [toteuma {:ajorata 0 :kuntoluokitus nil :sijainti {:type :point :coordinates [428024.7622351866 7210432.45750019]} :tierekisteriosoite {:numero 22 :alkuosa 1 :alkuetaisyys 3} :urakka-id 4 :loppupvm nil :arvot {:x 428025 :y 7210432 :asetusnr "11"} :puoli 1 :tietolaji "tl506" :id nil :uusi-liite nil :toiminto :lisatty :alkupvm (pvm/luo-pvm 2018 6 11) :tunniste nil :lisatieto nil} hakuehdot {:urakka-id 4 :sopimus-id 2 :alkupvm (pvm/luo-pvm 2017 9 30) :loppupvm (pvm/luo-pvm 3018 9 29) :tienumero nil} toteumien-maara (atom (count (q "SELECT id FROM toteuma;"))) , voidaan with - redefs funktiossa . Tarkoitus on vain muuttaa vastaus - saatu atomin , on suoritettu , se . laheta-varustetoteuma-tierekisteriin-copy tierekisteri/laheta-varustetoteuma-tierekisteriin haku-fn (fn [haku-parametrit vastaus-atom] (with-redefs [tierekisteri/laheta-varustetoteuma-tierekisteriin (fn [this varustetoteuma-id] (when (= (:tierekisteri-api-url this) +testi-tierekisteri-url+) (laheta-varustetoteuma-tierekisteriin-copy this varustetoteuma-id)) (reset! vastaus-atom true))] (kutsu-palvelua (:http-palvelin jarjestelma) :tallenna-varustetoteuma +kayttaja-jvh+ haku-parametrit)))] (testing "Varusteen tallentaminen" (let [lisaa-tietue-xml (slurp (io/resource "xsd/tierekisteri/esimerkit/ok-vastaus-response.xml")) vastaus-saatu (atom false)] (with-fake-http [(str +testi-tierekisteri-url+ "/lisaatietue") lisaa-tietue-xml] (let [vastaus (haku-fn {:hakuehdot hakuehdot :toteuma toteuma} vastaus-saatu) _ (odota-ehdon-tayttymista #(true? @vastaus-saatu) "Tierekisteristä saatiin vastaus" 10000) tallennettu-varuste (q "SELECT luotu, tunniste, tietolaji, toimenpide, tila FROM varustetoteuma WHERE tunniste='HARJ0000000000000002' ORDER BY luotu DESC;")] (swap! toteumien-maara inc) (is (= (count (q "SELECT id FROM toteuma;")) @toteumien-maara)) (is (true? @vastaus-saatu) "Saatiin vastaus") (is (= (mapv rest tallennettu-varuste) [["HARJ0000000000000002" "tl506" "lisatty" "lahetetty"]])) uusissa nil , tierekisteriin (is (= (:tunniste (first vastaus)) "HARJ0000000000000002")) (doseq [[kentta arvo] (:arvot (first vastaus))] (when (contains? (:arvot toteuma) kentta) (is (= arvo (str (kentta (:arvot toteuma))))))))))) (testing "Varusteen päivittäminen" (let [paivita-tietue-xml (slurp (io/resource "xsd/tierekisteri/esimerkit/ok-vastaus-response.xml")) vastaus-saatu (atom false)] (with-fake-http [(str +testi-tierekisteri-url+ "/paivitatietue") paivita-tietue-xml] (let [toteuma (-> toteuma (update :arvot (fn [arvot] (assoc arvot :lmteksti "foo"))) (assoc :toiminto :paivitetty :tunniste "HARJ0000000000000002")) vastaus (haku-fn {:hakuehdot hakuehdot :toteuma toteuma} vastaus-saatu) _ (odota-ehdon-tayttymista #(true? @vastaus-saatu) "Tierekisteristä saatiin vastaus" 10000) varusteet (q "SELECT luotu, tunniste, tietolaji, toimenpide, tila FROM varustetoteuma WHERE tunniste='HARJ0000000000000002' ORDER BY luotu ASC;")] (swap! toteumien-maara inc) (is (= (count (q "SELECT id FROM toteuma;")) @toteumien-maara)) (is (true? @vastaus-saatu) "Saatiin vastaus") (is (= (mapv rest varusteet) [["HARJ0000000000000002" "tl506" "lisatty" "lahetetty"] ["HARJ0000000000000002" "tl506" "paivitetty" "lahetetty"]])) (is (= (:tunniste (first vastaus)) "HARJ0000000000000002")) (doseq [[kentta arvo] (:arvot (first vastaus))] (when (contains? (:arvot toteuma) kentta) (is (= arvo (str (kentta (:arvot toteuma))))))))))) (testing "Varusteen poistaminen" (let [poista-tietue-xml (slurp (io/resource "xsd/tierekisteri/esimerkit/ok-vastaus-response.xml")) vastaus-saatu (atom false)] (with-fake-http [(str +testi-tierekisteri-url+ "/poistatietue") poista-tietue-xml] (let [toteuma (-> toteuma (update :arvot (fn [arvot] (assoc arvot :lmteksti "foo"))) (assoc :toiminto :poistettu :tunniste "HARJ0000000000000002")) vastaus (haku-fn {:hakuehdot hakuehdot :toteuma toteuma} vastaus-saatu) _ (odota-ehdon-tayttymista #(true? @vastaus-saatu) "Tierekisteristä saatiin vastaus" 10000) varusteet (q "SELECT luotu, tunniste, tietolaji, toimenpide, tila FROM varustetoteuma WHERE tunniste='HARJ0000000000000002' ORDER BY luotu ASC;")] (swap! toteumien-maara inc) (is (= (count (q "SELECT id FROM toteuma;")) @toteumien-maara)) (is (true? @vastaus-saatu) "Saatiin vastaus") (is (= (mapv rest varusteet) [["HARJ0000000000000002" "tl506" "lisatty" "lahetetty"] ["HARJ0000000000000002" "tl506" "paivitetty" "lahetetty"] ["HARJ0000000000000002" "tl506" "poistettu" "lahetetty"]])) (is (= (:tunniste (first vastaus)) "HARJ0000000000000002")))))) (testing "Varusteen epäonnistunut tallentaminen" (let [lisaa-tietue-virhe-xml (slurp (io/resource "xsd/tierekisteri/esimerkit/virhe-tietueen-lisays-epaonnistui-response.xml")) vastaus-saatu (atom false)] (with-fake-http [(str +testi-tierekisteri-url+ "/lisaatietue") lisaa-tietue-virhe-xml] (let [vastaus (haku-fn {:hakuehdot hakuehdot :toteuma toteuma} vastaus-saatu) _ (odota-ehdon-tayttymista #(true? @vastaus-saatu) "Tierekisteristä saatiin vastaus" 10000) tallennettu-varuste (q "SELECT luotu, tunniste, tietolaji, toimenpide, tila, lahetysvirhe FROM varustetoteuma WHERE tunniste='HARJ0000000000000003' ORDER BY luotu DESC;")] (swap! toteumien-maara inc) (is (= (count (q "SELECT id FROM toteuma;")) @toteumien-maara)) (is (true? @vastaus-saatu) "Saatiin vastaus") (is (= (mapv rest tallennettu-varuste) [["HARJ0000000000000003" "tl506" "lisatty" "virhe" "Virheet: Tietueen tiedot ovat puutteelliset"]])) (is (nil? (:tila vastaus))) (is (= (:tunniste (first vastaus)) "HARJ0000000000000003")) (doseq [[kentta arvo] (:arvot (first vastaus))] (when (contains? (:arvot toteuma) kentta) (is (= arvo (str (kentta (:arvot toteuma))))))))))) (testing "Varusteen epäonnistuneen tallentamisen tallentaminen" (let [lisaa-tietue-xml (slurp (io/resource "xsd/tierekisteri/esimerkit/ok-vastaus-response.xml")) vastaus-saatu (atom false)] (with-fake-http [(str +testi-tierekisteri-url+ "/lisaatietue") lisaa-tietue-xml] (let [toteuma (-> toteuma (assoc :tunniste "HARJ0000000000000003" :id (ffirst (q "SELECT id FROM varustetoteuma WHERE tunniste='HARJ0000000000000003'")))) vastaus (haku-fn {:hakuehdot hakuehdot :toteuma toteuma} vastaus-saatu) _ (odota-ehdon-tayttymista #(true? @vastaus-saatu) "Tierekisteristä saatiin vastaus" 10000) tallennettu-varuste (q "SELECT luotu, tunniste, tietolaji, toimenpide, tila, lahetysvirhe FROM varustetoteuma WHERE tunniste='HARJ0000000000000003' ORDER BY luotu DESC;")] (is (= (count (q "SELECT id FROM toteuma;")) @toteumien-maara)) (is (true? @vastaus-saatu) "Saatiin vastaus") (is (= (mapv rest tallennettu-varuste) [["HARJ0000000000000003" "tl506" "lisatty" "lahetetty" nil]])) (is (= (:tunniste (first vastaus)) "HARJ0000000000000003"))))))))) (deftest kokonaishintaisen-toteuman-siirtymatiedot (let [toteuma-id (ffirst (q "SELECT id FROM toteuma WHERE urakka = 2 AND lisatieto = 'Tämä on käsin tekaistu juttu'")) hae #(kutsu-palvelua (:http-palvelin jarjestelma) :siirry-toteuma % toteuma-id) ok-tulos {:alkanut #inst "2008-09-08T21:10:00.000000000-00:00" :urakka-id 2 :tyyppi "kokonaishintainen" :hallintayksikko-id 12 :aikavali {:alku #inst "2007-09-30T21:00:00.000-00:00" :loppu #inst "2008-09-29T21:00:00.000-00:00"} :tehtavat [{:toimenpidekoodi 1350, :toimenpideinstanssi "10100"}]} ei-ok-tulos nil] (is (some? toteuma-id)) ;; JVH voi hakea siirtymätiedot (tarkista-map-arvot ok-tulos (hae +kayttaja-jvh+)) Eri urakoitsijalla palautuu poikkeus oikeustarkistuksessa (is (thrown? Exception (hae +kayttaja-yit_uuvh+))) Toteuman urakan (tarkista-map-arvot ok-tulos (hae +kayttaja-ulle+)))) (deftest toteuman-paivitys-sama-partitiolle (let [urakka-id (hae-urakan-id-nimella "Pudasjärven alueurakka 2007-2012") sopimus-id (hae-pudasjarven-alueurakan-paasopimuksen-id) toteuma-id (ffirst (q (str "SELECT id FROM toteuma WHERE urakka = " urakka-id " AND lisatieto = 'Tämä on käsin tekaistu juttu'"))) toteuma-tehtava-id (ffirst (q (str "SELECT id FROM toteuma_tehtava WHERE toteuma = " toteuma-id ";"))) uusi-tyon-pvm-samassa-partitiossa (konv/sql-timestamp (pvm/luo-pvm 2009 11 24)) ;;24.12.2009 1.10.2016 hoitokausi-lopetuspvm (pvm/luo-pvm 2010 8 30) ;30.9.2017 tyo {:urakka-id urakka-id :sopimus-id sopimus-id :alkanut uusi-tyon-pvm-samassa-partitiossa :paattynyt uusi-tyon-pvm-samassa-partitiossa :reitti {:type :multiline :lines [{:type :line, :points [[426948.180407029 7212765.48225361] [430650.8691 7212578.8262]]}]} :hoitokausi-aloituspvm hoitokausi-aloituspvm :hoitokausi-lopetuspvm hoitokausi-lopetuspvm :suorittajan-nimi "Alihankkijapaja Ky" :suorittajan-ytunnus "123456-Y" :tyyppi :kokonaishintainen :lisatieto "Tämä on käsin tekaistu juttu" :toteuma-id toteuma-id :tehtavat [{:toimenpidekoodi 1368 :maara 333 :tehtava-id toteuma-tehtava-id}]} lisatty (first (kutsu-palvelua (:http-palvelin jarjestelma) :tallenna-urakan-toteuma-ja-kokonaishintaiset-tehtavat +kayttaja-jvh+ {:toteuma tyo :hakuparametrit {:urakka-id urakka-id :sopimus-id sopimus-id :alkupvm hoitokausi-aloituspvm :loppupvm hoitokausi-lopetuspvm :toimenpide nil :tehtava nil}})) toteuma-id-jalkeen (ffirst (q (str "SELECT id FROM toteuma WHERE urakka = " urakka-id " AND lisatieto = 'Tämä on käsin tekaistu juttu'")))] (is (= toteuma-id toteuma-id-jalkeen) "Toteuman id ei saa muuttua") (is (= (get-in lisatty [:pvm]) uusi-tyon-pvm-samassa-partitiossa) "Tallennetun työn alkanut pvm") (is (= (get-in lisatty [:jarjestelmanlisaama]) false)) (is (= (get-in lisatty [:nimi]) "Pistehiekoitus")) (is (= (get-in lisatty [:yksikko]) "tiekm") "Yksikkö") (is (= (get-in lisatty [:toimenpidekoodi]) 1368) "Tallennetun työn tehtävän toimenpidekoodi") (is (= (get-in lisatty [:maara]) 333M) "Tallennetun työn tehtävän määrä"))) (deftest toteuman-paivitys-siirtaa-eri-partitiolle (let [urakka-id (hae-urakan-id-nimella "Pudasjärven alueurakka 2007-2012") sopimus-id (hae-pudasjarven-alueurakan-paasopimuksen-id) toteuma-id (ffirst (q (str "SELECT id FROM toteuma WHERE urakka = " urakka-id " AND lisatieto = 'Tämä on käsin tekaistu juttu'"))) toteuma-tehtava-id (ffirst (q (str "SELECT id FROM toteuma_tehtava WHERE toteuma = " toteuma-id ";"))) 24.12.2020 hoitokausi-aloituspvm (pvm/luo-pvm 2020 9 1) hoitokausi-lopetuspvm (pvm/luo-pvm 2021 8 30) ;30.9.2017 tyo {:urakka-id urakka-id :sopimus-id sopimus-id :alkanut uusi-tyon-pvm-eri-partitiossa :paattynyt uusi-tyon-pvm-eri-partitiossa :reitti {:type :multiline :lines [{:type :line, :points [[426948.180407029 7212765.48225361] [430650.8691 7212578.8262]]}]} :hoitokausi-aloituspvm hoitokausi-aloituspvm :hoitokausi-lopetuspvm hoitokausi-lopetuspvm :suorittajan-nimi "Alihankkijapaja Ky" :suorittajan-ytunnus "123456-Y" :tyyppi :kokonaishintainen :lisatieto "Tämä on käsin tekaistu juttu" :toteuma-id toteuma-id :tehtavat [{:toimenpidekoodi 1368 :maara 444 :tehtava-id toteuma-tehtava-id}]} kaikki (kutsu-palvelua (:http-palvelin jarjestelma) :tallenna-urakan-toteuma-ja-kokonaishintaiset-tehtavat +kayttaja-jvh+ {:toteuma tyo :hakuparametrit {:urakka-id urakka-id :sopimus-id sopimus-id :alkupvm hoitokausi-aloituspvm :loppupvm hoitokausi-lopetuspvm :toimenpide nil :tehtava nil}}) lisatty (some #(when (= (:toimenpidekoodi %) 1368) %) kaikki) toteuma-id-jalkeen (ffirst (q (str "SELECT id FROM toteuma WHERE urakka = " urakka-id " AND lisatieto = 'Tämä on käsin tekaistu juttu'")))] (is (= toteuma-id toteuma-id-jalkeen) "Toteuman id ei saa muuttua") (is (= (get-in lisatty [:pvm]) uusi-tyon-pvm-eri-partitiossa) "Tallennetun työn alkanut pvm") (is (= (get-in lisatty [:pvm]) uusi-tyon-pvm-eri-partitiossa) "Tallennetun työn alkanut pvm") (is (= (get-in lisatty [:jarjestelmanlisaama]) false)) (is (= (get-in lisatty [:nimi]) "Pistehiekoitus")) (is (= (get-in lisatty [:yksikko]) "tiekm") "Yksikkö") (is (= (get-in lisatty [:toimenpidekoodi]) 1368) "Tallennetun työn tehtävän toimenpidekoodi") (is (= (get-in lisatty [:maara]) 444M) "Tallennetun työn tehtävän määrä"))) (defn luo-testitoteuma [urakka-id sopimus-id alkanut toteuma-id] {:sopimus sopimus-id :alkanut (konv/sql-date alkanut) :paattynyt (konv/sql-date alkanut) :reitti {:type :multiline :lines [{:type :line, :points [[426948.180407029 7212765.48225361] [430650.8691 7212578.8262]]}]} :id toteuma-id :alkuosa 1 :numero 4 :alkuetaisyys 1 :kayttaja 1 :ytunnus "123456-Y" :urakka urakka-id :suorittaja "Alihankkijapaja Ky" :loppuetaisyys 2 :loppuosa 2 :tyyppi "kokonaishintainen" :lisatieto "Tämä on käsin tekaistu juttu"}) (deftest toteuman-paivitys-ei-muuta-lukumaaraa (let [toteuma-count (ffirst (q (str "SELECT count(id) FROM toteuma"))) urakka-id (hae-urakan-id-nimella "Pudasjärven alueurakka 2007-2012") sopimus-id (hae-pudasjarven-alueurakan-paasopimuksen-id) toteuma-id (ffirst (q (str "SELECT id FROM toteuma WHERE urakka = " urakka-id " AND lisatieto = 'Tämä on käsin tekaistu juttu'")))] Satunnaisia päivämääriä vuosina 2000 - 2030 ... ( myös ) (doseq [alkanut (map #(pvm/->pvm (str (rand-int 28) "." (rand-int 170) "." %)) (range 2000 2030))] (do (toteumat-q/paivita-toteuma<! (:db jarjestelma) (luo-testitoteuma urakka-id sopimus-id alkanut toteuma-id)) (is (= toteuma-id (ffirst (q (str "SELECT id FROM toteuma WHERE urakka = " urakka-id " AND lisatieto = 'Tämä on käsin tekaistu juttu'")))) "Toteuma id ei saa muuttua.") (is (= alkanut (ffirst (q (str "SELECT alkanut FROM toteuma WHERE urakka = " urakka-id " AND lisatieto = 'Tämä on käsin tekaistu juttu'")))) "Toteuma alkanut OK") (is (= toteuma-count (ffirst (q (str "SELECT count(id) FROM toteuma")))) "Toteuma count ei saa muuttua."))))) (deftest hae-urakan-kokonaishintaisten-toteumien-tehtavien-paivakohtaiset-summat (let [urakka-id (hae-oulun-alueurakan-2014-2019-id) sopimus-id (hae-oulun-alueurakan-2014-2019-paasopimuksen-id) talvihoito-tpi-id (hae-oulun-alueurakan-talvihoito-tpi-id) odotettu [{:pvm #inst "2017-01-31T22:00:00.000-00:00", :toimenpidekoodi 1369, :maara 666M, :jarjestelmanlisaama true, :nimi "Suolaus", :yksikko "tiekm"} {:pvm #inst "2015-01-31T22:00:00.000-00:00", :toimenpidekoodi 1369, :maara 123M, :jarjestelmanlisaama true, :nimi "Suolaus", :yksikko "tiekm"}] vastaus (kutsu-palvelua (:http-palvelin jarjestelma) :hae-urakan-kokonaishintaisten-toteumien-tehtavien-paivakohtaiset-summat +kayttaja-jvh+ {:urakka-id urakka-id :sopimus-id sopimus-id :alkupvm (pvm/->pvm "1.10.2014") :loppupvm (pvm/->pvm "1.1.2018") :toimenpide talvihoito-tpi-id :tehtava nil})] (is (= odotettu vastaus) "hae-urakan-kokonaishintaisten-toteumien-tehtavien-paivakohtaiset-summat oikein")))
null
https://raw.githubusercontent.com/finnishtransportagency/harja/624f72c2dcd408fbf4acc3305fd0472e5afb341d/test/clj/harja/palvelin/palvelut/toteumat_test.clj
clojure
Testaa päivittämistä Testaa poistetuksi merkitsemistä "))) Testaa päivitys Testaa päivitys ")) 1.10.2020 30.9.2021 (not (circleci?)) on tekaistu) JVH voi hakea siirtymätiedot 24.12.2009 30.9.2017 30.9.2017
(ns harja.palvelin.palvelut.toteumat-test (:require [clojure.test :refer :all] [clojure.java.io :as io] [com.stuartsierra.component :as component] [harja [pvm :as pvm] [testi :refer :all]] [harja.kyselyt.konversio :as konv] [harja.kyselyt.toteumat :as toteumat-q] [harja.palvelin.komponentit.tietokanta :as tietokanta] [harja.palvelin.palvelut.toteumat :refer :all] [harja.tyokalut.functor :refer [fmap]] [taoensso.timbre :as log] [org.httpkit.fake :refer [with-fake-http]] [harja.palvelin.palvelut.toteumat :as toteumat] [harja.palvelin.palvelut.tehtavamaarat :as tehtavamaarat] [harja.palvelin.palvelut.karttakuvat :as karttakuvat] [harja.palvelin.integraatiot.integraatioloki :as integraatioloki] [harja.palvelin.integraatiot.tierekisteri.tierekisteri-komponentti :as tierekisteri] [harja.domain.tierekisteri.varusteet :as varusteet-domain])) (def +testi-tierekisteri-url+ "harja.testi.tierekisteri") (def +oikea-testi-tierekisteri-url+ "-test.solitaservices.fi/harja/integraatiotesti/tierekisteri") (defn jarjestelma-fixture [testit] (alter-var-root #'jarjestelma (fn [_] (let [tietokanta (tietokanta/luo-tietokanta testitietokanta)] (component/start (component/system-map :db tietokanta :db-replica tietokanta :http-palvelin (testi-http-palvelin) :karttakuvat (component/using (karttakuvat/luo-karttakuvat) [:http-palvelin :db]) :integraatioloki (component/using (integraatioloki/->Integraatioloki nil) [:db]) :tierekisteri (component/using (tierekisteri/->Tierekisteri +testi-tierekisteri-url+ nil) [:db :integraatioloki]) :toteumat (component/using (toteumat/->Toteumat) [:http-palvelin :db :db-replica :karttakuvat :tierekisteri]) :tehtavamaarat (component/using (tehtavamaarat/->Tehtavamaarat) [:http-palvelin :db])))))) (testit) (alter-var-root #'jarjestelma component/stop)) (use-fixtures :once (compose-fixtures jarjestelma-fixture urakkatieto-fixture)) käyttää testidata.sql : (deftest erilliskustannukset-haettu-oikein (let [alkupvm (pvm/luo-pvm 2005 9 1) loppupvm (pvm/luo-pvm 2006 10 30) res (kutsu-palvelua (:http-palvelin jarjestelma) :urakan-erilliskustannukset +kayttaja-jvh+ {:urakka-id @oulun-alueurakan-2005-2010-id :alkupvm alkupvm :loppupvm loppupvm}) oulun-alueurakan-toiden-lkm (ffirst (q (str "SELECT count(*) FROM erilliskustannus WHERE sopimus IN (SELECT id FROM sopimus WHERE urakka = " @oulun-alueurakan-2005-2010-id ") AND pvm >= '2005-10-01' AND pvm <= '2006-09-30'")))] (is (= (count res) oulun-alueurakan-toiden-lkm) "Erilliskustannusten määrä"))) (deftest tallenna-erilliskustannus-testi 1.10.2005 30.9.2006 toteuman-pvm (pvm/luo-pvm 2005 11 12) toteuman-lisatieto "Testikeissin lisätieto" ek {:urakka-id @oulun-alueurakan-2005-2010-id :alkupvm hoitokauden-alkupvm :loppupvm hoitokauden-loppupvm :pvm toteuman-pvm :rahasumma 20000.0 :indeksin_nimi "MAKU 2005" :toimenpideinstanssi 1 :sopimus 1 :tyyppi "asiakastyytyvaisyysbonus" :lisatieto toteuman-lisatieto} maara-ennen-lisaysta (ffirst (q (str "SELECT count(*) FROM erilliskustannus WHERE sopimus IN (SELECT id FROM sopimus WHERE urakka = " @oulun-alueurakan-2005-2010-id ") AND pvm >= '2005-10-01' AND pvm <= '2006-09-30'"))) vastaus (kutsu-palvelua (:http-palvelin jarjestelma) :tallenna-erilliskustannus +kayttaja-jvh+ ek) lisatty (first (filter #(and (= (:pvm %) toteuman-pvm) (= (:lisatieto %) toteuman-lisatieto)) vastaus))] (is (= (:pvm lisatty) toteuman-pvm) "Tallennetun erilliskustannuksen pvm") (is (= (:lisatieto lisatty) toteuman-lisatieto) "Tallennetun erilliskustannuksen lisätieto") (is (= (:indeksin_nimi lisatty) "MAKU 2005") "Tallennetun erilliskustannuksen indeksin nimi") (is (= (:rahasumma lisatty) 20000.0) "Tallennetun erilliskustannuksen pvm") (is (= (:urakka lisatty) @oulun-alueurakan-2005-2010-id) "Oikea urakka") (is (= (:toimenpideinstanssi lisatty) 1) "Tallennetun erilliskustannuksen tp") (is (= (count vastaus) (+ 1 maara-ennen-lisaysta)) "Tallennuksen jälkeen erilliskustannusten määrä") (let [ek-id (:id lisatty) vastaus (kutsu-palvelua (:http-palvelin jarjestelma) :tallenna-erilliskustannus +kayttaja-jvh+ (assoc ek :id ek-id :indeksin_nimi "MAKU 2010")) paivitetty (first (filter #(= (:id %) ek-id) vastaus))] (is (= (:indeksin_nimi paivitetty) "MAKU 2010") "Tallennetun erilliskustannuksen indeksin nimi")) Testaa virheellinen urakka (let [ek-id (:id lisatty) _ (is (thrown? SecurityException (kutsu-palvelua (:http-palvelin jarjestelma) :tallenna-erilliskustannus +kayttaja-jvh+ (assoc ek :id ek-id :indeksin_nimi "MAKSU 2015" :urakka-id @oulun-alueurakan-2014-2019-id)))) urakka (ffirst (q (str "SELECT urakka FROM erilliskustannus WHERE id = " ek-id ";"))) indeksin-nimi (ffirst (q (str "SELECT indeksin_nimi FROM erilliskustannus WHERE id = " ek-id ";")))] (is (= urakka @oulun-alueurakan-2005-2010-id) "Virheellistä urakkaa ei päivitetty") (is (= indeksin-nimi "MAKU 2010") "Virheellistä indeksiä ei päivitetty")) (let [ek-id (:id lisatty) poistettu-id (kutsu-palvelua (:http-palvelin jarjestelma) :poista-erilliskustannus +kayttaja-jvh+ {:id ek-id :urakka-id @oulun-alueurakan-2005-2010-id}) poistettu? (ffirst (q (str "SELECT poistettu FROM erilliskustannus WHERE id = " ek-id ";")))] (is (= poistettu-id ek-id) "Poistetun erilliskustannuksen id") (is (= poistettu? true))) (u (str "DELETE FROM erilliskustannus WHERE pvm = '2005-12-12' AND lisatieto = '" toteuman-lisatieto "'")))) (deftest tallenna-muut-tyot-toteuma-testi 24.12.2005 1.10.2005 30.9.2006 toteuman-lisatieto "Testikeissin lisätieto2" tyo {:urakka-id @oulun-alueurakan-2005-2010-id :sopimus-id @oulun-alueurakan-2005-2010-paasopimuksen-id :alkanut tyon-pvm :paattynyt tyon-pvm :hoitokausi-aloituspvm hoitokausi-aloituspvm :hoitokausi-lopetuspvm hoitokausi-lopetuspvm :suorittajan-nimi "Alihankkijapaja Ky" :suorittajan-ytunnus "123456-Y" :tyyppi :muutostyo :lisatieto toteuman-lisatieto :tehtava {:paivanhinta 456, :maara 2, :toimenpidekoodi 1368}} maara-ennen-lisaysta (ffirst (q (str "SELECT count(*) FROM toteuma WHERE urakka = " @oulun-alueurakan-2005-2010-id " AND sopimus = " @oulun-alueurakan-2005-2010-paasopimuksen-id " AND tyyppi IN ('muutostyo', 'lisatyo', 'akillinen-hoitotyo', 'vahinkojen-korjaukset') AND alkanut >= to_date('1-10-2005', 'DD-MM-YYYY') vastaus (kutsu-palvelua (:http-palvelin jarjestelma) :tallenna-muiden-toiden-toteuma +kayttaja-jvh+ tyo) lisatty (first (filter #(and (= (:lisatieto %) toteuman-lisatieto)) vastaus))] (is (= (count vastaus) (+ 1 maara-ennen-lisaysta)) "Tallennuksen jälkeen muiden töiden määrä") (is (= (:alkanut lisatty) tyon-pvm) "Tallennetun muun työn alkanut pvm") (is (= (:paattynyt lisatty) tyon-pvm) "Tallennetun muun työn paattynyt pvm") (is (= (:tyyppi lisatty) :muutostyo) "Tallennetun muun työn tyyppi") (is (= (:lisatieto lisatty) toteuman-lisatieto) "Tallennetun erilliskustannuksen lisätieto") (is (= (get-in lisatty [:tehtava :paivanhinta]) 456.0) "Tallennetun muun työn päivänhinta") (is (= (get-in lisatty [:tehtava :maara]) 2.0) "Tallennetun muun työn määrä") (is (= (get-in lisatty [:tehtava :toimenpidekoodi]) 1368) "Tallennetun muun työn toimenpidekoodi") (let [toteuma-id (get-in lisatty [:toteuma :id]) vastaus (kutsu-palvelua (:http-palvelin jarjestelma) :tallenna-muiden-toiden-toteuma +kayttaja-jvh+ (assoc tyo :toteuma {:id toteuma-id} :lisatieto "Testikeissi")) paivitetty (first (filter #(= (get-in % [:toteuma :id]) toteuma-id) vastaus))] (is (= (:lisatieto paivitetty) "Testikeissi") "Päivitetyn erilliskustannuksen lisätieto")) Testaa virheellinen urakka (try (let [toteuma-id (get-in lisatty [:toteuma :id]) _ (kutsu-palvelua (:http-palvelin jarjestelma) :tallenna-muiden-toiden-toteuma +kayttaja-jvh+ (assoc tyo :toteuma {:id toteuma-id} :urakka-id @oulun-alueurakan-2014-2019-id))]) (is false "Päivitys sallittiin virheellisesti") (catch Exception e (is true "Päivitystä ei sallittu"))) lisätyt rivit pois (u (str "DELETE FROM toteuma_tehtava WHERE toteuma = " (get-in lisatty [:toteuma :id]))) (u (str "DELETE FROM toteuma WHERE id = " (get-in lisatty [:toteuma :id]))))) (deftest tallenna-yksikkohintainen-toteuma-testi 24.12.2005 1.10.2005 30.9.2006 urakka-id @oulun-alueurakan-2005-2010-id toteuman-lisatieto "Testikeissin lisätieto4" tyo {:urakka-id urakka-id :sopimus-id @oulun-alueurakan-2005-2010-paasopimuksen-id :alkanut tyon-pvm :paattynyt tyon-pvm :hoitokausi-aloituspvm hoitokausi-aloituspvm :hoitokausi-lopetuspvm hoitokausi-lopetuspvm :suorittajan-nimi "Alihankkijapaja Ky" :suorittajan-ytunnus "123456-Y" :tyyppi :yksikkohintainen :toteuma-id nil :lisatieto toteuman-lisatieto :tehtavat [{:toimenpidekoodi 1368 :maara 333}]} hae-summat #(->> (kutsu-palvelua (:http-palvelin jarjestelma) :urakan-toteumien-tehtavien-summat +kayttaja-jvh+ {:urakka-id urakka-id :sopimus-id @oulun-alueurakan-2005-2010-paasopimuksen-id :alkupvm hoitokausi-aloituspvm :loppupvm hoitokausi-lopetuspvm :tyyppi :yksikkohintainen}) (group-by :tpk_id) (fmap first)) summat-ennen-lisaysta (hae-summat)] (is (not (contains? summat-ennen-lisaysta 1368))) (let [_ (println "tyo ::::::::::::::::." (pr-str tyo)) lisatty (kutsu-palvelua (:http-palvelin jarjestelma) :tallenna-urakan-toteuma-ja-yksikkohintaiset-tehtavat +kayttaja-jvh+ tyo) summat-lisayksen-jalkeen (hae-summat)] (is (= (get-in lisatty [:toteuma :alkanut]) tyon-pvm) "Tallennetun työn alkanut pvm") (is (= (get-in lisatty [:toteuma :paattynyt]) tyon-pvm) "Tallennetun työn paattynyt pvm") (is (= (get-in lisatty [:toteuma :lisatieto]) toteuman-lisatieto) "Tallennetun työn lisätieto") (is (= (get-in lisatty [:toteuma :suorittajan-nimi]) "Alihankkijapaja Ky") "Tallennetun työn suorittajan nimi") (is (= (get-in lisatty [:toteuma :suorittajan-ytunnus]) "123456-Y") "Tallennetun työn suorittajan y-tunnus") (is (= (get-in lisatty [:toteuma :urakka-id]) urakka-id) "Tallennetun työn urakan id") (is (= (get-in lisatty [:toteuma :sopimus-id]) @oulun-alueurakan-2005-2010-paasopimuksen-id) "Tallennetun työn pääsopimuksen id") (is (= (get-in lisatty [:toteuma :tehtavat 0 :toimenpidekoodi]) 1368) "Tallennetun työn tehtävän toimenpidekoodi") (is (= (get-in lisatty [:toteuma :tehtavat 0 :maara]) 333) "Tallennetun työn tehtävän määrä") (is (= (get-in lisatty [:toteuma :tyyppi]) :yksikkohintainen) "Tallennetun työn toteuman tyyppi") (is (== 333 (get-in summat-lisayksen-jalkeen [1368 :maara]))) (let [toteuma-id (get-in lisatty [:toteuma :toteuma-id]) toteuma (kutsu-palvelua (:http-palvelin jarjestelma) :urakan-toteuma +kayttaja-jvh+ {:urakka-id urakka-id :toteuma-id toteuma-id}) muokattu-tyo (assoc tyo :toteuma-id toteuma-id :tehtavat [{:toimenpidekoodi 1369 :maara 666 :tehtava-id (get-in toteuma [:tehtavat 0 :tehtava-id])}]) muokattu (kutsu-palvelua (:http-palvelin jarjestelma) :tallenna-urakan-toteuma-ja-yksikkohintaiset-tehtavat +kayttaja-jvh+ muokattu-tyo) summat-muokkauksen-jalkeen (hae-summat)] (is (= (get-in muokattu [:toteuma :tehtavat 0 :toimenpidekoodi]) 1369)) (is (= (get-in muokattu [:toteuma :tehtavat 0 :maara]) 666)) (is (= 1 (count (get-in muokattu [:toteuma :tehtavat])))) (is (not (contains? summat-muokkauksen-jalkeen 1368))) (is (== 666 (get-in summat-muokkauksen-jalkeen [1369 :maara]))) Testaa päivitys (try (kutsu-palvelua (:http-palvelin jarjestelma) :tallenna-urakan-toteuma-ja-yksikkohintaiset-tehtavat +kayttaja-jvh+ (assoc muokattu-tyo :urakka-id @muhoksen-paallystysurakan-id)) (is false "Virheellisesti sallittiin päivittää väärällä urakka-id:llä") (catch Exception e (is true "Ei sallittu päivittää väärällä urakka-id:llä"))) (u (str "DELETE FROM toteuma_tehtava (u (str "DELETE FROM toteuma WHERE id = " toteuma-id)))))) (deftest tallenna-yksikkohintainen-toteuma-ja-poista-tehtava-testi 24.12.2005 1.10.2005 30.9.2006 urakka-id @oulun-alueurakan-2005-2010-id toteuman-lisatieto "Testikeissin lisätieto4" tyo {:urakka-id urakka-id :sopimus-id @oulun-alueurakan-2005-2010-paasopimuksen-id :alkanut tyon-pvm :paattynyt tyon-pvm :hoitokausi-aloituspvm hoitokausi-aloituspvm :hoitokausi-lopetuspvm hoitokausi-lopetuspvm :suorittajan-nimi "Alihankkijapaja Ky" :suorittajan-ytunnus "123456-Y" :tyyppi :yksikkohintainen :toteuma-id nil :lisatieto toteuman-lisatieto :tehtavat [{:toimenpidekoodi 1368 :maara 333}]} hae-summat #(->> (kutsu-palvelua (:http-palvelin jarjestelma) :urakan-toteumien-tehtavien-summat +kayttaja-jvh+ {:urakka-id urakka-id :sopimus-id @oulun-alueurakan-2005-2010-paasopimuksen-id :alkupvm hoitokausi-aloituspvm :loppupvm hoitokausi-lopetuspvm :tyyppi :yksikkohintainen}) (group-by :tpk_id) (fmap first)) summat-ennen-lisaysta (hae-summat)] (is (not (contains? summat-ennen-lisaysta 1368))) (let [_ (println "tyo ::::::::::::::::." (pr-str tyo)) lisatty (kutsu-palvelua (:http-palvelin jarjestelma) :tallenna-urakan-toteuma-ja-yksikkohintaiset-tehtavat +kayttaja-jvh+ tyo) summat-lisayksen-jalkeen (hae-summat)] (is (= (get-in lisatty [:toteuma :alkanut]) tyon-pvm) "Tallennetun työn alkanut pvm") (is (= (get-in lisatty [:toteuma :paattynyt]) tyon-pvm) "Tallennetun työn paattynyt pvm") (is (= (get-in lisatty [:toteuma :lisatieto]) toteuman-lisatieto) "Tallennetun työn lisätieto") (is (= (get-in lisatty [:toteuma :suorittajan-nimi]) "Alihankkijapaja Ky") "Tallennetun työn suorittajan nimi") (is (= (get-in lisatty [:toteuma :suorittajan-ytunnus]) "123456-Y") "Tallennetun työn suorittajan y-tunnus") (is (= (get-in lisatty [:toteuma :urakka-id]) urakka-id) "Tallennetun työn urakan id") (is (= (get-in lisatty [:toteuma :sopimus-id]) @oulun-alueurakan-2005-2010-paasopimuksen-id) "Tallennetun työn pääsopimuksen id") (is (= (get-in lisatty [:toteuma :tehtavat 0 :toimenpidekoodi]) 1368) "Tallennetun työn tehtävän toimenpidekoodi") (is (= (get-in lisatty [:toteuma :tehtavat 0 :maara]) 333) "Tallennetun työn tehtävän määrä") (is (= (get-in lisatty [:toteuma :tyyppi]) :yksikkohintainen) "Tallennetun työn toteuman tyyppi") (is (== 333 (get-in summat-lisayksen-jalkeen [1368 :maara]))) Testaa (let [toteuma-id (get-in lisatty [:toteuma :toteuma-id]) toteuma (kutsu-palvelua (:http-palvelin jarjestelma) :urakan-toteuma +kayttaja-jvh+ {:urakka-id urakka-id :toteuma-id toteuma-id}) muokattu-tyo (assoc tyo :toteuma-id toteuma-id :tehtavat [{:toimenpidekoodi 1368 :maara 333 :poistettu true :tehtava-id (get-in toteuma [:tehtavat 0 :tehtava-id])} {:toimenpidekoodi 1369 :maara 333}]) muokattu (kutsu-palvelua (:http-palvelin jarjestelma) :tallenna-urakan-toteuma-ja-yksikkohintaiset-tehtavat +kayttaja-jvh+ muokattu-tyo) summat-muokkauksen-jalkeen (hae-summat)] (is (= (get-in muokattu [:toteuma :tehtavat 1 :toimenpidekoodi]) 1369)) (is (= (get-in muokattu [:toteuma :tehtavat 1 :maara]) 333)) (is (not (contains? summat-muokkauksen-jalkeen 1368))) (is (== 333 (get-in summat-muokkauksen-jalkeen [1369 :maara]))) (u (str "DELETE FROM toteuma_tehtava WHERE toteuma = " toteuma-id ";")) (u (str "DELETE FROM toteuma WHERE id = " toteuma-id)))))) (deftest tallenna-kokonaishintainen-toteuma-testi 24.12.2020 urakka-id (hae-oulun-alueurakan-2014-2019-id) tyo {:urakka-id urakka-id :sopimus-id (hae-oulun-alueurakan-2014-2019-paasopimuksen-id) :alkanut tyon-pvm :paattynyt tyon-pvm :reitti {:type :multiline :lines [{:type :line, :points [[426948.180407029 7212765.48225361] [430650.8691 7212578.8262]]}]} :hoitokausi-aloituspvm hoitokausi-aloituspvm :hoitokausi-lopetuspvm hoitokausi-lopetuspvm :suorittajan-nimi "Alihankkijapaja Ky" :suorittajan-ytunnus "123456-Y" :tyyppi :kokonaishintainen :toteuma-id nil :tehtavat [{:toimenpidekoodi 1368 :maara 333}]} lisatty (some #(when (= (:toimenpidekoodi %) 1368) %) (kutsu-palvelua (:http-palvelin jarjestelma) :tallenna-urakan-toteuma-ja-kokonaishintaiset-tehtavat +kayttaja-jvh+ {:toteuma tyo :hakuparametrit {:urakka-id urakka-id :sopimus-id (hae-oulun-alueurakan-2014-2019-paasopimuksen-id) :alkupvm hoitokausi-aloituspvm :loppupvm hoitokausi-lopetuspvm :toimenpide nil :tehtava nil}}))] (is (= (get-in lisatty [:pvm]) tyon-pvm) "Tallennetun työn alkanut pvm") (is (= (get-in lisatty [:jarjestelmanlisaama]) false)) (is (= (get-in lisatty [:nimi]) "Pistehiekoitus")) (is (= (get-in lisatty [:yksikko]) "tiekm") "Yksikkö") (is (= (get-in lisatty [:toimenpidekoodi]) 1368) "Tallennetun työn tehtävän toimenpidekoodi") (is (= (get-in lisatty [:maara]) 333M) "Tallennetun työn tehtävän määrä"))) (deftest hae-urakan-toteuma-kun-toteuma-ei-kuulu-urakkaan (let [toteuma-id (ffirst (q "SELECT id FROM toteuma WHERE urakka != " @oulun-alueurakan-2014-2019-id " AND tyyppi = 'yksikkohintainen' LIMIT 1;"))] (is (thrown? SecurityException (kutsu-palvelua (:http-palvelin jarjestelma) :urakan-toteuma +kayttaja-jvh+ {:urakka-id @oulun-alueurakan-2014-2019-id :toteuma-id toteuma-id}))))) (deftest tallenna-toteuma-ja-toteumamateriaalit-test (let [[urakka sopimus] (first (q (str "SELECT urakka, id FROM sopimus WHERE urakka=" @oulun-alueurakan-2005-2010-id))) toteuma (atom {:id -5, :urakka urakka :sopimus sopimus :alkanut (pvm/luo-pvm 2005 11 24) :paattynyt (pvm/luo-pvm 2005 11 24) :tyyppi "yksikkohintainen" :suorittajan-nimi "UNIT TEST" :suorittajan-ytunnus 1234 :lisatieto "Unit test teki tämän"}) tmt (atom [{:id -1 :materiaalikoodi 1 :maara 192837} {:materiaalikoodi 1 :maara 192837}]) sopimuksen-kaytetty-materiaali-ennen (q (str "SELECT alkupvm, materiaalikoodi, maara FROM sopimuksen_kaytetty_materiaali WHERE sopimus = " sopimus))] tarkistetaan että kaikki cachesta palautetut expected - setistä (is (= true (every? #(some? ((set [[#inst "2005-09-30T21:00:00.000-00:00" 1 7M] [#inst "2005-09-30T21:00:00.000-00:00" 4 9M] [#inst "2005-09-30T21:00:00.000-00:00" 2 4M] [#inst "2005-09-30T21:00:00.000-00:00" 3 3M] [#inst "2004-10-19T21:00:00.000-00:00" 5 25M]]) %)) sopimuksen-kaytetty-materiaali-ennen))) (is (= 0 (ffirst (q "SELECT count(*) FROM toteuma_materiaali WHERE maara=192837 AND poistettu IS NOT TRUE")))) (is (= 0 (ffirst (q "SELECT count(*) FROM toteuma WHERE suorittajan_nimi='UNIT TEST' AND poistettu IS NOT TRUE")))) (is (nil? (kutsu-palvelua (:http-palvelin jarjestelma) :tallenna-toteuma-ja-toteumamateriaalit +kayttaja-jvh+ {:toteuma @toteuma :toteumamateriaalit @tmt pvm / luo - pvm 2006 8 30 ) ] :sopimus sopimus}))) (let [tmidt (flatten (q "SELECT id FROM toteuma_materiaali WHERE maara=192837")) tid (ffirst (q "SELECT id from toteuma WHERE suorittajan_nimi='UNIT TEST'")) uusi-lisatieto "NYT PITÄIS OLLA MUUTTUNUT." sopimuksen-kaytetty-materiaali-jalkeen (q (str "SELECT alkupvm, materiaalikoodi, maara FROM sopimuksen_kaytetty_materiaali WHERE sopimus = " sopimus))] tarkistetaan että kaikki cachesta palautetut expected - setistä (is (= true (every? #(some? ((set [[#inst "2005-09-30T21:00:00.000-00:00" 1 7M] [#inst "2005-09-30T21:00:00.000-00:00" 4 9M] [#inst "2005-09-30T21:00:00.000-00:00" 2 4M] [#inst "2005-09-30T21:00:00.000-00:00" 3 3M] [#inst "2004-10-19T21:00:00.000-00:00" 5 25M] [#inst "2005-12-23T22:00:00.000-00:00" 1 385674M]]) %)) sopimuksen-kaytetty-materiaali-jalkeen))) (is (= 2 (ffirst (q "SELECT count(*) FROM toteuma_materiaali WHERE maara=192837 AND poistettu IS NOT TRUE")))) (is (= 1 (ffirst (q "SELECT count(*) FROM toteuma WHERE suorittajan_nimi='UNIT TEST' AND poistettu IS NOT TRUE")))) (reset! tmt [(-> (assoc (first @tmt) :id (first tmidt)) (assoc :poistettu true)) (-> (assoc (second @tmt) :id (second tmidt)) (assoc :maara 8712))]) (reset! toteuma (-> (assoc @toteuma :id tid) (assoc :lisatieto uusi-lisatieto))) (is (not (nil? (kutsu-palvelua (:http-palvelin jarjestelma) :tallenna-toteuma-ja-toteumamateriaalit +kayttaja-jvh+ {:toteuma @toteuma :toteumamateriaalit @tmt :hoitokausi [(pvm/luo-pvm 2005 9 1) (pvm/luo-pvm 2006 8 30)] :sopimus sopimus})))) (is (= 1 (ffirst (q "SELECT count(*) FROM toteuma WHERE suorittajan_nimi='UNIT TEST' AND poistettu IS NOT TRUE")))) (is (= 1 (ffirst (q "SELECT count(*) FROM toteuma_materiaali WHERE maara=192837 AND poistettu IS TRUE")))) (is (= 1 (ffirst (q "SELECT count(*) FROM toteuma_materiaali WHERE maara=8712 AND poistettu IS NOT TRUE")))) (is (= uusi-lisatieto (ffirst (q "SELECT lisatieto FROM toteuma WHERE id=" tid)))) (is (= 8712 (int (ffirst (q "SELECT maara FROM toteuma_materiaali WHERE id=" (second tmidt)))))) (u "DELETE FROM toteuma_materiaali WHERE id in (" (clojure.string/join "," tmidt) ")") (u "DELETE FROM toteuma WHERE id=" tid)))) (deftest materiaalin-pvm-muuttuu-cachet-pysyy-jiirissa (let [urakka-id (hae-oulun-alueurakan-2014-2019-id) sopimus-id (hae-oulun-alueurakan-2014-2019-paasopimuksen-id) sopimuksen-kaytetty-mat-ennen-odotettu (set [[2 #inst "2015-02-17T22:00:00.000-00:00" 1 1800M] [2 #inst "2015-02-18T22:00:00.000-00:00" 7 200M] [2 #inst "2015-02-18T22:00:00.000-00:00" 16 2000M]]) sopimuksen-kaytetty-mat-jalkeen-odotettu (set [[2 #inst "2015-02-17T22:00:00.000-00:00" 1 1800M] [2 #inst "2015-02-18T22:00:00.000-00:00" 7 200M] [2 #inst "2015-02-13T22:00:00.000-00:00" 16 2100M]]) hoitoluokittaiset-ennen-odotettu (set [[#inst "2015-02-17T22:00:00.000-00:00" 1 99 4 1800M] [#inst "2015-02-18T22:00:00.000-00:00" 7 99 4 200M] [#inst "2015-02-18T22:00:00.000-00:00" 16 99 4 2000M]]) hoitoluokittaiset-jalkeen-odotettu (set [[#inst "2015-02-17T22:00:00.000-00:00" 1 99 4 1800M] [#inst "2015-02-18T22:00:00.000-00:00" 7 99 4 200M] [#inst "2015-02-13T22:00:00.000-00:00" 16 99 4 2100M]]) sopimuksen-mat-kaytto-ennen (set (q (str "SELECT sopimus, alkupvm, materiaalikoodi, maara FROM sopimuksen_kaytetty_materiaali WHERE sopimus = " sopimus-id (pvm-vali-sql-tekstina "alkupvm" "'2015-02-01' AND '2015-02-28'") ";"))) hoitoluokittaiset-ennen (set (q (str "SELECT pvm, materiaalikoodi, talvihoitoluokka, urakka, maara FROM urakan_materiaalin_kaytto_hoitoluokittain WHERE urakka = " urakka-id (pvm-vali-sql-tekstina "pvm" "'2015-02-01' AND '2015-02-28'") ";"))) toteuman-id (ffirst (q (str "SELECT id FROM toteuma WHERE lisatieto = 'LYV-toteuma Natriumformiaatti';"))) tm-id (ffirst (q (str "SELECT id FROM toteuma_materiaali WHERE toteuma = " toteuman-id ";"))) toteuma {:id toteuman-id, :urakka urakka-id :sopimus sopimus-id :alkanut (pvm/->pvm "14.02.2015") :paattynyt (pvm/->pvm "14.02.2015") :tyyppi "materiaali" :suorittajan-nimi "Ahkera hommailija" :suorittajan-ytunnus 1234 :lisatieto "Pvm muutos ja cachet toimii"} tmt [{:id tm-id :materiaalikoodi 16 :maara 2100 :toteuma toteuman-id}]] tarkistetaan että kaikki cachesta palautetut expected - setistä (is (= sopimuksen-kaytetty-mat-ennen-odotettu sopimuksen-mat-kaytto-ennen ) "sopimuksen materiaalin käyttö cache ennen muutosta") (is (= hoitoluokittaiset-ennen-odotettu hoitoluokittaiset-ennen ) "hoitoluokittaisten cache ennen muutosta") kyseessä päivitys , palvelukutsua (is (= 1 (ffirst (q (str "SELECT count(*) FROM toteuma_materiaali WHERE toteuma = " toteuman-id " AND poistettu IS NOT TRUE;"))))) (is (= 1 (ffirst (q (str "SELECT count(*) FROM toteuma WHERE id=" toteuman-id " AND poistettu IS NOT TRUE;"))))) (kutsu-palvelua (:http-palvelin jarjestelma) :tallenna-toteuma-ja-toteumamateriaalit +kayttaja-jvh+ {:toteuma toteuma :toteumamateriaalit tmt :hoitokausi [#inst "2014-09-30T21:00:00.000-00:00" #inst "2015-09-30T20:59:59.000-00:00"] :sopimus sopimus-id}) lisäyksen yhden kerran ... (is (= 1 (ffirst (q (str "SELECT count(*) FROM toteuma_materiaali WHERE toteuma = " toteuman-id ";"))))) (is (= 1 (ffirst (q (str "SELECT count(*) FROM toteuma WHERE id=" toteuman-id " AND poistettu IS NOT TRUE;"))))) (let [sopimuksen-mat-kaytto-jalkeen (set (q (str "SELECT sopimus, alkupvm, materiaalikoodi, maara FROM sopimuksen_kaytetty_materiaali WHERE sopimus = " sopimus-id (pvm-vali-sql-tekstina "alkupvm" "'2015-02-01' AND '2015-02-28'") ";"))) hoitoluokittaiset-jalkeen (set (q (str "SELECT pvm, materiaalikoodi, talvihoitoluokka, urakka, maara FROM urakan_materiaalin_kaytto_hoitoluokittain WHERE urakka = " urakka-id (pvm-vali-sql-tekstina "pvm" "'2015-02-01' AND '2015-02-28'") ";")))] lisäyksen jälkeen cachet päivittyvät oikein , vanhalla pvm : , päivällä (is (= sopimuksen-kaytetty-mat-jalkeen-odotettu sopimuksen-mat-kaytto-jalkeen ) "sopimuksen materiaalin käyttö cache jalkeen muutoksen") (is (= hoitoluokittaiset-jalkeen-odotettu hoitoluokittaiset-jalkeen ) "hoitoluokittaisten cache jalkeen muutoksen")))) (deftest uusi-materliaali-cachet-pysyy-jiirissa (let [urakka-id (hae-oulun-alueurakan-2014-2019-id) sopimus-id (hae-oulun-alueurakan-2014-2019-paasopimuksen-id) sopimuksen-kaytetty-mat-ennen-odotettu (set []) sopimuksen-kaytetty-mat-jalkeen-odotettu (set [[2 #inst "2011-02-13T22:00:00.000-00:00" 16 200M]]) hoitoluokittaiset-ennen-odotettu (set []) hoitoluokittaiset-jalkeen-odotettu (set [[#inst "2011-02-13T22:00:00.000-00:00" 16 99 4 200M]]) sopimuksen-mat-kaytto-ennen (set (q (str "SELECT sopimus, alkupvm, materiaalikoodi, maara FROM sopimuksen_kaytetty_materiaali WHERE sopimus = " sopimus-id (pvm-vali-sql-tekstina "alkupvm" "'2011-02-01' AND '2011-02-28'") ";"))) hoitoluokittaiset-ennen (set (q (str "SELECT pvm, materiaalikoodi, talvihoitoluokka, urakka, maara FROM urakan_materiaalin_kaytto_hoitoluokittain WHERE urakka = " urakka-id (pvm-vali-sql-tekstina "pvm" "'2011-02-01' AND '2011-02-28'") ";"))) koska uusi koska uusi toteuma {:id toteuman-id, :urakka urakka-id :sopimus sopimus-id :alkanut (pvm/->pvm "14.02.2011") :paattynyt (pvm/->pvm "14.02.2011") :tyyppi "materiaali" :suorittajan-nimi "Ahkera hommailija" :suorittajan-ytunnus 1234 :lisatieto "Täysin uusi jiirijutska"} tmt [{:id tm-id :materiaalikoodi 16 :maara 200 :toteuma toteuman-id}]] tarkistetaan että kaikki cachesta palautetut expected - setistä (is (= sopimuksen-kaytetty-mat-ennen-odotettu sopimuksen-mat-kaytto-ennen ) "sopimuksen materiaalin käyttö cache ennen muutosta") (is (= hoitoluokittaiset-ennen-odotettu hoitoluokittaiset-ennen ) "hoitoluokittaisten cache ennen muutosta") (kutsu-palvelua (:http-palvelin jarjestelma) :tallenna-toteuma-ja-toteumamateriaalit +kayttaja-jvh+ {:toteuma toteuma :toteumamateriaalit tmt :hoitokausi [#inst "2010-09-30T21:00:00.000-00:00" #inst "2011-09-30T20:59:59.000-00:00"] :sopimus sopimus-id}) (let [toteuman-id-jalkeen (ffirst (q (str "SELECT id FROM toteuma WHERE lisatieto='Täysin uusi jiirijutska';")))] (is (= 1 (ffirst (q (str "SELECT count(*) FROM toteuma_materiaali WHERE toteuma = " toteuman-id-jalkeen ";"))))) (is (= 1 (ffirst (q (str "SELECT count(*) FROM toteuma WHERE id=" toteuman-id-jalkeen " AND poistettu IS NOT TRUE;")))))) (let [sopimuksen-mat-kaytto-jalkeen (set (q (str "SELECT sopimus, alkupvm, materiaalikoodi, maara FROM sopimuksen_kaytetty_materiaali WHERE sopimus = " sopimus-id (pvm-vali-sql-tekstina "alkupvm" "'2011-02-01' AND '2011-02-28'") ";"))) hoitoluokittaiset-jalkeen (set (q (str "SELECT pvm, materiaalikoodi, talvihoitoluokka, urakka, maara FROM urakan_materiaalin_kaytto_hoitoluokittain WHERE urakka = " urakka-id (pvm-vali-sql-tekstina "pvm" "'2011-02-01' AND '2011-02-28'") ";")))] lisäyksen jälkeen cachet päivittyvät oikein , vanhalla pvm : , päivällä (is (= sopimuksen-kaytetty-mat-jalkeen-odotettu sopimuksen-mat-kaytto-jalkeen ) "sopimuksen materiaalin käyttö cache jalkeen muutoksen") (is (= hoitoluokittaiset-jalkeen-odotettu hoitoluokittaiset-jalkeen ) "hoitoluokittaisten cache jalkeen muutoksen")))) (deftest varustetoteumat-haettu-oikein (let [alkupvm (pvm/luo-pvm 2005 9 1) loppupvm (pvm/luo-pvm 2017 10 30) hae-tietolaji-xml (slurp (io/resource "xsd/tierekisteri/esimerkit/hae-tietolaji-response.xml")) varustetoteumat (with-fake-http [(str +testi-tierekisteri-url+ "/haetietolaji") hae-tietolaji-xml] (kutsu-palvelua (:http-palvelin jarjestelma) :urakan-varustetoteumat +kayttaja-jvh+ {:urakka-id @oulun-alueurakan-2005-2010-id :sopimus-id @oulun-alueurakan-2005-2010-paasopimuksen-id :alkupvm alkupvm :loppupvm loppupvm :tietolajit (into #{} (keys varusteet-domain/tietolaji->selitys))}))] (is (>= (count varustetoteumat) 3)) (is (contains? (first varustetoteumat) :sijainti)))) circleci : stä ei saane yhteyttä + oikea - testi - tierekisteri - url+ Otetaan pois , että on saatu muutokset tierekisteriin liittyen tuotantoon asti - myöskään jenkinsistä ei saada yhteyttä joten disabloitu kunnes (deftest varusteiden-testit Tässä . , niin tallennuksen aikana ei tarvitse enään tehdä uutta kutsua ( , niin se epäonnistuisi , koska annetun tierekisterikomponentin url (tierekisteri/hae-tietolaji (assoc (:tierekisteri jarjestelma) :tierekisteri-api-url +oikea-testi-tierekisteri-url+) "tl506" nil) (let [toteuma {:ajorata 0 :kuntoluokitus nil :sijainti {:type :point :coordinates [428024.7622351866 7210432.45750019]} :tierekisteriosoite {:numero 22 :alkuosa 1 :alkuetaisyys 3} :urakka-id 4 :loppupvm nil :arvot {:x 428025 :y 7210432 :asetusnr "11"} :puoli 1 :tietolaji "tl506" :id nil :uusi-liite nil :toiminto :lisatty :alkupvm (pvm/luo-pvm 2018 6 11) :tunniste nil :lisatieto nil} hakuehdot {:urakka-id 4 :sopimus-id 2 :alkupvm (pvm/luo-pvm 2017 9 30) :loppupvm (pvm/luo-pvm 3018 9 29) :tienumero nil} toteumien-maara (atom (count (q "SELECT id FROM toteuma;"))) , voidaan with - redefs funktiossa . Tarkoitus on vain muuttaa vastaus - saatu atomin , on suoritettu , se . laheta-varustetoteuma-tierekisteriin-copy tierekisteri/laheta-varustetoteuma-tierekisteriin haku-fn (fn [haku-parametrit vastaus-atom] (with-redefs [tierekisteri/laheta-varustetoteuma-tierekisteriin (fn [this varustetoteuma-id] (when (= (:tierekisteri-api-url this) +testi-tierekisteri-url+) (laheta-varustetoteuma-tierekisteriin-copy this varustetoteuma-id)) (reset! vastaus-atom true))] (kutsu-palvelua (:http-palvelin jarjestelma) :tallenna-varustetoteuma +kayttaja-jvh+ haku-parametrit)))] (testing "Varusteen tallentaminen" (let [lisaa-tietue-xml (slurp (io/resource "xsd/tierekisteri/esimerkit/ok-vastaus-response.xml")) vastaus-saatu (atom false)] (with-fake-http [(str +testi-tierekisteri-url+ "/lisaatietue") lisaa-tietue-xml] (let [vastaus (haku-fn {:hakuehdot hakuehdot :toteuma toteuma} vastaus-saatu) _ (odota-ehdon-tayttymista #(true? @vastaus-saatu) "Tierekisteristä saatiin vastaus" 10000) tallennettu-varuste (q "SELECT luotu, tunniste, tietolaji, toimenpide, tila FROM varustetoteuma WHERE tunniste='HARJ0000000000000002' ORDER BY luotu DESC;")] (swap! toteumien-maara inc) (is (= (count (q "SELECT id FROM toteuma;")) @toteumien-maara)) (is (true? @vastaus-saatu) "Saatiin vastaus") (is (= (mapv rest tallennettu-varuste) [["HARJ0000000000000002" "tl506" "lisatty" "lahetetty"]])) uusissa nil , tierekisteriin (is (= (:tunniste (first vastaus)) "HARJ0000000000000002")) (doseq [[kentta arvo] (:arvot (first vastaus))] (when (contains? (:arvot toteuma) kentta) (is (= arvo (str (kentta (:arvot toteuma))))))))))) (testing "Varusteen päivittäminen" (let [paivita-tietue-xml (slurp (io/resource "xsd/tierekisteri/esimerkit/ok-vastaus-response.xml")) vastaus-saatu (atom false)] (with-fake-http [(str +testi-tierekisteri-url+ "/paivitatietue") paivita-tietue-xml] (let [toteuma (-> toteuma (update :arvot (fn [arvot] (assoc arvot :lmteksti "foo"))) (assoc :toiminto :paivitetty :tunniste "HARJ0000000000000002")) vastaus (haku-fn {:hakuehdot hakuehdot :toteuma toteuma} vastaus-saatu) _ (odota-ehdon-tayttymista #(true? @vastaus-saatu) "Tierekisteristä saatiin vastaus" 10000) varusteet (q "SELECT luotu, tunniste, tietolaji, toimenpide, tila FROM varustetoteuma WHERE tunniste='HARJ0000000000000002' ORDER BY luotu ASC;")] (swap! toteumien-maara inc) (is (= (count (q "SELECT id FROM toteuma;")) @toteumien-maara)) (is (true? @vastaus-saatu) "Saatiin vastaus") (is (= (mapv rest varusteet) [["HARJ0000000000000002" "tl506" "lisatty" "lahetetty"] ["HARJ0000000000000002" "tl506" "paivitetty" "lahetetty"]])) (is (= (:tunniste (first vastaus)) "HARJ0000000000000002")) (doseq [[kentta arvo] (:arvot (first vastaus))] (when (contains? (:arvot toteuma) kentta) (is (= arvo (str (kentta (:arvot toteuma))))))))))) (testing "Varusteen poistaminen" (let [poista-tietue-xml (slurp (io/resource "xsd/tierekisteri/esimerkit/ok-vastaus-response.xml")) vastaus-saatu (atom false)] (with-fake-http [(str +testi-tierekisteri-url+ "/poistatietue") poista-tietue-xml] (let [toteuma (-> toteuma (update :arvot (fn [arvot] (assoc arvot :lmteksti "foo"))) (assoc :toiminto :poistettu :tunniste "HARJ0000000000000002")) vastaus (haku-fn {:hakuehdot hakuehdot :toteuma toteuma} vastaus-saatu) _ (odota-ehdon-tayttymista #(true? @vastaus-saatu) "Tierekisteristä saatiin vastaus" 10000) varusteet (q "SELECT luotu, tunniste, tietolaji, toimenpide, tila FROM varustetoteuma WHERE tunniste='HARJ0000000000000002' ORDER BY luotu ASC;")] (swap! toteumien-maara inc) (is (= (count (q "SELECT id FROM toteuma;")) @toteumien-maara)) (is (true? @vastaus-saatu) "Saatiin vastaus") (is (= (mapv rest varusteet) [["HARJ0000000000000002" "tl506" "lisatty" "lahetetty"] ["HARJ0000000000000002" "tl506" "paivitetty" "lahetetty"] ["HARJ0000000000000002" "tl506" "poistettu" "lahetetty"]])) (is (= (:tunniste (first vastaus)) "HARJ0000000000000002")))))) (testing "Varusteen epäonnistunut tallentaminen" (let [lisaa-tietue-virhe-xml (slurp (io/resource "xsd/tierekisteri/esimerkit/virhe-tietueen-lisays-epaonnistui-response.xml")) vastaus-saatu (atom false)] (with-fake-http [(str +testi-tierekisteri-url+ "/lisaatietue") lisaa-tietue-virhe-xml] (let [vastaus (haku-fn {:hakuehdot hakuehdot :toteuma toteuma} vastaus-saatu) _ (odota-ehdon-tayttymista #(true? @vastaus-saatu) "Tierekisteristä saatiin vastaus" 10000) tallennettu-varuste (q "SELECT luotu, tunniste, tietolaji, toimenpide, tila, lahetysvirhe FROM varustetoteuma WHERE tunniste='HARJ0000000000000003' ORDER BY luotu DESC;")] (swap! toteumien-maara inc) (is (= (count (q "SELECT id FROM toteuma;")) @toteumien-maara)) (is (true? @vastaus-saatu) "Saatiin vastaus") (is (= (mapv rest tallennettu-varuste) [["HARJ0000000000000003" "tl506" "lisatty" "virhe" "Virheet: Tietueen tiedot ovat puutteelliset"]])) (is (nil? (:tila vastaus))) (is (= (:tunniste (first vastaus)) "HARJ0000000000000003")) (doseq [[kentta arvo] (:arvot (first vastaus))] (when (contains? (:arvot toteuma) kentta) (is (= arvo (str (kentta (:arvot toteuma))))))))))) (testing "Varusteen epäonnistuneen tallentamisen tallentaminen" (let [lisaa-tietue-xml (slurp (io/resource "xsd/tierekisteri/esimerkit/ok-vastaus-response.xml")) vastaus-saatu (atom false)] (with-fake-http [(str +testi-tierekisteri-url+ "/lisaatietue") lisaa-tietue-xml] (let [toteuma (-> toteuma (assoc :tunniste "HARJ0000000000000003" :id (ffirst (q "SELECT id FROM varustetoteuma WHERE tunniste='HARJ0000000000000003'")))) vastaus (haku-fn {:hakuehdot hakuehdot :toteuma toteuma} vastaus-saatu) _ (odota-ehdon-tayttymista #(true? @vastaus-saatu) "Tierekisteristä saatiin vastaus" 10000) tallennettu-varuste (q "SELECT luotu, tunniste, tietolaji, toimenpide, tila, lahetysvirhe FROM varustetoteuma WHERE tunniste='HARJ0000000000000003' ORDER BY luotu DESC;")] (is (= (count (q "SELECT id FROM toteuma;")) @toteumien-maara)) (is (true? @vastaus-saatu) "Saatiin vastaus") (is (= (mapv rest tallennettu-varuste) [["HARJ0000000000000003" "tl506" "lisatty" "lahetetty" nil]])) (is (= (:tunniste (first vastaus)) "HARJ0000000000000003"))))))))) (deftest kokonaishintaisen-toteuman-siirtymatiedot (let [toteuma-id (ffirst (q "SELECT id FROM toteuma WHERE urakka = 2 AND lisatieto = 'Tämä on käsin tekaistu juttu'")) hae #(kutsu-palvelua (:http-palvelin jarjestelma) :siirry-toteuma % toteuma-id) ok-tulos {:alkanut #inst "2008-09-08T21:10:00.000000000-00:00" :urakka-id 2 :tyyppi "kokonaishintainen" :hallintayksikko-id 12 :aikavali {:alku #inst "2007-09-30T21:00:00.000-00:00" :loppu #inst "2008-09-29T21:00:00.000-00:00"} :tehtavat [{:toimenpidekoodi 1350, :toimenpideinstanssi "10100"}]} ei-ok-tulos nil] (is (some? toteuma-id)) (tarkista-map-arvot ok-tulos (hae +kayttaja-jvh+)) Eri urakoitsijalla palautuu poikkeus oikeustarkistuksessa (is (thrown? Exception (hae +kayttaja-yit_uuvh+))) Toteuman urakan (tarkista-map-arvot ok-tulos (hae +kayttaja-ulle+)))) (deftest toteuman-paivitys-sama-partitiolle (let [urakka-id (hae-urakan-id-nimella "Pudasjärven alueurakka 2007-2012") sopimus-id (hae-pudasjarven-alueurakan-paasopimuksen-id) toteuma-id (ffirst (q (str "SELECT id FROM toteuma WHERE urakka = " urakka-id " AND lisatieto = 'Tämä on käsin tekaistu juttu'"))) toteuma-tehtava-id (ffirst (q (str "SELECT id FROM toteuma_tehtava WHERE toteuma = " toteuma-id ";"))) 1.10.2016 tyo {:urakka-id urakka-id :sopimus-id sopimus-id :alkanut uusi-tyon-pvm-samassa-partitiossa :paattynyt uusi-tyon-pvm-samassa-partitiossa :reitti {:type :multiline :lines [{:type :line, :points [[426948.180407029 7212765.48225361] [430650.8691 7212578.8262]]}]} :hoitokausi-aloituspvm hoitokausi-aloituspvm :hoitokausi-lopetuspvm hoitokausi-lopetuspvm :suorittajan-nimi "Alihankkijapaja Ky" :suorittajan-ytunnus "123456-Y" :tyyppi :kokonaishintainen :lisatieto "Tämä on käsin tekaistu juttu" :toteuma-id toteuma-id :tehtavat [{:toimenpidekoodi 1368 :maara 333 :tehtava-id toteuma-tehtava-id}]} lisatty (first (kutsu-palvelua (:http-palvelin jarjestelma) :tallenna-urakan-toteuma-ja-kokonaishintaiset-tehtavat +kayttaja-jvh+ {:toteuma tyo :hakuparametrit {:urakka-id urakka-id :sopimus-id sopimus-id :alkupvm hoitokausi-aloituspvm :loppupvm hoitokausi-lopetuspvm :toimenpide nil :tehtava nil}})) toteuma-id-jalkeen (ffirst (q (str "SELECT id FROM toteuma WHERE urakka = " urakka-id " AND lisatieto = 'Tämä on käsin tekaistu juttu'")))] (is (= toteuma-id toteuma-id-jalkeen) "Toteuman id ei saa muuttua") (is (= (get-in lisatty [:pvm]) uusi-tyon-pvm-samassa-partitiossa) "Tallennetun työn alkanut pvm") (is (= (get-in lisatty [:jarjestelmanlisaama]) false)) (is (= (get-in lisatty [:nimi]) "Pistehiekoitus")) (is (= (get-in lisatty [:yksikko]) "tiekm") "Yksikkö") (is (= (get-in lisatty [:toimenpidekoodi]) 1368) "Tallennetun työn tehtävän toimenpidekoodi") (is (= (get-in lisatty [:maara]) 333M) "Tallennetun työn tehtävän määrä"))) (deftest toteuman-paivitys-siirtaa-eri-partitiolle (let [urakka-id (hae-urakan-id-nimella "Pudasjärven alueurakka 2007-2012") sopimus-id (hae-pudasjarven-alueurakan-paasopimuksen-id) toteuma-id (ffirst (q (str "SELECT id FROM toteuma WHERE urakka = " urakka-id " AND lisatieto = 'Tämä on käsin tekaistu juttu'"))) toteuma-tehtava-id (ffirst (q (str "SELECT id FROM toteuma_tehtava WHERE toteuma = " toteuma-id ";"))) 24.12.2020 hoitokausi-aloituspvm (pvm/luo-pvm 2020 9 1) tyo {:urakka-id urakka-id :sopimus-id sopimus-id :alkanut uusi-tyon-pvm-eri-partitiossa :paattynyt uusi-tyon-pvm-eri-partitiossa :reitti {:type :multiline :lines [{:type :line, :points [[426948.180407029 7212765.48225361] [430650.8691 7212578.8262]]}]} :hoitokausi-aloituspvm hoitokausi-aloituspvm :hoitokausi-lopetuspvm hoitokausi-lopetuspvm :suorittajan-nimi "Alihankkijapaja Ky" :suorittajan-ytunnus "123456-Y" :tyyppi :kokonaishintainen :lisatieto "Tämä on käsin tekaistu juttu" :toteuma-id toteuma-id :tehtavat [{:toimenpidekoodi 1368 :maara 444 :tehtava-id toteuma-tehtava-id}]} kaikki (kutsu-palvelua (:http-palvelin jarjestelma) :tallenna-urakan-toteuma-ja-kokonaishintaiset-tehtavat +kayttaja-jvh+ {:toteuma tyo :hakuparametrit {:urakka-id urakka-id :sopimus-id sopimus-id :alkupvm hoitokausi-aloituspvm :loppupvm hoitokausi-lopetuspvm :toimenpide nil :tehtava nil}}) lisatty (some #(when (= (:toimenpidekoodi %) 1368) %) kaikki) toteuma-id-jalkeen (ffirst (q (str "SELECT id FROM toteuma WHERE urakka = " urakka-id " AND lisatieto = 'Tämä on käsin tekaistu juttu'")))] (is (= toteuma-id toteuma-id-jalkeen) "Toteuman id ei saa muuttua") (is (= (get-in lisatty [:pvm]) uusi-tyon-pvm-eri-partitiossa) "Tallennetun työn alkanut pvm") (is (= (get-in lisatty [:pvm]) uusi-tyon-pvm-eri-partitiossa) "Tallennetun työn alkanut pvm") (is (= (get-in lisatty [:jarjestelmanlisaama]) false)) (is (= (get-in lisatty [:nimi]) "Pistehiekoitus")) (is (= (get-in lisatty [:yksikko]) "tiekm") "Yksikkö") (is (= (get-in lisatty [:toimenpidekoodi]) 1368) "Tallennetun työn tehtävän toimenpidekoodi") (is (= (get-in lisatty [:maara]) 444M) "Tallennetun työn tehtävän määrä"))) (defn luo-testitoteuma [urakka-id sopimus-id alkanut toteuma-id] {:sopimus sopimus-id :alkanut (konv/sql-date alkanut) :paattynyt (konv/sql-date alkanut) :reitti {:type :multiline :lines [{:type :line, :points [[426948.180407029 7212765.48225361] [430650.8691 7212578.8262]]}]} :id toteuma-id :alkuosa 1 :numero 4 :alkuetaisyys 1 :kayttaja 1 :ytunnus "123456-Y" :urakka urakka-id :suorittaja "Alihankkijapaja Ky" :loppuetaisyys 2 :loppuosa 2 :tyyppi "kokonaishintainen" :lisatieto "Tämä on käsin tekaistu juttu"}) (deftest toteuman-paivitys-ei-muuta-lukumaaraa (let [toteuma-count (ffirst (q (str "SELECT count(id) FROM toteuma"))) urakka-id (hae-urakan-id-nimella "Pudasjärven alueurakka 2007-2012") sopimus-id (hae-pudasjarven-alueurakan-paasopimuksen-id) toteuma-id (ffirst (q (str "SELECT id FROM toteuma WHERE urakka = " urakka-id " AND lisatieto = 'Tämä on käsin tekaistu juttu'")))] Satunnaisia päivämääriä vuosina 2000 - 2030 ... ( myös ) (doseq [alkanut (map #(pvm/->pvm (str (rand-int 28) "." (rand-int 170) "." %)) (range 2000 2030))] (do (toteumat-q/paivita-toteuma<! (:db jarjestelma) (luo-testitoteuma urakka-id sopimus-id alkanut toteuma-id)) (is (= toteuma-id (ffirst (q (str "SELECT id FROM toteuma WHERE urakka = " urakka-id " AND lisatieto = 'Tämä on käsin tekaistu juttu'")))) "Toteuma id ei saa muuttua.") (is (= alkanut (ffirst (q (str "SELECT alkanut FROM toteuma WHERE urakka = " urakka-id " AND lisatieto = 'Tämä on käsin tekaistu juttu'")))) "Toteuma alkanut OK") (is (= toteuma-count (ffirst (q (str "SELECT count(id) FROM toteuma")))) "Toteuma count ei saa muuttua."))))) (deftest hae-urakan-kokonaishintaisten-toteumien-tehtavien-paivakohtaiset-summat (let [urakka-id (hae-oulun-alueurakan-2014-2019-id) sopimus-id (hae-oulun-alueurakan-2014-2019-paasopimuksen-id) talvihoito-tpi-id (hae-oulun-alueurakan-talvihoito-tpi-id) odotettu [{:pvm #inst "2017-01-31T22:00:00.000-00:00", :toimenpidekoodi 1369, :maara 666M, :jarjestelmanlisaama true, :nimi "Suolaus", :yksikko "tiekm"} {:pvm #inst "2015-01-31T22:00:00.000-00:00", :toimenpidekoodi 1369, :maara 123M, :jarjestelmanlisaama true, :nimi "Suolaus", :yksikko "tiekm"}] vastaus (kutsu-palvelua (:http-palvelin jarjestelma) :hae-urakan-kokonaishintaisten-toteumien-tehtavien-paivakohtaiset-summat +kayttaja-jvh+ {:urakka-id urakka-id :sopimus-id sopimus-id :alkupvm (pvm/->pvm "1.10.2014") :loppupvm (pvm/->pvm "1.1.2018") :toimenpide talvihoito-tpi-id :tehtava nil})] (is (= odotettu vastaus) "hae-urakan-kokonaishintaisten-toteumien-tehtavien-paivakohtaiset-summat oikein")))
487b4144eb974d4d2e117bdc2372977e271ea3a5f541cb20555c6b44c936f0d2
dsheets/ocaml-unix-dirent
dirent_unix_lwt.mli
* Copyright ( c ) 2016 < > * * Permission to use , copy , modify , and distribute this software for any * purpose with or without fee is hereby granted , provided that the above * copyright notice and this permission notice appear in all copies . * * THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN * ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE . * * Copyright (c) 2016 Jeremy Yallop <> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * *) val opendir : string -> Lwt_unix.dir_handle Lwt.t val readdir : Lwt_unix.dir_handle -> Dirent.Dirent.t Lwt.t val closedir : Lwt_unix.dir_handle -> unit Lwt.t
null
https://raw.githubusercontent.com/dsheets/ocaml-unix-dirent/b3749486aa44642b911b7740193cd8133c6e144a/lwt/dirent_unix_lwt.mli
ocaml
* Copyright ( c ) 2016 < > * * Permission to use , copy , modify , and distribute this software for any * purpose with or without fee is hereby granted , provided that the above * copyright notice and this permission notice appear in all copies . * * THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN * ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE . * * Copyright (c) 2016 Jeremy Yallop <> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * *) val opendir : string -> Lwt_unix.dir_handle Lwt.t val readdir : Lwt_unix.dir_handle -> Dirent.Dirent.t Lwt.t val closedir : Lwt_unix.dir_handle -> unit Lwt.t
6b2aa1ee7e434cd26e676fdea30c477800d901c0eb0ab8612dab1b2b38f1dffe
alanzplus/EOPL
reg-interpreter.rkt
#lang eopl (require "./reg-spec.rkt") (provide run) (provide num-val) (provide bool-val) (provide proc-val) (provide list-val) (provide expval->num) (provide expval->bool) (provide expval->proc) (provide expval->list) (provide procedure) (provide apply-procedure/k) ; ----------------------------------------------------------------------------- List Utilities ; ----------------------------------------------------------------------------- Return the first idx which satifies the predicate (define find-idx (lambda (predicate lst) (letrec ((helper (lambda (idx alst) (if (null? alst) -1 (if (predicate (car alst)) idx (helper (+ idx 1) (cdr alst))))))) (helper 0 lst)))) ; ----------------------------------------------------------------------------- ; Expression Value Representation ; ----------------------------------------------------------------------------- (define-datatype expval expval? (num-val (num number?)) (bool-val (bool boolean?)) (proc-val (proc proc?)) (list-val (alist list?)) ) ; ExpVal -> num (define expval->num (lambda (val) (cases expval val (num-val (num) num) (else (eopl:error "expected num-val"))))) ; ExpVal -> bool (define expval->bool (lambda (val) (cases expval val (bool-val (bool) bool) (else (eopl:error "expected bool-val"))))) ; ExpVal -> Procedure (define expval->proc (lambda (val) (cases expval val (proc-val (proc) proc) (else (eopl:error "expected proc-val"))))) ExpVal - > list (define expval->list (lambda (val) (cases expval val (list-val (alist) alist) (else (eopl:error "expected list-val"))))) ; ----------------------------------------------------------------------------- ; Procedure Representation ; ----------------------------------------------------------------------------- (define-datatype proc proc? (procedure (vars (list-of identifier?)) (body expression?) (env environment?))) Proc x ExpVal x Cont - > ExpVal (define apply-procedure/k (lambda () (cases proc proc1 (procedure (vars body saved-env) (eopl:pretty-print "~~~ apply-procedure/k") (eopl:pretty-print env) (eopl:pretty-print saved-env) (set! env (extend-env-list vars (newref-list val) saved-env)) (set! exp body) (value-of/k))))) ; ----------------------------------------------------------------------------- ; Store ; ----------------------------------------------------------------------------- (define the-store 'uninitialized) ; () -> Store (define empty-store (lambda () '())) ; () -> Store (define get-store (lambda () the-store)) ; () -> Unspecified (define initialize-store! (lambda () (set! the-store (empty-store)))) ; SchemeVal -> Bool (define reference? (lambda (v) (integer? v))) ; ExpVal -> Ref (define newref (lambda (val) (let ((next-ref (length the-store))) (set! the-store (append the-store (list val))) next-ref))) ; ExpVals -> Refs (define newref-list (lambda (vals) (map newref vals))) Ref - > ExpVal (define deref (lambda (ref) (list-ref the-store ref))) ; Ref x ExpVal -> Unspecified (define setref! (lambda (ref val) (set! the-store (letrec ((setref-inner (lambda (store1 ref1) (cond ((null? store1) (eopl:error "cannot set ~s in reference ~s" val ref)) ((zero? ref1) (cons val (cdr store1))) (else (cons (car store1) (setref-inner (cdr store1) (- ref1 1)))))))) (setref-inner the-store ref))))) ; ----------------------------------------------------------------------------- ; Environment ; ----------------------------------------------------------------------------- (define-datatype environment environment? (empty-env) (extend-env (var identifier?) (val reference?) (env environment?)) (extend-env-list (vars (list-of identifier?)) (vals (list-of reference?)) (env environment?)) (extend-env-rec (p-name identifier?) (p-vars (list-of identifier?)) (body expression?) (env environment?))) Environment x Identifier - > ExpVal (define apply-env (lambda (env1 search-var) (cases environment env1 (empty-env () (eopl:error "APPLY-ENV: there is no binding for" search-var)) (extend-env (saved-var saved-val saved-env) (if (eqv? search-var saved-var) saved-val (apply-env saved-env search-var))) (extend-env-list (saved-vars saved-vals saved-env) (let ((idx (find-idx (lambda (ele) (eqv? ele search-var)) saved-vars))) (if (eqv? idx -1) (apply-env saved-env search-var) (list-ref saved-vals idx)))) (extend-env-rec (p-name p-vars p-body saved-env) (if (eqv? search-var p-name) (newref (proc-val (procedure p-vars p-body saved-env))) (apply-env saved-env search-var)))))) ; Initilization (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)))))) ; ----------------------------------------------------------------------------- ; Continuation ; ----------------------------------------------------------------------------- (define-datatype continuation continuation? (end-cont) (zero-cont (cont continuation?)) (let-exp-cont (var identifier?) (body expression?) (env environment?) (cont continuation?)) (if-test-cont (exp2 expression?) (exp3 expression?) (env environment?) (cont continuation?)) (mul1-cont (exp2 expression?) (env environment?) (cont continuation?)) (mul2-cont (val expval?) (cont continuation?)) (diff1-cont (exp2 expression?) (env environment?) (cont continuation?)) (diff2-cont (val expval?) (cont continuation?)) (rator-cont (exps (list-of expression?)) (env environment?) (cont continuation?)) (rand-cont (env environment?) (val expval?) (exps (list-of expression?)) (vals (list-of expval?)) (cont continuation?)) (let2-cont1 (var1 identifier?) (var2 identifier?) (exp2 expression?) (body expression?) (env environment?) (cont continuation?)) (let2-cont2 (var1 identifier?) (val1 expval?) (var2 identifier?) (body expression?) (env environment?) (cont continuation?)) (let3-cont1 (var1 identifier?) (var2 identifier?) (exp2 expression?) (var3 identifier?) (exp3 expression?) (body expression?) (env environment?) (cont continuation?)) (let3-cont2 (var1 identifier?) (val1 expval?) (var2 identifier?) (var3 identifier?) (exp3 expression?) (body expression?) (env environment?) (cont continuation?)) (let3-cont3 (var1 identifier?) (val1 expval?) (var2 identifier?) (val2 expval?) (var3 identifier?) (body expression?) (env environment?) (cont continuation?)) (cons-cont1 (exp2 expression?) (env environment?) (cont continuation?)) (cons-cont2 (val expval?) (cont continuation?)) (car-cont (cont continuation?)) (cdr-cont (cont continuation?)) (null?-cont (cont continuation?)) (list-first-cont (val expval?) (cont continuation?)) (list-rest-cont (exps expression?) (env environment?) (cont continuation?)) (letmul-cont (vars (list-of identifier?)) (exps (list-of expression?)) (body expression?) (body-eval-env environment?) (binding-eval-env environment?) (cont continuation?)) (set-rhs-cont (env environment?) (var identifier?) (cont continuation?)) (begin-exp-cont (exps (list-of expression?)) (env environment?) (cont continuation?)) ) (define apply-cont (lambda () (begin (eopl:pretty-print "----- apply-cont ------") (eopl:pretty-print cont) (eopl:pretty-print val) (apply-cont-inner)))) (define apply-cont-inner (lambda () (cases continuation cont (end-cont () (begin (eopl:printf "---------------------\n") (eopl:printf "End of computation. Final answer: \n") (eopl:pretty-print val) (eopl:printf "---------------------\n\n") val)) (zero-cont (saved-cont) (set! cont saved-cont) (set! val (bool-val (zero? (expval->num val)))) (apply-cont)) (let-exp-cont (var body saved-env saved-cont) (set! cont saved-cont) (set! exp body) (set! env (extend-env var (newref val) saved-env)) (value-of/k)) (if-test-cont (exp2 exp3 saved-env saved-cont) (if (expval->bool val) (begin (set! cont saved-cont) (set! env saved-env) (set! exp exp2) (value-of/k)) (begin (set! cont saved-cont) (set! env saved-env) (set! exp exp3) (value-of/k)))) (mul1-cont (exp2 saved-env saved-cont) (set! cont (mul2-cont val saved-cont)) (set! env saved-env) (set! exp exp2) (value-of/k)) (mul2-cont (val1 saved-cont) (let ((num1 (expval->num val1)) (num2 (expval->num val))) (begin (set! cont saved-cont) (set! val (num-val (* num1 num2))) (apply-cont)))) (diff1-cont (exp2 saved-env saved-cont) (set! cont (diff2-cont val saved-cont)) (set! env saved-env) (set! exp exp2) (value-of/k)) (diff2-cont (val1 saved-cont) (let ((num1 (expval->num val1)) (num2 (expval->num val))) (begin (set! cont saved-cont) (set! val (num-val (- num1 num2))) (apply-cont)))) (rator-cont (exps saved-env saved-cont) (set! cont (rand-cont saved-env val (cdr exps) '() saved-cont)) (set! exp (car exps)) (set! env saved-env) (value-of/k)) (rand-cont (saved-env rator exps vals saved-cont) (if (null? exps) (begin (set! cont saved-cont) (set! proc1 (expval->proc rator)) (set! val (append vals (list val))) (apply-procedure/k)) (begin (set! cont (rand-cont saved-env rator (cdr exps) (append vals (list val)) saved-cont)) (set! env saved-env) (set! exp (car exps)) (value-of/k)))) (let2-cont1 (var1 var2 exp2 body saved-env saved-cont) (set! cont (let2-cont2 var1 val var2 body saved-env saved-cont)) (set! exp exp2) (set! env saved-env) (value-of/k)) (let2-cont2 (var1 val1 var2 body saved-env saved-cont) (set! cont saved-cont) (set! env (extend-env var2 (newref val) (extend-env var1 (newref val1) saved-env))) (set! exp body)) (let3-cont1 (var1 var2 exp2 var3 exp3 body saved-env saved-cont) (set! cont (let3-cont2 var1 val var2 var3 exp3 body saved-env saved-cont)) (set! env saved-env) (set! exp exp2) (value-of/k)) (let3-cont2 (var1 val1 var2 var3 exp3 body saved-env saved-cont) (set! cont (let3-cont3 var1 val1 var2 val var3 body saved-env saved-cont)) (set! env saved-env) (set! exp exp3) (value-of/k)) (let3-cont3 (var1 val1 var2 val2 var3 body saved-env saved-cont) (set! cont saved-cont) (set! env (extend-env var3 (newref val) (extend-env var2 (newref val2) (extend-env var1 (newref val1) saved-env)))) (set! exp body) (value-of/k)) (cons-cont1 (exp2 saved-env saved-cont) (set! cont (cons-cont2 val saved-cont)) (set! env saved-env) (set! exp exp2) (value-of/k)) (cons-cont2 (val1 saved-cont) (set! cont saved-cont) (set! val (list-val (list val1 val))) (apply-cont)) (car-cont (saved-cont) (set! cont saved-cont) (set! val (car (expval->list val))) (apply-cont)) (cdr-cont (saved-cont) (set! cont saved-cont) (set! val (cadr (expval->list val))) (apply-cont)) (null?-cont (saved-cont) (cases expval val (list-val (alist) (set! cont saved-cont) (set! val (bool-val (null? alist))) (apply-cont)) (else (eopl:error "expected list-val")))) (list-rest-cont (exps saved-env saved-cont) (set! cont (list-first-cont val saved-cont)) (set! exp exps) (set! env saved-env) (value-of/k)) (list-first-cont (val1 saved-cont) (set! cont saved-cont) (set! val (list-val (cons val1 (expval->list val)))) (apply-cont)) (letmul-cont (vars exps body body-eval-env binding-eval-env saved-cont) (if (null? exps) (begin (set! cont saved-cont) (set! env (extend-env (car vars) (newref val) body-eval-env)) (set! exp body) (value-of/k)) (begin (set! cont (letmul-cont (cdr vars) (cdr exps) body (extend-env (car vars) (newref val) body-eval-env) binding-eval-env saved-cont)) (set! env binding-eval-env) (set! exp (car exps))))) (set-rhs-cont (saved-env var saved-cont) (set! cont saved-cont) (set! val (setref! (apply-env saved-env var) val)) (apply-cont)) (begin-exp-cont (other-exps saved-env saved-cont) (if (null? other-exps) (begin (set! cont saved-cont) (apply-cont)) (begin (set! cont (begin-exp-cont (cdr other-exps) saved-env saved-cont)) (set! exp (car other-exps)) (set! env saved-env) (value-of/k)))) (else (eopl:error "unkonw type of continuation. ~s" cont)) ))) ; ----------------------------------------------------------------------------- Global Register ; ----------------------------------------------------------------------------- (define exp 'uninitialized) (define env 'uninitialized) (define cont 'uninitialized) (define val 'uninitialized) (define proc1 'uninitialized) ; ----------------------------------------------------------------------------- ; Interpreter ; ----------------------------------------------------------------------------- String - > ExpVal (define run (lambda (text) (value-of-program (scan-parse text)))) Program - > ExpVal (define value-of-program (lambda (pgm) (cases program pgm (a-program (exp1) (initialize-store!) (set! cont (end-cont)) (set! exp exp1) (set! env (init-env)) (value-of/k))))) Expression X Environemnt x Continutation - > FinalAnswer ( ExpVal ) (define value-of/k (lambda () (begin (eopl:pretty-print "==========================") (eopl:pretty-print exp) (eopl:pretty-print env) (eopl:pretty-print cont) (value-of/k-inner)))) (define value-of/k-inner (lambda () (cases expression exp (const-exp (num) (set! val (num-val num)) (apply-cont)) (var-exp (var) (set! val (deref (apply-env env var))) (apply-cont)) (proc-exp (vars body) (set! val (proc-val (procedure vars body env))) (apply-cont)) (letrec-exp (p-name p-vars p-body letrec-body) (set! exp letrec-body) (set! env (extend-env-rec p-name p-vars p-body env)) (value-of/k)) (zero?-exp (exp1) (set! cont (zero-cont cont)) (set! exp exp1) (value-of/k)) (let-exp (var exp1 body) (set! cont (let-exp-cont var body env cont)) (set! exp exp1) (value-of/k)) (if-exp (exp1 exp2 exp3) (set! cont (if-test-cont exp2 exp3 env cont)) (set! exp exp1) (value-of/k)) (mul-exp (exp1 exp2) (set! cont (mul1-cont exp2 env cont)) (set! exp exp1) (value-of/k)) (diff-exp (exp1 exp2) (set! cont (diff1-cont exp2 env cont)) (set! exp exp1) (value-of/k)) (call-exp (exp1 exps) (set! cont (rator-cont exps env cont)) (set! exp exp1) (value-of/k)) (let2-exp (var1 exp1 var2 exp2 body) (set! cont (let2-cont1 var1 var2 exp2 body env cont)) (set! exp exp1) (value-of/k)) (let3-exp (var1 exp1 var2 exp2 var3 exp3 body) (set! cont (let3-cont1 var1 var2 exp2 var3 exp3 body env cont)) (set! exp exp1) (value-of/k)) (cons-exp (exp1 exp2) (set! cont (cons-cont1 exp2 env cont)) (set! exp exp1) (value-of/k)) (car-exp (exp1) (set! cont (car-cont cont)) (set! exp exp1) (value-of/k)) (cdr-exp (exp1) (set! cont (cdr-cont cont)) (set! exp exp1) (value-of/k)) (null?-exp (exp1) (set! cont (null?-cont cont)) (set! exp exp1) (value-of/k)) (emptylist-exp () (set! val (list-val '())) (apply-cont)) (list-exp (exps) (if (null? exps) (begin (set! val (list-val '())) (apply-cont)) (begin (set! cont (list-rest-cont (list-exp (cdr exps)) env cont)) (set! exp exps) (value-of/k)))) (letmul-exp (vars exps body) (set! cont (letmul-cont vars (cdr exps) body env env cont)) (set! exp (car exps)) (value-of/k)) (assign-exp (var exp1) (set! cont (set-rhs-cont env var cont)) (set! exp exp1) (value-of/k)) (begin-exp (exp-first other-exps) (set! cont (begin-exp-cont other-exps env cont)) (set! exp exp-first) (value-of/k)) (else (eopl:error "cannot handle expression: ~s" exp)) ))) (run "letrec fun(k) = if zero?(k) then 1 else (fun -(k,1)) in (fun 1)")
null
https://raw.githubusercontent.com/alanzplus/EOPL/d7b06392d26d93df851d0ca66d9edc681a06693c/EOPL/ch5/buggy/reg-interpreter.rkt
racket
----------------------------------------------------------------------------- ----------------------------------------------------------------------------- ----------------------------------------------------------------------------- Expression Value Representation ----------------------------------------------------------------------------- ExpVal -> num ExpVal -> bool ExpVal -> Procedure ----------------------------------------------------------------------------- Procedure Representation ----------------------------------------------------------------------------- ----------------------------------------------------------------------------- Store ----------------------------------------------------------------------------- () -> Store () -> Store () -> Unspecified SchemeVal -> Bool ExpVal -> Ref ExpVals -> Refs Ref x ExpVal -> Unspecified ----------------------------------------------------------------------------- Environment ----------------------------------------------------------------------------- Initilization ----------------------------------------------------------------------------- Continuation ----------------------------------------------------------------------------- ----------------------------------------------------------------------------- ----------------------------------------------------------------------------- ----------------------------------------------------------------------------- Interpreter -----------------------------------------------------------------------------
#lang eopl (require "./reg-spec.rkt") (provide run) (provide num-val) (provide bool-val) (provide proc-val) (provide list-val) (provide expval->num) (provide expval->bool) (provide expval->proc) (provide expval->list) (provide procedure) (provide apply-procedure/k) List Utilities Return the first idx which satifies the predicate (define find-idx (lambda (predicate lst) (letrec ((helper (lambda (idx alst) (if (null? alst) -1 (if (predicate (car alst)) idx (helper (+ idx 1) (cdr alst))))))) (helper 0 lst)))) (define-datatype expval expval? (num-val (num number?)) (bool-val (bool boolean?)) (proc-val (proc proc?)) (list-val (alist list?)) ) (define expval->num (lambda (val) (cases expval val (num-val (num) num) (else (eopl:error "expected num-val"))))) (define expval->bool (lambda (val) (cases expval val (bool-val (bool) bool) (else (eopl:error "expected bool-val"))))) (define expval->proc (lambda (val) (cases expval val (proc-val (proc) proc) (else (eopl:error "expected proc-val"))))) ExpVal - > list (define expval->list (lambda (val) (cases expval val (list-val (alist) alist) (else (eopl:error "expected list-val"))))) (define-datatype proc proc? (procedure (vars (list-of identifier?)) (body expression?) (env environment?))) Proc x ExpVal x Cont - > ExpVal (define apply-procedure/k (lambda () (cases proc proc1 (procedure (vars body saved-env) (eopl:pretty-print "~~~ apply-procedure/k") (eopl:pretty-print env) (eopl:pretty-print saved-env) (set! env (extend-env-list vars (newref-list val) saved-env)) (set! exp body) (value-of/k))))) (define the-store 'uninitialized) (define empty-store (lambda () '())) (define get-store (lambda () the-store)) (define initialize-store! (lambda () (set! the-store (empty-store)))) (define reference? (lambda (v) (integer? v))) (define newref (lambda (val) (let ((next-ref (length the-store))) (set! the-store (append the-store (list val))) next-ref))) (define newref-list (lambda (vals) (map newref vals))) Ref - > ExpVal (define deref (lambda (ref) (list-ref the-store ref))) (define setref! (lambda (ref val) (set! the-store (letrec ((setref-inner (lambda (store1 ref1) (cond ((null? store1) (eopl:error "cannot set ~s in reference ~s" val ref)) ((zero? ref1) (cons val (cdr store1))) (else (cons (car store1) (setref-inner (cdr store1) (- ref1 1)))))))) (setref-inner the-store ref))))) (define-datatype environment environment? (empty-env) (extend-env (var identifier?) (val reference?) (env environment?)) (extend-env-list (vars (list-of identifier?)) (vals (list-of reference?)) (env environment?)) (extend-env-rec (p-name identifier?) (p-vars (list-of identifier?)) (body expression?) (env environment?))) Environment x Identifier - > ExpVal (define apply-env (lambda (env1 search-var) (cases environment env1 (empty-env () (eopl:error "APPLY-ENV: there is no binding for" search-var)) (extend-env (saved-var saved-val saved-env) (if (eqv? search-var saved-var) saved-val (apply-env saved-env search-var))) (extend-env-list (saved-vars saved-vals saved-env) (let ((idx (find-idx (lambda (ele) (eqv? ele search-var)) saved-vars))) (if (eqv? idx -1) (apply-env saved-env search-var) (list-ref saved-vals idx)))) (extend-env-rec (p-name p-vars p-body saved-env) (if (eqv? search-var p-name) (newref (proc-val (procedure p-vars p-body saved-env))) (apply-env saved-env search-var)))))) (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)))))) (define-datatype continuation continuation? (end-cont) (zero-cont (cont continuation?)) (let-exp-cont (var identifier?) (body expression?) (env environment?) (cont continuation?)) (if-test-cont (exp2 expression?) (exp3 expression?) (env environment?) (cont continuation?)) (mul1-cont (exp2 expression?) (env environment?) (cont continuation?)) (mul2-cont (val expval?) (cont continuation?)) (diff1-cont (exp2 expression?) (env environment?) (cont continuation?)) (diff2-cont (val expval?) (cont continuation?)) (rator-cont (exps (list-of expression?)) (env environment?) (cont continuation?)) (rand-cont (env environment?) (val expval?) (exps (list-of expression?)) (vals (list-of expval?)) (cont continuation?)) (let2-cont1 (var1 identifier?) (var2 identifier?) (exp2 expression?) (body expression?) (env environment?) (cont continuation?)) (let2-cont2 (var1 identifier?) (val1 expval?) (var2 identifier?) (body expression?) (env environment?) (cont continuation?)) (let3-cont1 (var1 identifier?) (var2 identifier?) (exp2 expression?) (var3 identifier?) (exp3 expression?) (body expression?) (env environment?) (cont continuation?)) (let3-cont2 (var1 identifier?) (val1 expval?) (var2 identifier?) (var3 identifier?) (exp3 expression?) (body expression?) (env environment?) (cont continuation?)) (let3-cont3 (var1 identifier?) (val1 expval?) (var2 identifier?) (val2 expval?) (var3 identifier?) (body expression?) (env environment?) (cont continuation?)) (cons-cont1 (exp2 expression?) (env environment?) (cont continuation?)) (cons-cont2 (val expval?) (cont continuation?)) (car-cont (cont continuation?)) (cdr-cont (cont continuation?)) (null?-cont (cont continuation?)) (list-first-cont (val expval?) (cont continuation?)) (list-rest-cont (exps expression?) (env environment?) (cont continuation?)) (letmul-cont (vars (list-of identifier?)) (exps (list-of expression?)) (body expression?) (body-eval-env environment?) (binding-eval-env environment?) (cont continuation?)) (set-rhs-cont (env environment?) (var identifier?) (cont continuation?)) (begin-exp-cont (exps (list-of expression?)) (env environment?) (cont continuation?)) ) (define apply-cont (lambda () (begin (eopl:pretty-print "----- apply-cont ------") (eopl:pretty-print cont) (eopl:pretty-print val) (apply-cont-inner)))) (define apply-cont-inner (lambda () (cases continuation cont (end-cont () (begin (eopl:printf "---------------------\n") (eopl:printf "End of computation. Final answer: \n") (eopl:pretty-print val) (eopl:printf "---------------------\n\n") val)) (zero-cont (saved-cont) (set! cont saved-cont) (set! val (bool-val (zero? (expval->num val)))) (apply-cont)) (let-exp-cont (var body saved-env saved-cont) (set! cont saved-cont) (set! exp body) (set! env (extend-env var (newref val) saved-env)) (value-of/k)) (if-test-cont (exp2 exp3 saved-env saved-cont) (if (expval->bool val) (begin (set! cont saved-cont) (set! env saved-env) (set! exp exp2) (value-of/k)) (begin (set! cont saved-cont) (set! env saved-env) (set! exp exp3) (value-of/k)))) (mul1-cont (exp2 saved-env saved-cont) (set! cont (mul2-cont val saved-cont)) (set! env saved-env) (set! exp exp2) (value-of/k)) (mul2-cont (val1 saved-cont) (let ((num1 (expval->num val1)) (num2 (expval->num val))) (begin (set! cont saved-cont) (set! val (num-val (* num1 num2))) (apply-cont)))) (diff1-cont (exp2 saved-env saved-cont) (set! cont (diff2-cont val saved-cont)) (set! env saved-env) (set! exp exp2) (value-of/k)) (diff2-cont (val1 saved-cont) (let ((num1 (expval->num val1)) (num2 (expval->num val))) (begin (set! cont saved-cont) (set! val (num-val (- num1 num2))) (apply-cont)))) (rator-cont (exps saved-env saved-cont) (set! cont (rand-cont saved-env val (cdr exps) '() saved-cont)) (set! exp (car exps)) (set! env saved-env) (value-of/k)) (rand-cont (saved-env rator exps vals saved-cont) (if (null? exps) (begin (set! cont saved-cont) (set! proc1 (expval->proc rator)) (set! val (append vals (list val))) (apply-procedure/k)) (begin (set! cont (rand-cont saved-env rator (cdr exps) (append vals (list val)) saved-cont)) (set! env saved-env) (set! exp (car exps)) (value-of/k)))) (let2-cont1 (var1 var2 exp2 body saved-env saved-cont) (set! cont (let2-cont2 var1 val var2 body saved-env saved-cont)) (set! exp exp2) (set! env saved-env) (value-of/k)) (let2-cont2 (var1 val1 var2 body saved-env saved-cont) (set! cont saved-cont) (set! env (extend-env var2 (newref val) (extend-env var1 (newref val1) saved-env))) (set! exp body)) (let3-cont1 (var1 var2 exp2 var3 exp3 body saved-env saved-cont) (set! cont (let3-cont2 var1 val var2 var3 exp3 body saved-env saved-cont)) (set! env saved-env) (set! exp exp2) (value-of/k)) (let3-cont2 (var1 val1 var2 var3 exp3 body saved-env saved-cont) (set! cont (let3-cont3 var1 val1 var2 val var3 body saved-env saved-cont)) (set! env saved-env) (set! exp exp3) (value-of/k)) (let3-cont3 (var1 val1 var2 val2 var3 body saved-env saved-cont) (set! cont saved-cont) (set! env (extend-env var3 (newref val) (extend-env var2 (newref val2) (extend-env var1 (newref val1) saved-env)))) (set! exp body) (value-of/k)) (cons-cont1 (exp2 saved-env saved-cont) (set! cont (cons-cont2 val saved-cont)) (set! env saved-env) (set! exp exp2) (value-of/k)) (cons-cont2 (val1 saved-cont) (set! cont saved-cont) (set! val (list-val (list val1 val))) (apply-cont)) (car-cont (saved-cont) (set! cont saved-cont) (set! val (car (expval->list val))) (apply-cont)) (cdr-cont (saved-cont) (set! cont saved-cont) (set! val (cadr (expval->list val))) (apply-cont)) (null?-cont (saved-cont) (cases expval val (list-val (alist) (set! cont saved-cont) (set! val (bool-val (null? alist))) (apply-cont)) (else (eopl:error "expected list-val")))) (list-rest-cont (exps saved-env saved-cont) (set! cont (list-first-cont val saved-cont)) (set! exp exps) (set! env saved-env) (value-of/k)) (list-first-cont (val1 saved-cont) (set! cont saved-cont) (set! val (list-val (cons val1 (expval->list val)))) (apply-cont)) (letmul-cont (vars exps body body-eval-env binding-eval-env saved-cont) (if (null? exps) (begin (set! cont saved-cont) (set! env (extend-env (car vars) (newref val) body-eval-env)) (set! exp body) (value-of/k)) (begin (set! cont (letmul-cont (cdr vars) (cdr exps) body (extend-env (car vars) (newref val) body-eval-env) binding-eval-env saved-cont)) (set! env binding-eval-env) (set! exp (car exps))))) (set-rhs-cont (saved-env var saved-cont) (set! cont saved-cont) (set! val (setref! (apply-env saved-env var) val)) (apply-cont)) (begin-exp-cont (other-exps saved-env saved-cont) (if (null? other-exps) (begin (set! cont saved-cont) (apply-cont)) (begin (set! cont (begin-exp-cont (cdr other-exps) saved-env saved-cont)) (set! exp (car other-exps)) (set! env saved-env) (value-of/k)))) (else (eopl:error "unkonw type of continuation. ~s" cont)) ))) Global Register (define exp 'uninitialized) (define env 'uninitialized) (define cont 'uninitialized) (define val 'uninitialized) (define proc1 'uninitialized) String - > ExpVal (define run (lambda (text) (value-of-program (scan-parse text)))) Program - > ExpVal (define value-of-program (lambda (pgm) (cases program pgm (a-program (exp1) (initialize-store!) (set! cont (end-cont)) (set! exp exp1) (set! env (init-env)) (value-of/k))))) Expression X Environemnt x Continutation - > FinalAnswer ( ExpVal ) (define value-of/k (lambda () (begin (eopl:pretty-print "==========================") (eopl:pretty-print exp) (eopl:pretty-print env) (eopl:pretty-print cont) (value-of/k-inner)))) (define value-of/k-inner (lambda () (cases expression exp (const-exp (num) (set! val (num-val num)) (apply-cont)) (var-exp (var) (set! val (deref (apply-env env var))) (apply-cont)) (proc-exp (vars body) (set! val (proc-val (procedure vars body env))) (apply-cont)) (letrec-exp (p-name p-vars p-body letrec-body) (set! exp letrec-body) (set! env (extend-env-rec p-name p-vars p-body env)) (value-of/k)) (zero?-exp (exp1) (set! cont (zero-cont cont)) (set! exp exp1) (value-of/k)) (let-exp (var exp1 body) (set! cont (let-exp-cont var body env cont)) (set! exp exp1) (value-of/k)) (if-exp (exp1 exp2 exp3) (set! cont (if-test-cont exp2 exp3 env cont)) (set! exp exp1) (value-of/k)) (mul-exp (exp1 exp2) (set! cont (mul1-cont exp2 env cont)) (set! exp exp1) (value-of/k)) (diff-exp (exp1 exp2) (set! cont (diff1-cont exp2 env cont)) (set! exp exp1) (value-of/k)) (call-exp (exp1 exps) (set! cont (rator-cont exps env cont)) (set! exp exp1) (value-of/k)) (let2-exp (var1 exp1 var2 exp2 body) (set! cont (let2-cont1 var1 var2 exp2 body env cont)) (set! exp exp1) (value-of/k)) (let3-exp (var1 exp1 var2 exp2 var3 exp3 body) (set! cont (let3-cont1 var1 var2 exp2 var3 exp3 body env cont)) (set! exp exp1) (value-of/k)) (cons-exp (exp1 exp2) (set! cont (cons-cont1 exp2 env cont)) (set! exp exp1) (value-of/k)) (car-exp (exp1) (set! cont (car-cont cont)) (set! exp exp1) (value-of/k)) (cdr-exp (exp1) (set! cont (cdr-cont cont)) (set! exp exp1) (value-of/k)) (null?-exp (exp1) (set! cont (null?-cont cont)) (set! exp exp1) (value-of/k)) (emptylist-exp () (set! val (list-val '())) (apply-cont)) (list-exp (exps) (if (null? exps) (begin (set! val (list-val '())) (apply-cont)) (begin (set! cont (list-rest-cont (list-exp (cdr exps)) env cont)) (set! exp exps) (value-of/k)))) (letmul-exp (vars exps body) (set! cont (letmul-cont vars (cdr exps) body env env cont)) (set! exp (car exps)) (value-of/k)) (assign-exp (var exp1) (set! cont (set-rhs-cont env var cont)) (set! exp exp1) (value-of/k)) (begin-exp (exp-first other-exps) (set! cont (begin-exp-cont other-exps env cont)) (set! exp exp-first) (value-of/k)) (else (eopl:error "cannot handle expression: ~s" exp)) ))) (run "letrec fun(k) = if zero?(k) then 1 else (fun -(k,1)) in (fun 1)")
ada171d725c5187e539b3e9027f01a3cb23c4a697e61bb8d769aef8c2f72bf05
NyanCAD/Mosaic
libman.cljs
SPDX - FileCopyrightText : 2022 ; SPDX - License - Identifier : MPL-2.0 (ns nyancad.mosaic.libman (:require clojure.string [reagent.core :as r] [reagent.dom :as rd] [nyancad.hipflask :refer [pouch-atom pouchdb sep watch-changes]] [nyancad.mosaic.common :as cm])) ; initialise the model database (def params (js/URLSearchParams. js/window.location.search)) (def dbname (or (.get params "db") (js/localStorage.getItem "db") "schematics")) (def dburl (if js/window.dburl (.-href (js/URL. dbname js/window.dburl)) dbname)) (def sync (or (.get params "sync") (js/localStorage.getItem "sync") js/window.default_sync)) (defonce db (pouchdb dburl)) (defonce modeldb (pouch-atom db "models" (r/atom {}))) (defonce snapshots (pouch-atom db "snapshots" (r/atom {}))) (defonce watcher (watch-changes db modeldb snapshots)) ; used for ephermeal UI state (defonce selcat (r/atom [])) (defonce selcell (r/atom nil)) (defonce selmod (r/atom nil)) (defonce syncactive (r/atom false)) (defonce modal-content (r/atom nil)) (defn modal [] [:div.modal.window {:class (if @modal-content "visible" "hidden")} @modal-content]) (defonce context-content (r/atom {:x 0 :y 0 :body nil})) (defn contextmenu [] (let [{:keys [:x :y :body]} @context-content] [:div.contextmenu.window {:style {:top y, :left, x} :class (if body "visible" "hidden")} body])) (defn prompt [text cb] (reset! modal-content [:form {:on-submit (fn [^js e] (js/console.log e) (.preventDefault e) (let [name (.. e -target -elements -valuefield -value)] (when (seq name) (cb name))) (reset! modal-content nil))} [:div text] [:input {:name "valuefield" :type "text" :auto-focus true}] [:button {:on-click #(reset! modal-content nil)} "Cancel"] [:input {:type "submit" :value "Ok"}]])) (defn alert [text] (reset! modal-content [:div [:p text] [:button {:on-click #(reset! modal-content nil)} "Ok"]])) (defn cell-context-menu [e db cellname] (.preventDefault e) (reset! context-content {:x (.-clientX e), :y (.-clientY e) :body [:ul [:li {:on-click #(swap! db dissoc cellname)} "delete"]]})) (defn vec-startswith [v prefix] (= (subvec v 0 (min (count v) (count prefix))) prefix)) (defn cell-categories [cell] (map #(conj (clojure.string/split % "/") (:_id cell)) (conj (mapcat :categories (vals (:models cell))) "Everything"))) (defn category-trie [models] (->> (vals models) (mapcat cell-categories) (reduce #(assoc-in %1 %2 {}) {}))) (defn categories [base trie] [:<> (doall (for [[cat subtrie] trie :when (and (seq cat) (seq subtrie)) ; branch :let [path (conj base cat)]] [:details.tree {:key path :class path :open (vec-startswith @selcat path) :on-toggle #(when (.. % -target -open) (.stopPropagation %) (reset! selcell nil) (reset! selmod nil) (reset! selcat path))} [:summary cat] [:div.detailbody [categories path subtrie]]])) [cm/radiobuttons selcell (doall (for [[cat subtrie] trie :when (empty? subtrie) ; leaf :let [cell (get @modeldb cat) cname (second (.split cat ":"))]] ; inactive, active, key, title [(get cell :name cname) [cm/renamable (r/cursor modeldb [cat :name])] cat cname])) nil (fn [key] #(cell-context-menu % modeldb key))]]) (defn database-selector [] [:div.cellsel (if (seq @modeldb) [categories [] (category-trie @modeldb)] [:div.empty "There aren't any interfaces yet. Open a different workspace or click \"Add interface\" to get started."])]) (defn edit-url [cell mod] (let [mname (str cell "$" mod)] (doto (js/URL. "editor" js/window.location) (.. -searchParams (append "schem" mname)) (.. -searchParams (append "db" dbname)) (.. -searchParams (append "sync" sync))))) (defn schem-context-menu [e db cellname key] (.preventDefault e) (reset! context-content {:x (.-clientX e), :y (.-clientY e) :body [:ul [:li {:on-click #(js/window.open (edit-url (second (.split cellname ":")) (name key)), cellname)} "edit"] [:li {:on-click #(swap! db update-in [cellname :models] dissoc key)} "delete"]]})) (defn schematic-selector [db] (let [cellname @selcell cell (get @db cellname)] [:div.schematics (if @selcell [cm/radiobuttons selmod (doall (for [[key mod] (:models cell) :when (or (= @selcat ["Everything"]) (some (partial = (apply str (interpose "/" @selcat))) (:categories mod))) :let [schem? (= (get-in cell [:models key :type]) "schematic") icon (if schem? cm/schemmodel cm/codemodel)]] ; inactive, active, key, title [[:span [icon] " " (get mod :name key)] [:span [icon] " " [cm/renamable (r/cursor db [cellname :models key :name])]] key key])) (fn [key] (when (= (get-in cell [:models key :type]) "schematic") #(js/window.open (edit-url (second (.split cellname ":")) (name key)), cellname))) (fn [key] #(schem-context-menu % db cellname key))] [:div.empty "There are no implementations to show. Select an interface to edit its schematics and SPICE models."])])) (defn db-properties [] [:div.dbprops [:details [:summary "Workspace properties"] [:form.properties [:label {:for "dbname"} "Name"] [:input {:id "dbname" :name "db" :default-value dbname}] [:label {:for "dbsync"} "URL"] [:input {:id "dbsync" :name "sync" :default-value sync}] [:button.primary {:type "submit"} [cm/connect] "Open"]]]]) (defn shape-selector [cell] (let [[width height] (:bg @cell) width (+ 2 width) height (+ 2 height)] [:table [:tbody (doall (for [y (range height)] [:tr {:key y} (doall (for [x (range width) :let [handler (fn [^js e] (if (.. e -target -checked) (swap! cell update :conn cm/set-coord [x y "#"]) (swap! cell update :conn cm/remove-coord [x y "#"])))]] [:td {:key x} [:input {:type "checkbox" :checked (cm/has-coord (:conn @cell) [x y]) :on-change handler}]]))]))]])) (defn background-selector [cell] [:<> [:label {:for "bgwidth" :title "Width of the background tile"} "Background width"] [:input {:id "bgwidth" :type "number" :default-value (get (:bg @cell) 0 1) :on-change (cm/debounce #(swap! cell update :bg (fnil assoc [0 0]) 0 (js/parseInt (.. % -target -value))))}] [:label {:for "bgheight" :title "Width of the background tile"} "Background height"] [:input {:id "bgheigt" :type "number" :default-value (get (:bg @cell) 1 1) :on-change (cm/debounce #(swap! cell update :bg (fnil assoc [0 0]) 1 (js/parseInt (.. % -target -value))))}]]) (defn port-namer [cell] [:<> (for [[x y name] (:conn @cell) :let [handler (cm/debounce #(swap! cell update :conn cm/set-coord [x y (.. % -target -value)]))]] [:<> {:key [x y]} [:label {:for (str "port" x ":" y) :title "Port name"} x "/" y] [:input {:id (str "port" x ":" y) :type "text" :default-value name :on-change handler}]])]) (defn cell-properties [db] (let [cell @selcell sc (r/cursor db [cell])] (if cell [:<> [:div.properties [background-selector sc] [:label {:for "ports" :title "pattern for the device ports"} "ports"] [shape-selector sc] [port-namer sc] [:label {:for "symurl" :title "image url for this component"} "url"] [:input {:id "symurl" :type "text" :default-value (get-in @db [cell :sym]) :on-blur #(swap! db assoc-in [cell :sym] (.. % -target -value))}]]] [:div.empty "Select an interface to edit its properties."]))) (def dialect (r/atom "NgSpice")) (defn model-preview [db] (let [mod (r/cursor db [@selcell :models (keyword @selmod) (keyword @dialect)])] (prn @mod) [:div.properties (if (= (get-in @db [@selcell :models (keyword @selmod) :type]) "spice") [:<> [:label {:for "dialect"} "Simulator"] [:select {:id "dialect" :type "text" :value @dialect :on-change #(reset! dialect (.. % -target -value))} [:option "NgSpice"] [:option "Xyce"]] [:label {:for "reftempl"} "Reference template"] [cm/dbfield :textarea {:id "reftempl", :placeholder "X{name} {ports} {properties}"} mod :reftempl #(swap! %1 assoc :reftempl %2)] [:label {:for "decltempl"} "Declaration template"] [cm/dbfield :textarea {:id "decltempl"} mod :decltempl #(swap! %1 assoc :decltempl %2)] [:label {:for "vectors" :title "Comma-seperated device outputs to save"} "Vectors"] [cm/dbfield :input {:id "vectors", :placeholder "id, gm"} mod #(apply str (interpose ", " (:vectors %))) #(swap! %1 assoc :vectors (clojure.string/split %2 #", " -1))] (when (clojure.string/starts-with? (clojure.string/lower-case (:reftempl @mod "")) "x") [:<> [:label {:for "vectorcomp" :title "For subcircuits, the name of the thing inside of which to save vectors"} "Main component"] [cm/dbfield :input {:id "vectorcomp"} mod :component #(swap! %1 assoc :component %2)]])] (when (and @selcell @selmod) [:<> [:a {:href (edit-url (second (.split @selcell ":")) (name @selmod)) :target @selcell} "Edit"]])) (if (and @selcell @selmod) [:<> [:label {:for "categories" :title "Comma-seperated device categories"} "Categories"] [cm/dbfield :input {:id "categories"} mod #(apply str (interpose ", " (:categories %))) #(swap! %1 assoc :categories (clojure.string/split %2 #", " -1))]] [:div.empty "Select a schematic or SPICE model to edit its properties."])])) (defn cell-view [] (let [add-cell #(prompt "Enter the name of the new interface" (fn [name] (swap! modeldb assoc (str "models" sep name) {:name name}))) add-schem #(prompt "Enter the name of the new schematic" (fn [name] (swap! modeldb assoc-in [@selcell :models (keyword name)] {:name name, :type "schematic"}))) add-spice #(prompt "Enter the name of the new SPICE model" (fn [name] (swap! modeldb assoc-in [@selcell :models (keyword name)] {:name name :type "spice"})))] [:<> [:div.schsel [:div.addbuttons [:button {:on-click add-cell :disabled (nil? @selcat)} [cm/add-cell] "Add interface"] [:div.buttongroup.primary [:button {:on-click add-schem :disabled (or (nil? @selcat) (nil? @selcell))} [cm/add-model] "Add schematic"] [:details [:summary.button] [:button {:on-click add-spice :disabled (or (nil? @selcat) (nil? @selcell))} [cm/add-model] "Add SPICE model"]]]] [:h2 "Interface " (when-let [cell @selcell] (second (.split cell ":")))] [schematic-selector modeldb]] [:div.proppane [:div.preview [model-preview modeldb]] [:h3 "Interface properties"] [cell-properties modeldb]]])) (defn library-manager [] [:<> [:div.libraries [:div.libhead [:h1 "Libraries"] (if @syncactive [:span.syncstatus.active {:title "saving changes"} [cm/sync-active]] [:span.syncstatus.done {:title "changes saved"} [cm/sync-done]])] [database-selector] [db-properties]] [cell-view] [contextmenu] [modal]]) (def shortcuts {}) (defn ^:dev/after-load render [] (rd/render [library-manager] (.getElementById js/document "mosaic_libman"))) (defn synchronise [] (when (seq sync) ; pass nil to disable synchronization (let [es (.sync db sync #js{:live true})] (.on es "paused" #(reset! syncactive false)) (.on es "active" #(reset! syncactive true)) (.on es "denied" #(alert (str "Permission denied synchronising to " sync ", changes are saved locally"))) (.on es "error" #(alert (str "Error synchronising to " sync ", changes are saved locally")))))) (defn ^:export init [] ;; (set! js/document.onkeyup (partial cm/keyboard-shortcuts shortcuts)) (set! js/window.name "libman") (set! js/document.onclick #(swap! context-content assoc :body nil)) (js/localStorage.setItem "db" dbname) (when (seq sync) (js/localStorage.setItem "sync" sync)) (synchronise) (render))
null
https://raw.githubusercontent.com/NyanCAD/Mosaic/ea210a8b33d90584ed3c690386a74dc28d0f0181/src/main/nyancad/mosaic/libman.cljs
clojure
initialise the model database used for ephermeal UI state branch leaf inactive, active, key, title inactive, active, key, title pass nil to disable synchronization (set! js/document.onkeyup (partial cm/keyboard-shortcuts shortcuts))
SPDX - FileCopyrightText : 2022 SPDX - License - Identifier : MPL-2.0 (ns nyancad.mosaic.libman (:require clojure.string [reagent.core :as r] [reagent.dom :as rd] [nyancad.hipflask :refer [pouch-atom pouchdb sep watch-changes]] [nyancad.mosaic.common :as cm])) (def params (js/URLSearchParams. js/window.location.search)) (def dbname (or (.get params "db") (js/localStorage.getItem "db") "schematics")) (def dburl (if js/window.dburl (.-href (js/URL. dbname js/window.dburl)) dbname)) (def sync (or (.get params "sync") (js/localStorage.getItem "sync") js/window.default_sync)) (defonce db (pouchdb dburl)) (defonce modeldb (pouch-atom db "models" (r/atom {}))) (defonce snapshots (pouch-atom db "snapshots" (r/atom {}))) (defonce watcher (watch-changes db modeldb snapshots)) (defonce selcat (r/atom [])) (defonce selcell (r/atom nil)) (defonce selmod (r/atom nil)) (defonce syncactive (r/atom false)) (defonce modal-content (r/atom nil)) (defn modal [] [:div.modal.window {:class (if @modal-content "visible" "hidden")} @modal-content]) (defonce context-content (r/atom {:x 0 :y 0 :body nil})) (defn contextmenu [] (let [{:keys [:x :y :body]} @context-content] [:div.contextmenu.window {:style {:top y, :left, x} :class (if body "visible" "hidden")} body])) (defn prompt [text cb] (reset! modal-content [:form {:on-submit (fn [^js e] (js/console.log e) (.preventDefault e) (let [name (.. e -target -elements -valuefield -value)] (when (seq name) (cb name))) (reset! modal-content nil))} [:div text] [:input {:name "valuefield" :type "text" :auto-focus true}] [:button {:on-click #(reset! modal-content nil)} "Cancel"] [:input {:type "submit" :value "Ok"}]])) (defn alert [text] (reset! modal-content [:div [:p text] [:button {:on-click #(reset! modal-content nil)} "Ok"]])) (defn cell-context-menu [e db cellname] (.preventDefault e) (reset! context-content {:x (.-clientX e), :y (.-clientY e) :body [:ul [:li {:on-click #(swap! db dissoc cellname)} "delete"]]})) (defn vec-startswith [v prefix] (= (subvec v 0 (min (count v) (count prefix))) prefix)) (defn cell-categories [cell] (map #(conj (clojure.string/split % "/") (:_id cell)) (conj (mapcat :categories (vals (:models cell))) "Everything"))) (defn category-trie [models] (->> (vals models) (mapcat cell-categories) (reduce #(assoc-in %1 %2 {}) {}))) (defn categories [base trie] [:<> (doall (for [[cat subtrie] trie :let [path (conj base cat)]] [:details.tree {:key path :class path :open (vec-startswith @selcat path) :on-toggle #(when (.. % -target -open) (.stopPropagation %) (reset! selcell nil) (reset! selmod nil) (reset! selcat path))} [:summary cat] [:div.detailbody [categories path subtrie]]])) [cm/radiobuttons selcell (doall (for [[cat subtrie] trie :let [cell (get @modeldb cat) cname (second (.split cat ":"))]] [(get cell :name cname) [cm/renamable (r/cursor modeldb [cat :name])] cat cname])) nil (fn [key] #(cell-context-menu % modeldb key))]]) (defn database-selector [] [:div.cellsel (if (seq @modeldb) [categories [] (category-trie @modeldb)] [:div.empty "There aren't any interfaces yet. Open a different workspace or click \"Add interface\" to get started."])]) (defn edit-url [cell mod] (let [mname (str cell "$" mod)] (doto (js/URL. "editor" js/window.location) (.. -searchParams (append "schem" mname)) (.. -searchParams (append "db" dbname)) (.. -searchParams (append "sync" sync))))) (defn schem-context-menu [e db cellname key] (.preventDefault e) (reset! context-content {:x (.-clientX e), :y (.-clientY e) :body [:ul [:li {:on-click #(js/window.open (edit-url (second (.split cellname ":")) (name key)), cellname)} "edit"] [:li {:on-click #(swap! db update-in [cellname :models] dissoc key)} "delete"]]})) (defn schematic-selector [db] (let [cellname @selcell cell (get @db cellname)] [:div.schematics (if @selcell [cm/radiobuttons selmod (doall (for [[key mod] (:models cell) :when (or (= @selcat ["Everything"]) (some (partial = (apply str (interpose "/" @selcat))) (:categories mod))) :let [schem? (= (get-in cell [:models key :type]) "schematic") icon (if schem? cm/schemmodel cm/codemodel)]] [[:span [icon] " " (get mod :name key)] [:span [icon] " " [cm/renamable (r/cursor db [cellname :models key :name])]] key key])) (fn [key] (when (= (get-in cell [:models key :type]) "schematic") #(js/window.open (edit-url (second (.split cellname ":")) (name key)), cellname))) (fn [key] #(schem-context-menu % db cellname key))] [:div.empty "There are no implementations to show. Select an interface to edit its schematics and SPICE models."])])) (defn db-properties [] [:div.dbprops [:details [:summary "Workspace properties"] [:form.properties [:label {:for "dbname"} "Name"] [:input {:id "dbname" :name "db" :default-value dbname}] [:label {:for "dbsync"} "URL"] [:input {:id "dbsync" :name "sync" :default-value sync}] [:button.primary {:type "submit"} [cm/connect] "Open"]]]]) (defn shape-selector [cell] (let [[width height] (:bg @cell) width (+ 2 width) height (+ 2 height)] [:table [:tbody (doall (for [y (range height)] [:tr {:key y} (doall (for [x (range width) :let [handler (fn [^js e] (if (.. e -target -checked) (swap! cell update :conn cm/set-coord [x y "#"]) (swap! cell update :conn cm/remove-coord [x y "#"])))]] [:td {:key x} [:input {:type "checkbox" :checked (cm/has-coord (:conn @cell) [x y]) :on-change handler}]]))]))]])) (defn background-selector [cell] [:<> [:label {:for "bgwidth" :title "Width of the background tile"} "Background width"] [:input {:id "bgwidth" :type "number" :default-value (get (:bg @cell) 0 1) :on-change (cm/debounce #(swap! cell update :bg (fnil assoc [0 0]) 0 (js/parseInt (.. % -target -value))))}] [:label {:for "bgheight" :title "Width of the background tile"} "Background height"] [:input {:id "bgheigt" :type "number" :default-value (get (:bg @cell) 1 1) :on-change (cm/debounce #(swap! cell update :bg (fnil assoc [0 0]) 1 (js/parseInt (.. % -target -value))))}]]) (defn port-namer [cell] [:<> (for [[x y name] (:conn @cell) :let [handler (cm/debounce #(swap! cell update :conn cm/set-coord [x y (.. % -target -value)]))]] [:<> {:key [x y]} [:label {:for (str "port" x ":" y) :title "Port name"} x "/" y] [:input {:id (str "port" x ":" y) :type "text" :default-value name :on-change handler}]])]) (defn cell-properties [db] (let [cell @selcell sc (r/cursor db [cell])] (if cell [:<> [:div.properties [background-selector sc] [:label {:for "ports" :title "pattern for the device ports"} "ports"] [shape-selector sc] [port-namer sc] [:label {:for "symurl" :title "image url for this component"} "url"] [:input {:id "symurl" :type "text" :default-value (get-in @db [cell :sym]) :on-blur #(swap! db assoc-in [cell :sym] (.. % -target -value))}]]] [:div.empty "Select an interface to edit its properties."]))) (def dialect (r/atom "NgSpice")) (defn model-preview [db] (let [mod (r/cursor db [@selcell :models (keyword @selmod) (keyword @dialect)])] (prn @mod) [:div.properties (if (= (get-in @db [@selcell :models (keyword @selmod) :type]) "spice") [:<> [:label {:for "dialect"} "Simulator"] [:select {:id "dialect" :type "text" :value @dialect :on-change #(reset! dialect (.. % -target -value))} [:option "NgSpice"] [:option "Xyce"]] [:label {:for "reftempl"} "Reference template"] [cm/dbfield :textarea {:id "reftempl", :placeholder "X{name} {ports} {properties}"} mod :reftempl #(swap! %1 assoc :reftempl %2)] [:label {:for "decltempl"} "Declaration template"] [cm/dbfield :textarea {:id "decltempl"} mod :decltempl #(swap! %1 assoc :decltempl %2)] [:label {:for "vectors" :title "Comma-seperated device outputs to save"} "Vectors"] [cm/dbfield :input {:id "vectors", :placeholder "id, gm"} mod #(apply str (interpose ", " (:vectors %))) #(swap! %1 assoc :vectors (clojure.string/split %2 #", " -1))] (when (clojure.string/starts-with? (clojure.string/lower-case (:reftempl @mod "")) "x") [:<> [:label {:for "vectorcomp" :title "For subcircuits, the name of the thing inside of which to save vectors"} "Main component"] [cm/dbfield :input {:id "vectorcomp"} mod :component #(swap! %1 assoc :component %2)]])] (when (and @selcell @selmod) [:<> [:a {:href (edit-url (second (.split @selcell ":")) (name @selmod)) :target @selcell} "Edit"]])) (if (and @selcell @selmod) [:<> [:label {:for "categories" :title "Comma-seperated device categories"} "Categories"] [cm/dbfield :input {:id "categories"} mod #(apply str (interpose ", " (:categories %))) #(swap! %1 assoc :categories (clojure.string/split %2 #", " -1))]] [:div.empty "Select a schematic or SPICE model to edit its properties."])])) (defn cell-view [] (let [add-cell #(prompt "Enter the name of the new interface" (fn [name] (swap! modeldb assoc (str "models" sep name) {:name name}))) add-schem #(prompt "Enter the name of the new schematic" (fn [name] (swap! modeldb assoc-in [@selcell :models (keyword name)] {:name name, :type "schematic"}))) add-spice #(prompt "Enter the name of the new SPICE model" (fn [name] (swap! modeldb assoc-in [@selcell :models (keyword name)] {:name name :type "spice"})))] [:<> [:div.schsel [:div.addbuttons [:button {:on-click add-cell :disabled (nil? @selcat)} [cm/add-cell] "Add interface"] [:div.buttongroup.primary [:button {:on-click add-schem :disabled (or (nil? @selcat) (nil? @selcell))} [cm/add-model] "Add schematic"] [:details [:summary.button] [:button {:on-click add-spice :disabled (or (nil? @selcat) (nil? @selcell))} [cm/add-model] "Add SPICE model"]]]] [:h2 "Interface " (when-let [cell @selcell] (second (.split cell ":")))] [schematic-selector modeldb]] [:div.proppane [:div.preview [model-preview modeldb]] [:h3 "Interface properties"] [cell-properties modeldb]]])) (defn library-manager [] [:<> [:div.libraries [:div.libhead [:h1 "Libraries"] (if @syncactive [:span.syncstatus.active {:title "saving changes"} [cm/sync-active]] [:span.syncstatus.done {:title "changes saved"} [cm/sync-done]])] [database-selector] [db-properties]] [cell-view] [contextmenu] [modal]]) (def shortcuts {}) (defn ^:dev/after-load render [] (rd/render [library-manager] (.getElementById js/document "mosaic_libman"))) (defn synchronise [] (let [es (.sync db sync #js{:live true})] (.on es "paused" #(reset! syncactive false)) (.on es "active" #(reset! syncactive true)) (.on es "denied" #(alert (str "Permission denied synchronising to " sync ", changes are saved locally"))) (.on es "error" #(alert (str "Error synchronising to " sync ", changes are saved locally")))))) (defn ^:export init [] (set! js/window.name "libman") (set! js/document.onclick #(swap! context-content assoc :body nil)) (js/localStorage.setItem "db" dbname) (when (seq sync) (js/localStorage.setItem "sync" sync)) (synchronise) (render))
cbdd914530407143e020aac367aaf4291ce8233bf63ecebb9554e2d6adfb2acb
ocaml-flambda/flambda-backend
simplify_primitives.ml
(**************************************************************************) (* *) (* OCaml *) (* *) , OCamlPro and , (* *) (* Copyright 2013--2016 OCamlPro SAS *) Copyright 2014 - -2016 Jane Street Group LLC (* *) (* All rights reserved. This file is distributed under the terms of *) the GNU Lesser General Public License version 2.1 , with the (* special exception on linking described in the file LICENSE. *) (* *) (**************************************************************************) [@@@ocaml.warning "+a-4-9-30-40-41-42-66"] open! Int_replace_polymorphic_compare module A = Simple_value_approx module C = Inlining_cost module I = Simplify_boxed_integer_ops module S = Simplify_common let phys_equal (approxs:A.t list) = match approxs with | [] | [_] | _ :: _ :: _ :: _ -> Misc.fatal_error "wrong number of arguments for equality" | [a1; a2] -> (* N.B. The following would be incorrect if the variables are not bound in the environment: match a1.var, a2.var with | Some v1, Some v2 when Variable.equal v1 v2 -> true | _ -> ... *) match a1.symbol, a2.symbol with | Some (s1, None), Some (s2, None) -> Symbol.equal s1 s2 | Some (s1, Some f1), Some (s2, Some f2) -> Symbol.equal s1 s2 && f1 = f2 | _ -> false let is_known_to_be_some_kind_of_int (arg:A.descr) = match arg with | Value_int _ | Value_char _ -> true | Value_block _ | Value_float _ | Value_set_of_closures _ | Value_closure _ | Value_string _ | Value_float_array _ | A.Value_boxed_int _ | Value_unknown _ | Value_extern _ | Value_symbol _ | Value_unresolved _ | Value_bottom -> false let is_known_to_be_some_kind_of_block (arg:A.descr) = match arg with | Value_block _ | Value_float _ | Value_float_array _ | A.Value_boxed_int _ | Value_closure _ | Value_string _ -> true | Value_set_of_closures _ | Value_int _ | Value_char _ | Value_unknown _ | Value_extern _ | Value_symbol _ | Value_unresolved _ | Value_bottom -> false let rec structurally_different (arg1:A.t) (arg2:A.t) = match arg1.descr, arg2.descr with | (Value_int n1), (Value_int n2) when n1 <> n2 -> true | Value_block (tag1, fields1), Value_block (tag2, fields2) -> not (Tag.equal tag1 tag2) || (Array.length fields1 <> Array.length fields2) || Misc.Stdlib.Array.exists2 structurally_different fields1 fields2 | descr1, descr2 -> (* This is not very precise as this won't allow to distinguish blocks from strings for instance. This can be improved if it is deemed valuable. *) (is_known_to_be_some_kind_of_int descr1 && is_known_to_be_some_kind_of_block descr2) || (is_known_to_be_some_kind_of_block descr1 && is_known_to_be_some_kind_of_int descr2) let phys_different (approxs:A.t list) = match approxs with | [] | [_] | _ :: _ :: _ :: _ -> Misc.fatal_error "wrong number of arguments for equality" | [a1; a2] -> structurally_different a1 a2 let is_empty = function | [] -> true | _ :: _ -> false let is_pisint = function | Clambda_primitives.Pisint -> true | _ -> false let is_pstring_length = function | Clambda_primitives.Pstringlength -> true | _ -> false let is_pbytes_length = function | Clambda_primitives.Pbyteslength -> true | _ -> false let is_pstringrefs = function | Clambda_primitives.Pstringrefs -> true | _ -> false let is_pbytesrefs = function | Clambda_primitives.Pbytesrefs -> true | _ -> false let primitive (p : Clambda_primitives.primitive) (args, approxs) expr dbg ~size_int : Flambda.named * A.t * Inlining_cost.Benefit.t = let fpc = !Clflags.float_const_prop in match p with | Pmakeblock(tag_int, (Immutable | Immutable_unique), shape, mode) -> let tag = Tag.create_exn tag_int in let shape = match shape with | None -> List.map (fun _ -> Lambda.Pgenval) args | Some shape -> List.map (fun kind -> kind) shape in let approxs = List.map2 A.augment_with_kind approxs shape in let shape = List.map2 A.augment_kind_with_approx approxs shape in Prim (Pmakeblock(tag_int, Lambda.Immutable, Some shape, mode), args, dbg), A.value_block tag (Array.of_list approxs), C.Benefit.zero | Praise _ -> expr, A.value_bottom, C.Benefit.zero | Pmakearray(_, _, mode) when is_empty approxs -> Prim (Pmakeblock(0, Lambda.Immutable, Some [], mode), [], dbg), A.value_block (Tag.create_exn 0) [||], C.Benefit.zero | Pmakearray (Pfloatarray, Mutable, _) -> let approx = A.value_mutable_float_array ~size:(List.length args) in expr, approx, C.Benefit.zero | Pmakearray (Pfloatarray, (Immutable | Immutable_unique), _) -> let approx = A.value_immutable_float_array (Array.of_list approxs) in expr, approx, C.Benefit.zero | Pintcomp Ceq when phys_equal approxs -> S.const_bool_expr expr true | Pintcomp Cne when phys_equal approxs -> S.const_bool_expr expr false N.B. Having [ not ( phys_equal approxs ) ] would not on its own tell us anything about whether the two values concerned are unequal . To judge that , it would be necessary to prove that the approximations are different , which would in turn entail them being completely known . It may seem that in the case where we have two approximations each annotated with a symbol that we should be able to judge inequality even if part of the approximation description(s ) are unknown . This is unfortunately not the case . Here is an example : let a = f 1 let b = f 1 let c = a , a let d = b , b If [ Share_constants ] is run before [ f ] is completely inlined ( assuming [ f ] always generates the same result ; effects of [ f ] are n't in fact relevant ) then [ c ] and [ d ] will not be shared . However if [ f ] is inlined later , [ a ] and [ b ] could be shared and thus [ c ] and [ d ] could be too . As such , any intermediate non - aliasing judgement would be invalid . anything about whether the two values concerned are unequal. To judge that, it would be necessary to prove that the approximations are different, which would in turn entail them being completely known. It may seem that in the case where we have two approximations each annotated with a symbol that we should be able to judge inequality even if part of the approximation description(s) are unknown. This is unfortunately not the case. Here is an example: let a = f 1 let b = f 1 let c = a, a let d = b, b If [Share_constants] is run before [f] is completely inlined (assuming [f] always generates the same result; effects of [f] aren't in fact relevant) then [c] and [d] will not be shared. However if [f] is inlined later, [a] and [b] could be shared and thus [c] and [d] could be too. As such, any intermediate non-aliasing judgement would be invalid. *) | Pintcomp Ceq when phys_different approxs -> S.const_bool_expr expr false | Pintcomp Cne when phys_different approxs -> S.const_bool_expr expr true If two values are structurally different we are certain they can never be shared be shared*) | _ -> match A.descrs approxs with | [Value_int x] -> begin match p with | Pnot -> S.const_bool_expr expr (x = 0) | Pnegint -> S.const_int_expr expr (-x) | Pbswap16 -> S.const_int_expr expr (S.swap16 x) | Pisint -> S.const_bool_expr expr true | Poffsetint y -> S.const_int_expr expr (x + y) | Pfloatofint _ when fpc -> S.const_float_expr expr (float_of_int x) | Pbintofint (Pnativeint,_) -> S.const_boxed_int_expr expr Nativeint (Nativeint.of_int x) | Pbintofint (Pint32,_) -> S.const_boxed_int_expr expr Int32 (Int32.of_int x) | Pbintofint (Pint64,_) -> S.const_boxed_int_expr expr Int64 (Int64.of_int x) | _ -> expr, A.value_unknown Other, C.Benefit.zero end | [Value_int x; Value_int y] -> let shift_precond = 0 <= y && y < 8 * size_int in begin match p with | Paddint -> S.const_int_expr expr (x + y) | Psubint -> S.const_int_expr expr (x - y) | Pmulint -> S.const_int_expr expr (x * y) | Pdivint _ when y <> 0 -> S.const_int_expr expr (x / y) | Pmodint _ when y <> 0 -> S.const_int_expr expr (x mod y) | Pandint -> S.const_int_expr expr (x land y) | Porint -> S.const_int_expr expr (x lor y) | Pxorint -> S.const_int_expr expr (x lxor y) | Plslint when shift_precond -> S.const_int_expr expr (x lsl y) | Plsrint when shift_precond -> S.const_int_expr expr (x lsr y) | Pasrint when shift_precond -> S.const_int_expr expr (x asr y) | Pintcomp cmp -> S.const_integer_comparison_expr expr cmp x y | Pcompare_ints -> S.const_int_expr expr (compare x y) | Pisout -> S.const_bool_expr expr (y > x || y < 0) | _ -> expr, A.value_unknown Other, C.Benefit.zero end | [Value_char x; Value_char y] -> begin match p with | Pintcomp cmp -> S.const_integer_comparison_expr expr cmp x y | Pcompare_ints -> S.const_int_expr expr (Char.compare x y) | _ -> expr, A.value_unknown Other, C.Benefit.zero end | [Value_float (Some x)] when fpc -> begin match p with | Pintoffloat -> S.const_int_expr expr (int_of_float x) | Pnegfloat _ -> S.const_float_expr expr (-. x) | Pabsfloat _ -> S.const_float_expr expr (abs_float x) | _ -> expr, A.value_unknown Other, C.Benefit.zero end | [Value_float (Some n1); Value_float (Some n2)] when fpc -> begin match p with | Paddfloat _ -> S.const_float_expr expr (n1 +. n2) | Psubfloat _ -> S.const_float_expr expr (n1 -. n2) | Pmulfloat _ -> S.const_float_expr expr (n1 *. n2) | Pdivfloat _ -> S.const_float_expr expr (n1 /. n2) | Pfloatcomp c -> S.const_float_comparison_expr expr c n1 n2 | Pcompare_floats -> S.const_int_expr expr (Float.compare n1 n2) | _ -> expr, A.value_unknown Other, C.Benefit.zero end | [A.Value_boxed_int(A.Nativeint, n)] -> I.Simplify_boxed_nativeint.simplify_unop p Nativeint expr n | [A.Value_boxed_int(A.Int32, n)] -> I.Simplify_boxed_int32.simplify_unop p Int32 expr n | [A.Value_boxed_int(A.Int64, n)] -> I.Simplify_boxed_int64.simplify_unop p Int64 expr n | [A.Value_boxed_int(A.Nativeint, n1); A.Value_boxed_int(A.Nativeint, n2)] -> I.Simplify_boxed_nativeint.simplify_binop p Nativeint expr n1 n2 | [A.Value_boxed_int(A.Int32, n1); A.Value_boxed_int(A.Int32, n2)] -> I.Simplify_boxed_int32.simplify_binop p Int32 expr n1 n2 | [A.Value_boxed_int(A.Int64, n1); A.Value_boxed_int(A.Int64, n2)] -> I.Simplify_boxed_int64.simplify_binop p Int64 expr n1 n2 | [A.Value_boxed_int(A.Nativeint, n1); Value_int n2] -> I.Simplify_boxed_nativeint.simplify_binop_int p Nativeint expr n1 n2 ~size_int | [A.Value_boxed_int(A.Int32, n1); Value_int n2] -> I.Simplify_boxed_int32.simplify_binop_int p Int32 expr n1 n2 ~size_int | [A.Value_boxed_int(A.Int64, n1); Value_int n2] -> I.Simplify_boxed_int64.simplify_binop_int p Int64 expr n1 n2 ~size_int | [Value_block _] when is_pisint p -> S.const_bool_expr expr false | [Value_string { size }] when (is_pstring_length p || is_pbytes_length p) -> S.const_int_expr expr size | [Value_string { size; contents = Some s }; (Value_int x)] when x >= 0 && x < size -> begin match p with | Pstringrefu | Pstringrefs | Pbytesrefu | Pbytesrefs -> S.const_char_expr (Prim(Pstringrefu, args, dbg)) s.[x] | _ -> expr, A.value_unknown Other, C.Benefit.zero end | [Value_string { size; contents = None }; (Value_int x)] when x >= 0 && x < size && is_pstringrefs p -> Flambda.Prim (Pstringrefu, args, dbg), A.value_unknown Other, (* we improved it, but there is no way to account for that: *) C.Benefit.zero | [Value_string { size; contents = None }; (Value_int x)] when x >= 0 && x < size && is_pbytesrefs p -> Flambda.Prim (Pbytesrefu, args, dbg), A.value_unknown Other, (* we improved it, but there is no way to account for that: *) C.Benefit.zero | [Value_float_array { size; contents }] -> begin match p with | Parraylength _ -> S.const_int_expr expr size | Pfloatfield (i,_) -> begin match contents with | A.Contents a when i >= 0 && i < size -> begin match A.check_approx_for_float a.(i) with | None -> expr, a.(i), C.Benefit.zero | Some v -> S.const_float_expr expr v end | Contents _ | Unknown_or_mutable -> expr, A.value_unknown Other, C.Benefit.zero end | _ -> expr, A.value_unknown Other, C.Benefit.zero end | _ -> match Semantics_of_primitives.return_type_of_primitive p with | Float -> expr, A.value_any_float, C.Benefit.zero | Other -> expr, A.value_unknown Other, C.Benefit.zero
null
https://raw.githubusercontent.com/ocaml-flambda/flambda-backend/651e3119bfd6ed8d79d3139054093872b735fda1/middle_end/flambda/simplify_primitives.ml
ocaml
************************************************************************ OCaml Copyright 2013--2016 OCamlPro SAS All rights reserved. This file is distributed under the terms of special exception on linking described in the file LICENSE. ************************************************************************ N.B. The following would be incorrect if the variables are not bound in the environment: match a1.var, a2.var with | Some v1, Some v2 when Variable.equal v1 v2 -> true | _ -> ... This is not very precise as this won't allow to distinguish blocks from strings for instance. This can be improved if it is deemed valuable. we improved it, but there is no way to account for that: we improved it, but there is no way to account for that:
, OCamlPro and , Copyright 2014 - -2016 Jane Street Group LLC the GNU Lesser General Public License version 2.1 , with the [@@@ocaml.warning "+a-4-9-30-40-41-42-66"] open! Int_replace_polymorphic_compare module A = Simple_value_approx module C = Inlining_cost module I = Simplify_boxed_integer_ops module S = Simplify_common let phys_equal (approxs:A.t list) = match approxs with | [] | [_] | _ :: _ :: _ :: _ -> Misc.fatal_error "wrong number of arguments for equality" | [a1; a2] -> match a1.symbol, a2.symbol with | Some (s1, None), Some (s2, None) -> Symbol.equal s1 s2 | Some (s1, Some f1), Some (s2, Some f2) -> Symbol.equal s1 s2 && f1 = f2 | _ -> false let is_known_to_be_some_kind_of_int (arg:A.descr) = match arg with | Value_int _ | Value_char _ -> true | Value_block _ | Value_float _ | Value_set_of_closures _ | Value_closure _ | Value_string _ | Value_float_array _ | A.Value_boxed_int _ | Value_unknown _ | Value_extern _ | Value_symbol _ | Value_unresolved _ | Value_bottom -> false let is_known_to_be_some_kind_of_block (arg:A.descr) = match arg with | Value_block _ | Value_float _ | Value_float_array _ | A.Value_boxed_int _ | Value_closure _ | Value_string _ -> true | Value_set_of_closures _ | Value_int _ | Value_char _ | Value_unknown _ | Value_extern _ | Value_symbol _ | Value_unresolved _ | Value_bottom -> false let rec structurally_different (arg1:A.t) (arg2:A.t) = match arg1.descr, arg2.descr with | (Value_int n1), (Value_int n2) when n1 <> n2 -> true | Value_block (tag1, fields1), Value_block (tag2, fields2) -> not (Tag.equal tag1 tag2) || (Array.length fields1 <> Array.length fields2) || Misc.Stdlib.Array.exists2 structurally_different fields1 fields2 | descr1, descr2 -> (is_known_to_be_some_kind_of_int descr1 && is_known_to_be_some_kind_of_block descr2) || (is_known_to_be_some_kind_of_block descr1 && is_known_to_be_some_kind_of_int descr2) let phys_different (approxs:A.t list) = match approxs with | [] | [_] | _ :: _ :: _ :: _ -> Misc.fatal_error "wrong number of arguments for equality" | [a1; a2] -> structurally_different a1 a2 let is_empty = function | [] -> true | _ :: _ -> false let is_pisint = function | Clambda_primitives.Pisint -> true | _ -> false let is_pstring_length = function | Clambda_primitives.Pstringlength -> true | _ -> false let is_pbytes_length = function | Clambda_primitives.Pbyteslength -> true | _ -> false let is_pstringrefs = function | Clambda_primitives.Pstringrefs -> true | _ -> false let is_pbytesrefs = function | Clambda_primitives.Pbytesrefs -> true | _ -> false let primitive (p : Clambda_primitives.primitive) (args, approxs) expr dbg ~size_int : Flambda.named * A.t * Inlining_cost.Benefit.t = let fpc = !Clflags.float_const_prop in match p with | Pmakeblock(tag_int, (Immutable | Immutable_unique), shape, mode) -> let tag = Tag.create_exn tag_int in let shape = match shape with | None -> List.map (fun _ -> Lambda.Pgenval) args | Some shape -> List.map (fun kind -> kind) shape in let approxs = List.map2 A.augment_with_kind approxs shape in let shape = List.map2 A.augment_kind_with_approx approxs shape in Prim (Pmakeblock(tag_int, Lambda.Immutable, Some shape, mode), args, dbg), A.value_block tag (Array.of_list approxs), C.Benefit.zero | Praise _ -> expr, A.value_bottom, C.Benefit.zero | Pmakearray(_, _, mode) when is_empty approxs -> Prim (Pmakeblock(0, Lambda.Immutable, Some [], mode), [], dbg), A.value_block (Tag.create_exn 0) [||], C.Benefit.zero | Pmakearray (Pfloatarray, Mutable, _) -> let approx = A.value_mutable_float_array ~size:(List.length args) in expr, approx, C.Benefit.zero | Pmakearray (Pfloatarray, (Immutable | Immutable_unique), _) -> let approx = A.value_immutable_float_array (Array.of_list approxs) in expr, approx, C.Benefit.zero | Pintcomp Ceq when phys_equal approxs -> S.const_bool_expr expr true | Pintcomp Cne when phys_equal approxs -> S.const_bool_expr expr false N.B. Having [ not ( phys_equal approxs ) ] would not on its own tell us anything about whether the two values concerned are unequal . To judge that , it would be necessary to prove that the approximations are different , which would in turn entail them being completely known . It may seem that in the case where we have two approximations each annotated with a symbol that we should be able to judge inequality even if part of the approximation description(s ) are unknown . This is unfortunately not the case . Here is an example : let a = f 1 let b = f 1 let c = a , a let d = b , b If [ Share_constants ] is run before [ f ] is completely inlined ( assuming [ f ] always generates the same result ; effects of [ f ] are n't in fact relevant ) then [ c ] and [ d ] will not be shared . However if [ f ] is inlined later , [ a ] and [ b ] could be shared and thus [ c ] and [ d ] could be too . As such , any intermediate non - aliasing judgement would be invalid . anything about whether the two values concerned are unequal. To judge that, it would be necessary to prove that the approximations are different, which would in turn entail them being completely known. It may seem that in the case where we have two approximations each annotated with a symbol that we should be able to judge inequality even if part of the approximation description(s) are unknown. This is unfortunately not the case. Here is an example: let a = f 1 let b = f 1 let c = a, a let d = b, b If [Share_constants] is run before [f] is completely inlined (assuming [f] always generates the same result; effects of [f] aren't in fact relevant) then [c] and [d] will not be shared. However if [f] is inlined later, [a] and [b] could be shared and thus [c] and [d] could be too. As such, any intermediate non-aliasing judgement would be invalid. *) | Pintcomp Ceq when phys_different approxs -> S.const_bool_expr expr false | Pintcomp Cne when phys_different approxs -> S.const_bool_expr expr true If two values are structurally different we are certain they can never be shared be shared*) | _ -> match A.descrs approxs with | [Value_int x] -> begin match p with | Pnot -> S.const_bool_expr expr (x = 0) | Pnegint -> S.const_int_expr expr (-x) | Pbswap16 -> S.const_int_expr expr (S.swap16 x) | Pisint -> S.const_bool_expr expr true | Poffsetint y -> S.const_int_expr expr (x + y) | Pfloatofint _ when fpc -> S.const_float_expr expr (float_of_int x) | Pbintofint (Pnativeint,_) -> S.const_boxed_int_expr expr Nativeint (Nativeint.of_int x) | Pbintofint (Pint32,_) -> S.const_boxed_int_expr expr Int32 (Int32.of_int x) | Pbintofint (Pint64,_) -> S.const_boxed_int_expr expr Int64 (Int64.of_int x) | _ -> expr, A.value_unknown Other, C.Benefit.zero end | [Value_int x; Value_int y] -> let shift_precond = 0 <= y && y < 8 * size_int in begin match p with | Paddint -> S.const_int_expr expr (x + y) | Psubint -> S.const_int_expr expr (x - y) | Pmulint -> S.const_int_expr expr (x * y) | Pdivint _ when y <> 0 -> S.const_int_expr expr (x / y) | Pmodint _ when y <> 0 -> S.const_int_expr expr (x mod y) | Pandint -> S.const_int_expr expr (x land y) | Porint -> S.const_int_expr expr (x lor y) | Pxorint -> S.const_int_expr expr (x lxor y) | Plslint when shift_precond -> S.const_int_expr expr (x lsl y) | Plsrint when shift_precond -> S.const_int_expr expr (x lsr y) | Pasrint when shift_precond -> S.const_int_expr expr (x asr y) | Pintcomp cmp -> S.const_integer_comparison_expr expr cmp x y | Pcompare_ints -> S.const_int_expr expr (compare x y) | Pisout -> S.const_bool_expr expr (y > x || y < 0) | _ -> expr, A.value_unknown Other, C.Benefit.zero end | [Value_char x; Value_char y] -> begin match p with | Pintcomp cmp -> S.const_integer_comparison_expr expr cmp x y | Pcompare_ints -> S.const_int_expr expr (Char.compare x y) | _ -> expr, A.value_unknown Other, C.Benefit.zero end | [Value_float (Some x)] when fpc -> begin match p with | Pintoffloat -> S.const_int_expr expr (int_of_float x) | Pnegfloat _ -> S.const_float_expr expr (-. x) | Pabsfloat _ -> S.const_float_expr expr (abs_float x) | _ -> expr, A.value_unknown Other, C.Benefit.zero end | [Value_float (Some n1); Value_float (Some n2)] when fpc -> begin match p with | Paddfloat _ -> S.const_float_expr expr (n1 +. n2) | Psubfloat _ -> S.const_float_expr expr (n1 -. n2) | Pmulfloat _ -> S.const_float_expr expr (n1 *. n2) | Pdivfloat _ -> S.const_float_expr expr (n1 /. n2) | Pfloatcomp c -> S.const_float_comparison_expr expr c n1 n2 | Pcompare_floats -> S.const_int_expr expr (Float.compare n1 n2) | _ -> expr, A.value_unknown Other, C.Benefit.zero end | [A.Value_boxed_int(A.Nativeint, n)] -> I.Simplify_boxed_nativeint.simplify_unop p Nativeint expr n | [A.Value_boxed_int(A.Int32, n)] -> I.Simplify_boxed_int32.simplify_unop p Int32 expr n | [A.Value_boxed_int(A.Int64, n)] -> I.Simplify_boxed_int64.simplify_unop p Int64 expr n | [A.Value_boxed_int(A.Nativeint, n1); A.Value_boxed_int(A.Nativeint, n2)] -> I.Simplify_boxed_nativeint.simplify_binop p Nativeint expr n1 n2 | [A.Value_boxed_int(A.Int32, n1); A.Value_boxed_int(A.Int32, n2)] -> I.Simplify_boxed_int32.simplify_binop p Int32 expr n1 n2 | [A.Value_boxed_int(A.Int64, n1); A.Value_boxed_int(A.Int64, n2)] -> I.Simplify_boxed_int64.simplify_binop p Int64 expr n1 n2 | [A.Value_boxed_int(A.Nativeint, n1); Value_int n2] -> I.Simplify_boxed_nativeint.simplify_binop_int p Nativeint expr n1 n2 ~size_int | [A.Value_boxed_int(A.Int32, n1); Value_int n2] -> I.Simplify_boxed_int32.simplify_binop_int p Int32 expr n1 n2 ~size_int | [A.Value_boxed_int(A.Int64, n1); Value_int n2] -> I.Simplify_boxed_int64.simplify_binop_int p Int64 expr n1 n2 ~size_int | [Value_block _] when is_pisint p -> S.const_bool_expr expr false | [Value_string { size }] when (is_pstring_length p || is_pbytes_length p) -> S.const_int_expr expr size | [Value_string { size; contents = Some s }; (Value_int x)] when x >= 0 && x < size -> begin match p with | Pstringrefu | Pstringrefs | Pbytesrefu | Pbytesrefs -> S.const_char_expr (Prim(Pstringrefu, args, dbg)) s.[x] | _ -> expr, A.value_unknown Other, C.Benefit.zero end | [Value_string { size; contents = None }; (Value_int x)] when x >= 0 && x < size && is_pstringrefs p -> Flambda.Prim (Pstringrefu, args, dbg), A.value_unknown Other, C.Benefit.zero | [Value_string { size; contents = None }; (Value_int x)] when x >= 0 && x < size && is_pbytesrefs p -> Flambda.Prim (Pbytesrefu, args, dbg), A.value_unknown Other, C.Benefit.zero | [Value_float_array { size; contents }] -> begin match p with | Parraylength _ -> S.const_int_expr expr size | Pfloatfield (i,_) -> begin match contents with | A.Contents a when i >= 0 && i < size -> begin match A.check_approx_for_float a.(i) with | None -> expr, a.(i), C.Benefit.zero | Some v -> S.const_float_expr expr v end | Contents _ | Unknown_or_mutable -> expr, A.value_unknown Other, C.Benefit.zero end | _ -> expr, A.value_unknown Other, C.Benefit.zero end | _ -> match Semantics_of_primitives.return_type_of_primitive p with | Float -> expr, A.value_any_float, C.Benefit.zero | Other -> expr, A.value_unknown Other, C.Benefit.zero
ca510ac0765bbc0206e16354268eba01114c746f96f52cb8ae9766e398918c1a
chethan/SICP
FibonacciTailRecursive.hs
fib n = fib_iter 1 0 n where fib_iter a b n | n==0 = b | otherwise = fib_iter (a+b) a (n-1)
null
https://raw.githubusercontent.com/chethan/SICP/ff83adc7e3e89e299c772080d32103f72ecf5dbf/Chapter1/FibonacciTailRecursive.hs
haskell
fib n = fib_iter 1 0 n where fib_iter a b n | n==0 = b | otherwise = fib_iter (a+b) a (n-1)
1686d0a5f6a5e7f9a7118d4f3e4f2026b497f0d903687834d376579af21d51ed
manuel-serrano/hop
cache.scm
;*=====================================================================*/ * serrano / prgm / project / hop / hop / runtime / cache.scm * / ;* ------------------------------------------------------------- */ * Author : * / * Creation : Sat Apr 1 06:54:00 2006 * / * Last change : We d Oct 24 14:39:07 2018 ( serrano ) * / * Copyright : 2006 - 18 * / ;* ------------------------------------------------------------- */ * LRU file caching . * / ;*=====================================================================*/ ;*---------------------------------------------------------------------*/ ;* The module */ ;*---------------------------------------------------------------------*/ (module __hop_cache (import __hop_misc __hop_param) (export (class cache-entry (%prev (default #f)) (%next (default #f)) (signature::elong read-only) (value read-only) (upath::bstring read-only)) (abstract-class cache (%table (default #f)) (%head (default #f)) (%tail (default #f)) (%forced (default #f)) (%mutex (default (make-mutex "cache"))) (register::bool (default #t)) (max-entries::long (default 128)) (current-entries::long (default 0)) (uid::long (default 0)) (validity::procedure (default cache-entry-valid?))) (class cache-disk::cache (%cache-disk-new) (path read-only) (clear read-only (default #t)) (map (default #f)) (out::procedure read-only) (max-file-size::elong (default #e100000))) (class cache-memory::cache (%cache-memory-new) (max-file-size::elong (default #e4096))) (registered-caches::pair-nil) (unregister-cache! ::cache) (cache-entry-valid?::bool ::obj ::bstring) (%cache-disk-new ::cache-disk) (%cache-memory-new ::cache-memory) (generic cache-clear ::cache) (generic cache->list ::cache) (generic cache-get::obj ::cache ::bstring) (generic cache-put!::obj ::cache ::bstring ::obj))) ;*---------------------------------------------------------------------*/ ;* *all-caches* ... */ ;*---------------------------------------------------------------------*/ (define *all-caches* '()) ;*---------------------------------------------------------------------*/ ;* registered-caches ... */ ;*---------------------------------------------------------------------*/ (define (registered-caches) *all-caches*) ;*---------------------------------------------------------------------*/ ;* unregister-cache! ... */ ;*---------------------------------------------------------------------*/ (define (unregister-cache! c) (set! *all-caches* (remq! c *all-caches*))) ;*---------------------------------------------------------------------*/ ;* %cache-disk-new ... */ ;*---------------------------------------------------------------------*/ (define (%cache-disk-new c::cache-disk) (with-access::cache-disk c (path clear map %table max-entries register) ;; create the new directory if it does not exist (cond ((directory? path) ;; cleanup the cache directory when configured (when clear (for-each delete-path (directory->path-list path)))) ((not (make-directories path)) (error "instantiate::cache" "Can't create directory" path))) (set! %table (make-hashtable (*fx 4 max-entries))) (when register (set! *all-caches* (cons c *all-caches*))) ;; the name of the cache map path (unless (string? map) (set! map (make-file-name path "cache.map"))) ;; restore the cache (when (file-exists? map) (cache-restore! c)) c)) ;*---------------------------------------------------------------------*/ ;* %cache-memory-new ... */ ;*---------------------------------------------------------------------*/ (define (%cache-memory-new c::cache-memory) (with-access::cache-memory c (%table max-entries register) (set! %table (make-hashtable (*fx 4 max-entries))) (when register (set! *all-caches* (cons c *all-caches*))))) ;*---------------------------------------------------------------------*/ ;* cache-entry-valid? ... */ ;*---------------------------------------------------------------------*/ (define (cache-entry-valid? ce path) (and (isa? ce cache-entry) (with-access::cache-entry ce (signature) (signature-equal? signature (cache-signature path))))) ;*---------------------------------------------------------------------*/ ;* signature-equal? ... */ ;*---------------------------------------------------------------------*/ (define (signature-equal? a b) (=elong a b)) ;*---------------------------------------------------------------------*/ ;* cache-signature ... */ ;*---------------------------------------------------------------------*/ (define (cache-signature path) (bit-xorelong (file-modification-time path) (fixnum->elong (hop-session)))) ;*---------------------------------------------------------------------*/ ;* for-each-cache ... */ ;*---------------------------------------------------------------------*/ (define (for-each-cache proc::procedure c::cache) (with-access::cache c (%head) (let loop ((h %head)) (when (isa? h cache-entry) (proc h) (with-access::cache-entry h (%next) (loop %next)))))) ;*---------------------------------------------------------------------*/ ;* cache-clear ::cache ... */ ;*---------------------------------------------------------------------*/ (define-generic (cache-clear c::cache) (with-access::cache c (%table %head %tail current-entries uid max-entries) (set! %table (make-hashtable (*fx 4 max-entries))) (set! %head #f) (set! %tail #f) (set! current-entries 0) (set! uid 0))) ;*---------------------------------------------------------------------*/ ;* cache-clear ::cache-disk ... */ ;* ------------------------------------------------------------- */ ;* Removes all the entry from the cache */ ;*---------------------------------------------------------------------*/ (define-method (cache-clear c::cache-disk) (for-each-cache (lambda (ce) (with-access::cache-entry ce (value) (when (file-exists? value) (delete-file value)))) c) (call-next-method)) ;*---------------------------------------------------------------------*/ ;* cache->list ::cache ... */ ;*---------------------------------------------------------------------*/ (define-generic (cache->list c::cache) (with-access::cache c (%tail) (let loop ((tail %tail) (res '())) (if (not tail) res (with-access::cache-entry tail (%prev) (loop %prev (cons tail res))))))) ;*---------------------------------------------------------------------*/ ;* cache-get ::cache ... */ ;*---------------------------------------------------------------------*/ (define-generic (cache-get c::cache path::bstring) (with-access::cache c (%table %head %tail %mutex validity current-entries) (synchronize %mutex (let ((ce (hashtable-get %table path))) (cond ((validity ce path) (with-access::cache-entry ce (%prev %next) (unless (eq? %head ce) (when %prev (if %next (begin (with-access::cache-entry %next ((prev %prev)) (set! prev %prev)) (with-access::cache-entry %prev ((next %next)) (set! next %next))) (begin (with-access::cache-entry %prev (%next) (set! %next #f)) (set! %tail %prev))) (set! %prev #f) (set! %next %head) (with-access::cache-entry %head (%prev) (set! %prev ce)) (set! %head ce))) ce)) ((isa? ce cache-entry) (hashtable-remove! %table path) (set! current-entries (-fx current-entries 1)) (with-access::cache-entry ce (%prev %next) (if %prev (with-access::cache-entry %prev ((next %next)) (set! next %next)) (set! %head %next)) (if %next (with-access::cache-entry %next ((prev %prev)) (set! prev %prev)) (set! %tail %prev)) #f)) (else #f)))))) ;*---------------------------------------------------------------------*/ ;* cache-get ::cache-disk ... */ ;*---------------------------------------------------------------------*/ (define-method (cache-get c::cache-disk path::bstring) (with-access::cache-disk c (%table %head %tail validity %mutex current-entries) (synchronize %mutex (let ((ce (hashtable-get %table path))) (cond ((and ce (validity ce path) (with-access::cache-entry ce (value) (file-exists? value))) (with-access::cache-entry ce (%prev %next) (when %prev (if %next (begin (with-access::cache-entry %next ((prev %prev)) (set! prev %prev)) (with-access::cache-entry %prev ((next %next)) (set! next %next))) (begin (with-access::cache-entry %prev (%next) (set! %next #f)) (set! %tail %prev))) (set! %prev #f) (set! %next %head) (with-access::cache-entry %head (%prev) (set! %prev ce)) (set! %head ce)) ce)) ((isa? ce cache-entry) (hashtable-remove! %table path) (set! current-entries (-fx current-entries 1)) (with-access::cache-entry ce (value %prev %next) (if (file-exists? value) (delete-file value)) (if %prev (with-access::cache-entry %prev ((next %next)) (set! next %next)) (set! %head %next)) (if %next (with-access::cache-entry %next ((prev %prev)) (set! prev %prev)) (set! %tail %prev)) #f)) (else #f)))))) ;*---------------------------------------------------------------------*/ ;* cache-restore! ::cache ... */ ;*---------------------------------------------------------------------*/ (define-generic (cache-restore! c::cache)) ;*---------------------------------------------------------------------*/ ;* cache-restore! ::cache-disk ... */ ;*---------------------------------------------------------------------*/ (define-method (cache-restore! c::cache-disk) (with-access::cache-disk c (validity map path uid) (let ((omap (with-input-from-file map read)) (t (make-hashtable))) (delete-file map) (when (pair? omap) (set! uid (car omap)) (for-each (lambda (e) (match-case e ((?upath ?sig ?value) (when (and (file-exists? upath) (file-exists? value)) (let ((ce (instantiate::cache-entry (value value) (signature sig) (upath upath)))) (when (validity ce upath) (cache-add-entry! c ce) (hashtable-put! t value #t))))))) (cadr omap)) (hashtable-put! t (make-file-name path "cache.map") #t) (for-each (lambda (f) (unless (hashtable-get t f) (delete-file f))) (directory->path-list path)))))) ;*---------------------------------------------------------------------*/ ;* cache-put! ::cache ... */ ;*---------------------------------------------------------------------*/ (define-generic (cache-put!::cache-entry c::cache upath::bstring value::obj)) ;*---------------------------------------------------------------------*/ ;* cache-put! ::cache-disk ... */ ;*---------------------------------------------------------------------*/ (define-method (cache-put!::cache-entry c::cache-disk upath::bstring value) (with-access::cache-disk c (%table %forced %head %tail %mutex max-entries current-entries uid path max-file-size out) (when (and (or (hop-cache-enable) %forced) (or (<=elong max-file-size #e0) (<elong (file-size upath) max-file-size))) (synchronize %mutex (let* ((name (format "~a-~a" uid (basename upath))) (cpath (make-file-name path name)) (ce (instantiate::cache-entry (value cpath) (upath upath) (signature (cache-signature upath))))) ;; make sure that the cache path exists (cond ((not (file-exists? path)) (make-directories path)) ((not (directory? path)) (delete-file path) (make-directories path))) ;; put the file in the cache (let ((p (open-output-file cpath))) (when (output-port? p) (unwind-protect (out value p) (close-output-port p)))) ;; and the entry in the cache (set! uid (+fx 1 uid)) (cache-add-entry! c ce) ce))))) ;*---------------------------------------------------------------------*/ ;* cache-put! ::cache-memory ... */ ;*---------------------------------------------------------------------*/ (define-method (cache-put! c::cache-memory upath::bstring value) (with-access::cache-memory c (%table %forced %head %tail %mutex max-entries max-file-size) (when (and (or (hop-cache-enable) %forced) (or (<=elong max-file-size #e0) (<elong (file-size upath) max-file-size))) (let ((ce (instantiate::cache-entry (value value) (upath upath) (signature (cache-signature upath))))) (synchronize %mutex (cache-add-entry! c ce)) ce)))) ;*---------------------------------------------------------------------*/ ;* cache-add-entry! ::cache ... */ ;*---------------------------------------------------------------------*/ (define-generic (cache-add-entry! c::cache ce::cache-entry)) ;*---------------------------------------------------------------------*/ ;* cache-add-entry! ::cache-disk ... */ ;*---------------------------------------------------------------------*/ (define-method (cache-add-entry! c::cache-disk ce::cache-entry) (with-access::cache-disk c (%table %head %tail max-entries current-entries path max-file-size out map uid) (with-access::cache-entry ce (upath value) ;; add the entry in the hash table (hashtable-put! %table upath ce) (if (<fx current-entries max-entries) (set! current-entries (+fx 1 current-entries)) (begin (with-access::cache-entry %tail (upath) (hashtable-remove! %table upath)) (with-access::cache-entry %tail (%prev) (set! %tail %prev)) (with-access::cache-entry %tail (%next) (set! %next #f)))) (if %head (begin (with-access::cache-entry ce (%next) (set! %next %head)) (with-access::cache-entry %head (%prev) (set! %prev ce)) (set! %head ce)) (begin (set! %head ce) (set! %tail ce))) ;; update the cache map (for future sessions) (with-output-to-file map (lambda () (display "(") (write uid) (display " ") (write (hashtable-map %table (lambda (k ce) (with-access::cache-entry ce (upath signature value) (list upath signature value))))) (display ")")))))) ;*---------------------------------------------------------------------*/ ;* cache-add-entry! ::cache-memory ... */ ;*---------------------------------------------------------------------*/ (define-method (cache-add-entry! c::cache-memory ce::cache-entry) (with-access::cache-memory c (%table %head %tail max-entries current-entries max-file-size) (with-access::cache-entry ce (upath) (hashtable-put! %table upath ce) (if (<fx current-entries max-entries) (set! current-entries (+fx 1 current-entries)) (begin (with-access::cache-entry %tail (upath) (hashtable-remove! %table upath)) (with-access::cache-entry %tail (%prev) (set! %tail %prev)) (with-access::cache-entry %tail (%next) (set! %next #f)))) (if %head (begin (with-access::cache-entry ce (%next) (set! %next %head)) (with-access::cache-entry %head (%prev) (set! %prev ce)) (set! %head ce)) (begin (set! %head ce) (set! %tail ce))))))
null
https://raw.githubusercontent.com/manuel-serrano/hop/481cb10478286796addd2ec9ee29c95db27aa390/runtime/cache.scm
scheme
*=====================================================================*/ * ------------------------------------------------------------- */ * ------------------------------------------------------------- */ *=====================================================================*/ *---------------------------------------------------------------------*/ * The module */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * *all-caches* ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * registered-caches ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * unregister-cache! ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * %cache-disk-new ... */ *---------------------------------------------------------------------*/ create the new directory if it does not exist cleanup the cache directory when configured the name of the cache map path restore the cache *---------------------------------------------------------------------*/ * %cache-memory-new ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * cache-entry-valid? ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * signature-equal? ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * cache-signature ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * for-each-cache ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * cache-clear ::cache ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * cache-clear ::cache-disk ... */ * ------------------------------------------------------------- */ * Removes all the entry from the cache */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * cache->list ::cache ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * cache-get ::cache ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * cache-get ::cache-disk ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * cache-restore! ::cache ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * cache-restore! ::cache-disk ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * cache-put! ::cache ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * cache-put! ::cache-disk ... */ *---------------------------------------------------------------------*/ make sure that the cache path exists put the file in the cache and the entry in the cache *---------------------------------------------------------------------*/ * cache-put! ::cache-memory ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * cache-add-entry! ::cache ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * cache-add-entry! ::cache-disk ... */ *---------------------------------------------------------------------*/ add the entry in the hash table update the cache map (for future sessions) *---------------------------------------------------------------------*/ * cache-add-entry! ::cache-memory ... */ *---------------------------------------------------------------------*/
* serrano / prgm / project / hop / hop / runtime / cache.scm * / * Author : * / * Creation : Sat Apr 1 06:54:00 2006 * / * Last change : We d Oct 24 14:39:07 2018 ( serrano ) * / * Copyright : 2006 - 18 * / * LRU file caching . * / (module __hop_cache (import __hop_misc __hop_param) (export (class cache-entry (%prev (default #f)) (%next (default #f)) (signature::elong read-only) (value read-only) (upath::bstring read-only)) (abstract-class cache (%table (default #f)) (%head (default #f)) (%tail (default #f)) (%forced (default #f)) (%mutex (default (make-mutex "cache"))) (register::bool (default #t)) (max-entries::long (default 128)) (current-entries::long (default 0)) (uid::long (default 0)) (validity::procedure (default cache-entry-valid?))) (class cache-disk::cache (%cache-disk-new) (path read-only) (clear read-only (default #t)) (map (default #f)) (out::procedure read-only) (max-file-size::elong (default #e100000))) (class cache-memory::cache (%cache-memory-new) (max-file-size::elong (default #e4096))) (registered-caches::pair-nil) (unregister-cache! ::cache) (cache-entry-valid?::bool ::obj ::bstring) (%cache-disk-new ::cache-disk) (%cache-memory-new ::cache-memory) (generic cache-clear ::cache) (generic cache->list ::cache) (generic cache-get::obj ::cache ::bstring) (generic cache-put!::obj ::cache ::bstring ::obj))) (define *all-caches* '()) (define (registered-caches) *all-caches*) (define (unregister-cache! c) (set! *all-caches* (remq! c *all-caches*))) (define (%cache-disk-new c::cache-disk) (with-access::cache-disk c (path clear map %table max-entries register) (cond ((directory? path) (when clear (for-each delete-path (directory->path-list path)))) ((not (make-directories path)) (error "instantiate::cache" "Can't create directory" path))) (set! %table (make-hashtable (*fx 4 max-entries))) (when register (set! *all-caches* (cons c *all-caches*))) (unless (string? map) (set! map (make-file-name path "cache.map"))) (when (file-exists? map) (cache-restore! c)) c)) (define (%cache-memory-new c::cache-memory) (with-access::cache-memory c (%table max-entries register) (set! %table (make-hashtable (*fx 4 max-entries))) (when register (set! *all-caches* (cons c *all-caches*))))) (define (cache-entry-valid? ce path) (and (isa? ce cache-entry) (with-access::cache-entry ce (signature) (signature-equal? signature (cache-signature path))))) (define (signature-equal? a b) (=elong a b)) (define (cache-signature path) (bit-xorelong (file-modification-time path) (fixnum->elong (hop-session)))) (define (for-each-cache proc::procedure c::cache) (with-access::cache c (%head) (let loop ((h %head)) (when (isa? h cache-entry) (proc h) (with-access::cache-entry h (%next) (loop %next)))))) (define-generic (cache-clear c::cache) (with-access::cache c (%table %head %tail current-entries uid max-entries) (set! %table (make-hashtable (*fx 4 max-entries))) (set! %head #f) (set! %tail #f) (set! current-entries 0) (set! uid 0))) (define-method (cache-clear c::cache-disk) (for-each-cache (lambda (ce) (with-access::cache-entry ce (value) (when (file-exists? value) (delete-file value)))) c) (call-next-method)) (define-generic (cache->list c::cache) (with-access::cache c (%tail) (let loop ((tail %tail) (res '())) (if (not tail) res (with-access::cache-entry tail (%prev) (loop %prev (cons tail res))))))) (define-generic (cache-get c::cache path::bstring) (with-access::cache c (%table %head %tail %mutex validity current-entries) (synchronize %mutex (let ((ce (hashtable-get %table path))) (cond ((validity ce path) (with-access::cache-entry ce (%prev %next) (unless (eq? %head ce) (when %prev (if %next (begin (with-access::cache-entry %next ((prev %prev)) (set! prev %prev)) (with-access::cache-entry %prev ((next %next)) (set! next %next))) (begin (with-access::cache-entry %prev (%next) (set! %next #f)) (set! %tail %prev))) (set! %prev #f) (set! %next %head) (with-access::cache-entry %head (%prev) (set! %prev ce)) (set! %head ce))) ce)) ((isa? ce cache-entry) (hashtable-remove! %table path) (set! current-entries (-fx current-entries 1)) (with-access::cache-entry ce (%prev %next) (if %prev (with-access::cache-entry %prev ((next %next)) (set! next %next)) (set! %head %next)) (if %next (with-access::cache-entry %next ((prev %prev)) (set! prev %prev)) (set! %tail %prev)) #f)) (else #f)))))) (define-method (cache-get c::cache-disk path::bstring) (with-access::cache-disk c (%table %head %tail validity %mutex current-entries) (synchronize %mutex (let ((ce (hashtable-get %table path))) (cond ((and ce (validity ce path) (with-access::cache-entry ce (value) (file-exists? value))) (with-access::cache-entry ce (%prev %next) (when %prev (if %next (begin (with-access::cache-entry %next ((prev %prev)) (set! prev %prev)) (with-access::cache-entry %prev ((next %next)) (set! next %next))) (begin (with-access::cache-entry %prev (%next) (set! %next #f)) (set! %tail %prev))) (set! %prev #f) (set! %next %head) (with-access::cache-entry %head (%prev) (set! %prev ce)) (set! %head ce)) ce)) ((isa? ce cache-entry) (hashtable-remove! %table path) (set! current-entries (-fx current-entries 1)) (with-access::cache-entry ce (value %prev %next) (if (file-exists? value) (delete-file value)) (if %prev (with-access::cache-entry %prev ((next %next)) (set! next %next)) (set! %head %next)) (if %next (with-access::cache-entry %next ((prev %prev)) (set! prev %prev)) (set! %tail %prev)) #f)) (else #f)))))) (define-generic (cache-restore! c::cache)) (define-method (cache-restore! c::cache-disk) (with-access::cache-disk c (validity map path uid) (let ((omap (with-input-from-file map read)) (t (make-hashtable))) (delete-file map) (when (pair? omap) (set! uid (car omap)) (for-each (lambda (e) (match-case e ((?upath ?sig ?value) (when (and (file-exists? upath) (file-exists? value)) (let ((ce (instantiate::cache-entry (value value) (signature sig) (upath upath)))) (when (validity ce upath) (cache-add-entry! c ce) (hashtable-put! t value #t))))))) (cadr omap)) (hashtable-put! t (make-file-name path "cache.map") #t) (for-each (lambda (f) (unless (hashtable-get t f) (delete-file f))) (directory->path-list path)))))) (define-generic (cache-put!::cache-entry c::cache upath::bstring value::obj)) (define-method (cache-put!::cache-entry c::cache-disk upath::bstring value) (with-access::cache-disk c (%table %forced %head %tail %mutex max-entries current-entries uid path max-file-size out) (when (and (or (hop-cache-enable) %forced) (or (<=elong max-file-size #e0) (<elong (file-size upath) max-file-size))) (synchronize %mutex (let* ((name (format "~a-~a" uid (basename upath))) (cpath (make-file-name path name)) (ce (instantiate::cache-entry (value cpath) (upath upath) (signature (cache-signature upath))))) (cond ((not (file-exists? path)) (make-directories path)) ((not (directory? path)) (delete-file path) (make-directories path))) (let ((p (open-output-file cpath))) (when (output-port? p) (unwind-protect (out value p) (close-output-port p)))) (set! uid (+fx 1 uid)) (cache-add-entry! c ce) ce))))) (define-method (cache-put! c::cache-memory upath::bstring value) (with-access::cache-memory c (%table %forced %head %tail %mutex max-entries max-file-size) (when (and (or (hop-cache-enable) %forced) (or (<=elong max-file-size #e0) (<elong (file-size upath) max-file-size))) (let ((ce (instantiate::cache-entry (value value) (upath upath) (signature (cache-signature upath))))) (synchronize %mutex (cache-add-entry! c ce)) ce)))) (define-generic (cache-add-entry! c::cache ce::cache-entry)) (define-method (cache-add-entry! c::cache-disk ce::cache-entry) (with-access::cache-disk c (%table %head %tail max-entries current-entries path max-file-size out map uid) (with-access::cache-entry ce (upath value) (hashtable-put! %table upath ce) (if (<fx current-entries max-entries) (set! current-entries (+fx 1 current-entries)) (begin (with-access::cache-entry %tail (upath) (hashtable-remove! %table upath)) (with-access::cache-entry %tail (%prev) (set! %tail %prev)) (with-access::cache-entry %tail (%next) (set! %next #f)))) (if %head (begin (with-access::cache-entry ce (%next) (set! %next %head)) (with-access::cache-entry %head (%prev) (set! %prev ce)) (set! %head ce)) (begin (set! %head ce) (set! %tail ce))) (with-output-to-file map (lambda () (display "(") (write uid) (display " ") (write (hashtable-map %table (lambda (k ce) (with-access::cache-entry ce (upath signature value) (list upath signature value))))) (display ")")))))) (define-method (cache-add-entry! c::cache-memory ce::cache-entry) (with-access::cache-memory c (%table %head %tail max-entries current-entries max-file-size) (with-access::cache-entry ce (upath) (hashtable-put! %table upath ce) (if (<fx current-entries max-entries) (set! current-entries (+fx 1 current-entries)) (begin (with-access::cache-entry %tail (upath) (hashtable-remove! %table upath)) (with-access::cache-entry %tail (%prev) (set! %tail %prev)) (with-access::cache-entry %tail (%next) (set! %next #f)))) (if %head (begin (with-access::cache-entry ce (%next) (set! %next %head)) (with-access::cache-entry %head (%prev) (set! %prev ce)) (set! %head ce)) (begin (set! %head ce) (set! %tail ce))))))
059e964a4dcc26308473258ca717d8204f747cd362dd7b21e541a3d271cae734
wlitwin/graphv
graphv_gles3.ml
include Graphv_core let create ~flags () = let gles = Gles.create ~flags () |> opt_exn in let font = Fontstash.create () in create ~flags gles font
null
https://raw.githubusercontent.com/wlitwin/graphv/d0a09575c5ff5ee3727c222dd6130d22e4cf62d9/gles3/graphv_gles3.ml
ocaml
include Graphv_core let create ~flags () = let gles = Gles.create ~flags () |> opt_exn in let font = Fontstash.create () in create ~flags gles font
3d63de3e9c05f3f6780ecf6757e68f054efdfc7cd70bc6fea3abb78ba08058fc
marick/fp-oo
lazy-world.clj
The solution to 1 is in the text 2 (def ys-and-ns (filter (fn [string] (or (.startsWith string "y") (.startsWith string "n"))) (repeatedly prompt-and-read))) 3 (def counted-sum (fn [] (let [numbers-only (map to-integer (filter number-string? (repeatedly prompt-and-read))) number-count (first numbers-only) numbers (take number-count (rest numbers-only))] (apply + numbers))))
null
https://raw.githubusercontent.com/marick/fp-oo/434937826d794d6fe02b3e9a62cf5b4fbc314412/solutions/lazy-world.clj
clojure
The solution to 1 is in the text 2 (def ys-and-ns (filter (fn [string] (or (.startsWith string "y") (.startsWith string "n"))) (repeatedly prompt-and-read))) 3 (def counted-sum (fn [] (let [numbers-only (map to-integer (filter number-string? (repeatedly prompt-and-read))) number-count (first numbers-only) numbers (take number-count (rest numbers-only))] (apply + numbers))))
4a0ec83dd06288317cd44b4ca682883c8a267cd923e5f9f55c42c87873d2cf12
khinsen/leibniz
documents.rkt
#lang racket (provide empty-document add-to-library add-context-from-source get-asset get-context make-term make-rule make-transformation make-equation make-test get-document-sxml get-context-sxml write-xml import-xml write-signature-graphs clean-declarations) (require (prefix-in sorts: "./sorts.rkt") (only-in "./sorts.rkt" sort-graph? empty-sort-graph) (prefix-in operators: "./operators.rkt") (prefix-in terms: "./terms.rkt") (prefix-in equations: "./equations.rkt") (prefix-in rewrite: "./rewrite.rkt") (prefix-in tools: "./tools.rkt") (prefix-in builtins: "./builtin-contexts.rkt") "./transformations.rkt" "./lightweight-class.rkt" racket/hash sxml threading) (module+ test (require rackunit)) ;; ;; Re-raise exceptions with the source location information from the document ;; (define-struct (exn:fail:leibniz exn:fail) (a-srcloc-list) #:property prop:exn:srclocs (λ (a-struct) (match a-struct [(struct exn:fail:leibniz (msg marks a-srcloc-list)) a-srcloc-list]))) (define ((re-raise-exn loc) e) (if loc (raise (make-exn:fail:leibniz (exn-message e) (current-continuation-marks) (for/list ([l loc]) (and l (apply srcloc l))))) (raise e))) ;; ;; Compile declarations from a context to internal datas tructures. ;; (define (get-loc locs decl) (cond [(procedure? locs) (locs decl)] [(hash? locs) (hash-ref locs decl #f)] [else #f])) (define (compile-sort-graph includes sort-decls subsort-decls locs) ;; Merge the sort graphs of the included contexts. (define after-includes (for/fold ([ms sorts:empty-sort-graph]) ([m/c includes]) (sorts:merge-sort-graphs ms (operators:signature-sort-graph (hash-ref (cdr m/c) 'compiled-signature))))) ;; Process the sort declarations. (define after-sorts (for/fold ([sorts after-includes]) ([s sort-decls]) (with-handlers ([exn:fail? (re-raise-exn (get-loc locs s))]) (sorts:add-sort sorts s)))) Process the subsort declarations . (for/fold ([sorts after-sorts]) ([ss subsort-decls]) (with-handlers ([exn:fail? (re-raise-exn (get-loc locs ss))]) (sorts:add-subsort-relation sorts (car ss) (cdr ss))))) (define (compile-signature sorts includes op-decls var-decls locs) (define (argsort sort-or-var-decl) (match sort-or-var-decl [(list 'sort sort-id) sort-id] [(list 'var var-name sort-id) sort-id])) ;; Merge the signatures of the included contexts. (define after-includes (for/fold ([msig (operators:empty-signature sorts)]) ([m/c includes]) (define csig (hash-ref (cdr m/c) 'compiled-signature)) (define isig (case (car m/c) [(use) (operators:remove-vars csig)] [(extend) csig])) (operators:merge-signatures msig isig sorts))) Process the op declarations . (define after-ops (for/fold ([sig after-includes]) ([od op-decls]) (with-handlers ([exn:fail? (re-raise-exn (get-loc locs od))]) (match-define (list name arity rsort) od) (operators:add-op sig name (map argsort arity) rsort #:meta (get-loc locs od))))) ;; Process the var declarations. (define signature (for/fold ([sig after-ops]) ([(vname vsort) var-decls]) (with-handlers ([exn:fail? (re-raise-exn (get-loc locs (hash vname vsort)))]) (operators:add-var sig vname vsort)))) ;; Check for non-regularity. (define non-regular (operators:non-regular-op-example signature)) (when non-regular (match-let ([(list op arity rsorts) non-regular]) (displayln (format "Warning: operator ~a~a has ambiguous sorts ~a" op arity rsorts)))) signature) (define (make-term* signature) (letrec ([fn (match-lambda [(list 'term-or-var name) (terms:make-var-or-term signature name)] [(list 'term op args) (terms:make-term signature op (map fn args))] [(list 'integer n) n] [(list 'rational r) r] [(list 'floating-point fp) fp])]) fn)) (define (make-pattern* signature local-vars) (letrec ([fn (match-lambda [#f #f] [(list 'term-or-var name) (terms:make-var-or-term signature name local-vars)] [(list 'term op args) (terms:make-term signature op (map fn args))] [(list 'integer n) n] [(list 'rational r) r] [(list 'floating-point fp) fp])]) fn)) (define (make-rule* signature rule-expr check-equationality?) (match rule-expr [(list 'rule vars pattern replacement condition) (let* ([mp (make-pattern* signature vars)]) (equations:make-rule signature (mp pattern) (mp condition) (mp replacement) #f check-equationality?))] [_ #f])) (define (make-transformation* signature rule-expr) (and~> (make-rule* signature (cons 'rule (rest rule-expr)) #f) (equations:make-transformation signature _))) (define (as-rule* signature value flip?) (cond [(equations:rule? value) value] [(equations:equation? value) (define-values (left right) (if flip? (values (equations:equation-right value) (equations:equation-left value)) (values (equations:equation-left value) (equations:equation-right value)))) (equations:make-rule signature left (equations:equation-condition value) right #f #t)] [else (error (format "cannot convert ~a to a rule" value))])) (define (compile-rules signature includes rule-decls locs) ;; Merge the rule lists of the included contexts. (define after-includes (for/fold ([mrl equations:empty-rulelist]) ([m/c includes]) (equations:merge-rulelists mrl (hash-ref (cdr m/c) 'compiled-rules) signature))) ;; Process the rule declarations (for/fold ([rl after-includes]) ([rd rule-decls]) (with-handlers ([exn:fail? (re-raise-exn (get-loc locs rd))]) (equations:add-rule rl (make-rule* signature rd #t))))) (define (make-equation* signature equation-expr) (match equation-expr [(list 'equation vars left right condition) (let ([mp (make-pattern* signature vars)]) (equations:make-equation signature (mp left) (mp condition) (mp right)))] [_ #f])) (define (as-equation* signature value) (cond [(equations:equation? value) value] [(equations:rule? value) (equations:make-equation signature (equations:rule-pattern value) (equations:rule-condition value) (equations:rule-replacement value))] [else (error (format "cannot convert ~a to an equation" value))])) (define (substitution* signature rule value) (unless (equations:rule? rule) (error (format "not a rule: ~a" rule))) (define transformation (equations:make-transformation signature rule)) (cond [(terms:term? value) (rewrite:substitute signature transformation value)] [(equations:equation? value) (rewrite:substitute-equation signature transformation value)] [else (error (format "not a term or equation: ~a" value))])) (define (transformation* signature transformation value) (unless (equations:transformation? transformation) (error (format "not a transformation: ~a" transformation))) (cond [(terms:term? value) (rewrite:transform signature transformation value)] [(equations:equation? value) (rewrite:transform-equation signature transformation value)] [else (error (format "not a term or equation: ~a" value))])) (define (reduce* signature rulelist value) (unless (equations:rulelist? rulelist) (error (format "not a rulelist: ~a" rulelist))) (cond [(terms:term? value) (rewrite:reduce signature rulelist value)] [(equations:equation? value) (rewrite:reduce-equation signature rulelist value)] [else (error (format "not a term or equation: ~a" value))])) (define (combine-assets label asset1 asset2) (cond [(equal? asset1 asset2) asset1] [(and (equal? (first asset1) 'assets) (equal? (first asset1) 'assets)) (list 'assets (hash-union (second asset1) (second asset2) #:combine/key combine-assets))] [else (error (format "Asset label ~a already used for value ~a" label asset1))])) (define (combine-compiled-assets label asset1 asset2) (cond [(equal? asset1 asset2) asset1] [(and (hash? asset1) (hash? asset2)) (hash-union asset1 asset2 #:combine/key combine-compiled-assets)] [(and (box? asset1) (not (unbox asset1))) asset2] [(and (box? asset2) (not (unbox asset2))) asset1] [else (error (format "Asset label ~a already used for value ~a" label asset1))])) (define (compile-assets signature rulelist includes asset-decls locs) (define unevaluated empty) ;; Helper function for compiling a single asset. (define (compile-asset decl) (match decl [(list 'rule arg ...) (box (make-rule* signature decl #f))] [(list 'equation arg ...) (box (make-equation* signature decl))] [(list 'transformation arg ...) (box (make-transformation* signature decl))] [(or (list 'as-equation _) (list 'as-rule _ _) (list 'substitute _ _ _) (list 'transform _ _ _)) (let ([no-value (box #f)]) (set! unevaluated (cons (list no-value decl) unevaluated)) no-value)] [(list 'assets assets) (for/hash ([(label value) assets]) (values label (compile-asset value)))] ;; TODO Should test for valid term declarations, rather than suppose ;; that it must be a term since it's no other valid declaration. [term (box ((make-term* signature) decl))])) ;; Helper functions for computing dependent assets (define (compute-asset assets decl) (match decl [(list 'as-equation label) (and~> (lookup-asset assets label) (as-equation* signature _))] [(list 'as-rule label flip?) (and~> (lookup-asset assets label) (as-rule* signature _ flip?))] [(list 'substitute rule-label asset-label reduce?) (let* ([rule (lookup-asset assets rule-label)] [asset (lookup-asset assets asset-label)] [substituted (and rule asset (substitution* signature rule asset))]) (if reduce? (and substituted (reduce* signature rulelist substituted)) substituted))] [(list 'transform tr-label asset-label reduce?) (let* ([tr (lookup-asset assets tr-label)] [asset (lookup-asset assets asset-label)] [transformed (and tr asset (transformation* signature tr asset))]) (if reduce? (and transformed (reduce* signature rulelist transformed)) transformed))])) (define (compute-assets unevaluated) (for/fold ([remaining empty]) ([box+decl unevaluated]) (match-define (list box decl) box+decl) (define value (compute-asset assets decl)) (if value (begin (set-box! box value) remaining) (cons (list box decl) remaining)))) (define (compute-assets-iteratively unevaluated) (let ([remaining (compute-assets unevaluated)]) (if (equal? (length remaining) (length unevaluated)) remaining (compute-assets-iteratively remaining)))) ;; Merge the assets of the included contexts. (define after-includes (for/fold ([merged-assets (hash)]) ([m/c includes]) (hash-union merged-assets (hash-ref (cdr m/c) 'compiled-assets (hash)) #:combine/key combine-compiled-assets))) ;; Process the asset declarations (define assets (for/fold ([assets after-includes]) ([(label ad) asset-decls]) (with-handlers ([exn:fail? (re-raise-exn (get-loc locs (hash label ad)))]) (hash-union assets (hash label (compile-asset ad)) #:combine/key combine-compiled-assets)))) ;; Compute unevaluated assets (define remaining (compute-assets-iteratively unevaluated)) (unless (empty? remaining) (error (format "~a remaining unevaluated assets" (length remaining)))) ;; Return compiled assets, guaranteed without unevaluated boxes assets) ;; Convert an SXML document to the internal document data structure . ;; (define (combine-varsets name sort1 sort2) (unless (equal? sort1 sort2) (error (format "Var ~a of sort ~a redefined with sort ~a" name sort1 sort2))) sort1) (define (sxml->document sxml-document) (match-define (list '*TOP* (list 'leibniz-document (list 'library document-refs ...) sxml-contexts ...)) sxml-document) (let ([doc-with-library (for/fold ([doc empty-document]) ([dref document-refs]) (match-define `(document-ref (@ (id ,name)) ,ref) dref) (send doc import-xml name ref))]) (for/fold ([doc doc-with-library]) ([sxml-context sxml-contexts]) (define-values (namespace context-decls) (sxml->context sxml-context)) (send doc add-context namespace (hash-set context-decls 'locs (hash)))))) (define (sxml->context sxml-context) (define (sxml->arg sxml-arg) (match sxml-arg [`(var (@ (id ,var-name) (sort ,sort-name))) (list 'var (string->symbol var-name) (string->symbol sort-name))] [`(var (@ (sort ,sort-name) (id ,var-name))) (list 'var (string->symbol var-name) (string->symbol sort-name))] [`(sort (@ (id ,sort-name))) (list 'sort (string->symbol sort-name))])) (define (sxml->vars sxml-vars) (for/fold ([vars (hash)]) ([v sxml-vars]) (define new-var (match v [(or `(var (@ (id ,vn) (sort ,sn))) `(var (@ (sort ,sn) (id ,vn)))) (hash (string->symbol vn) (string->symbol sn))])) (hash-union vars new-var #:combine/key combine-varsets))) (define (sxml->asset sxml-asset) (match sxml-asset [`(assets (asset (@ (id ,label)) ,value) ...) (list 'assets (for/hash ([l label] [v value]) (values (string->symbol l) (sxml->asset v))))] [`(equation (vars ,ev ...) (left ,el) ,ec (right ,er)) (list 'equation (sxml->vars ev) (sxml->asset el) (sxml->asset er) (match ec [`(condition) #f] [`(condition ,term) term]))] [`(rule (vars ,rv ...) (pattern ,rp) ,rc (replacement ,rr)) (list 'rule (sxml->vars rv) (sxml->asset rp) (sxml->asset rr) (match rc [`(condition) #f] [`(condition ,term) term]))] [`(transformation (vars ,rv ...) (pattern ,rp) ,rc (replacement ,rr)) (list 'transformation (sxml->vars rv) (sxml->asset rp) (sxml->asset rr) (match rc [`(condition) #f] [`(condition ,term) term]))] [`(term (@ (op ,op-string)) ,args ...) (list 'term (string->symbol op-string) (map sxml->asset args))] [`(term-or-var (@ (name ,name-string))) (list 'term-or-var (string->symbol name-string))] [`(,number-tag (@ (value ,v))) (list number-tag (read (open-input-string v)))] [`(as-equation (@ (ref ,asset-ref))) (list 'as-equation (string->symbol asset-ref))] [`(as-rule (@ (ref ,asset-ref) (flip ,flip?))) (list 'as-rule (string->symbol asset-ref) (equal? flip? "true"))] [`(substitute (@ (substitute ,substitution-ref) (ref ,asset-ref) (reduce ,reduce?))) (list 'substitute (string->symbol substitution-ref) (string->symbol asset-ref) (equal? reduce? "true"))] [`(transform (@ (transformation ,transformation-ref) (ref ,asset-ref) (reduce ,reduce?))) (list 'transform (string->symbol transformation-ref) (string->symbol asset-ref) (equal? reduce? "true"))])) (match-define `(context (@ (id, name)) (includes ,sxml-includes ...) (sorts ,sxml-sorts ...) (subsorts ,sxml-subsorts ...) (vars ,sxml-vars ...) (ops ,sxml-ops ...) (rules ,sxml-rules ...) (assets ,sxml-assets ...)) sxml-context) (define includes (for/list ([include sxml-includes]) (match include [(list mode include-ref) (cons mode include-ref)]))) (define sorts (for/set ([sort sxml-sorts]) (match sort [`(sort (@ (id ,s))) (string->symbol s)]))) (define subsorts (for/set ([subsort sxml-subsorts]) (match subsort [`(subsort (@ (subsort ,s1) (supersort ,s2))) (cons (string->symbol s1) (string->symbol s2))] [`(subsort (@ (supersort ,s2) (subsort ,s1))) (cons (string->symbol s1) (string->symbol s2))]))) (define vars (sxml->vars sxml-vars)) (define ops (for/set ([op sxml-ops]) (match op [`(op (@ (id ,on)) (arity ,oa ...) (sort (@ (id ,os)))) (list (string->symbol on) (map sxml->arg oa) (string->symbol os))]))) (define rules (for/list ([rule sxml-rules]) (sxml->asset rule))) (define assets (second (sxml->asset (cons 'assets sxml-assets)))) (values name (hash 'includes includes 'sorts sorts 'subsorts subsorts 'vars vars 'ops ops 'rules rules 'assets assets 'locs (hash)))) Decompose an compound asset label into a list of nested simple asset labels (define (nested-labels compound-label) (~> (symbol->string compound-label) (string-split ".") (map string->symbol _))) ;; ;; A document is a collection of contexts that can refer to each other by name. ;; Each document also keeps a library of other documents to whose contexts ;; its own contexts can refer. The dependency graph is acyclic by construction. ;; (define-class document (field contexts order library library-refs) ;; contexts: a hash mapping context names to hashes with keys ;; 'includes 'sorts 'ops 'vars 'rules 'assets, ;; values are lists/sets/hashes of the declarations in ;; each category ;; order: a list of context names in the inverse order of definition ;; library: a hash mapping document names to documents ;; library-refs: a hash mapping document names to external references ;; (filenames for now, later maybe DOIs or hashes) ;; Add another document to the library. (define (add-to-library name library-document external-ref) (document contexts order (hash-set library name library-document) (hash-set library-refs name external-ref))) ;; Add a built-in context. Used only for preparing a single document ;; called "builtins", which is automatically added to every other ;; document's library. (define (add-builtin-context name include-decls signature rules) (define temp-doc (add-context-from-source name include-decls)) (define inclusion-decls (send temp-doc get-context name)) (document (hash-set contexts name (hash 'includes (hash-ref inclusion-decls 'includes) 'compiled-signature signature 'compiled-rules rules 'compiled-assets (hash))) (cons name order) library library-refs)) Take context declarations parsed by ' extensions to Scribble ;; and convert them to the internal context data structure. (define (preprocess-source-declarations source-decls) (define (add-loc context decl loc) (hash-update context 'locs (λ (ls) (if (and loc (not (hash-has-key? ls decl))) (hash-set ls decl (list loc)) ls)))) (define (add-include context mode cname loc) (~> context (hash-update 'includes (λ (cnames) (append cnames (list (cons mode cname))))) (add-loc cname loc))) (define (add-sort context s loc) (~> context (hash-update 'sorts (λ (ss) (set-add ss s))) (add-loc s loc))) (define (add-subsort context s1 s2 loc) (define new-ss (cons s1 s2)) (~> context (hash-update 'subsorts (λ (ss) (set-add ss new-ss))) (add-loc new-ss loc))) (define (add-op context name arity rsort loc) (define new-op (list name arity rsort)) (~> context (hash-update 'ops (λ (ops) (set-add ops new-op))) (add-loc new-op loc))) (define (add-var context name sort loc) (define new-var (hash name sort)) (~> context (hash-update 'vars (λ (vars) (hash-union vars new-var #:combine/key combine-varsets))) (add-loc new-var loc))) (define (group-clauses clauses loc) (for/fold ([vars (hash)] [condition #f]) ([c clauses]) (match c [`(var ,name ,sort) (values (hash-union vars (hash name sort) #:combine/key combine-varsets) condition)] [term (if condition (values vars (list 'term '_∧ (list condition term))) (values vars term))]))) (define (add-rule context pattern replacement clauses loc) (define-values (vars condition) (group-clauses clauses loc)) (define new-rule (list 'rule vars pattern replacement condition)) (~> context (hash-update 'rules (λ (rules) (if (member new-rule rules) rules (append rules (list new-rule))))) (add-loc new-rule loc))) (define (preprocess-asset value loc) (match value [(list 'rule pattern replacement clauses) (define-values (vars condition) (group-clauses clauses loc)) (list 'rule vars pattern replacement condition)] [(list 'equation left right clauses) (define-values (vars condition) (group-clauses clauses loc)) (list 'equation vars left right condition)] [(list 'transformation pattern replacement clauses) (define-values (vars condition) (group-clauses clauses loc)) (list 'transformation vars pattern replacement condition)] [(list 'assets (list label value) ...) (list 'assets (for/hash ([l label] [v value]) (values l (preprocess-asset v loc))))] [(list 'as-rule label flip?) value] [(list 'as-equation label) value] [(list (or'substitute 'transform) label rule value reduce?) value] [term term])) (define (add-asset context label value loc) (define preprocessed-value (preprocess-asset value loc)) (define nested (nested-labels label)) (define new-asset (hash (first nested) (for/fold ([v preprocessed-value]) ([l (reverse (rest nested))]) (list 'assets (hash l v))))) (~> context (hash-update 'assets (λ (assets) (hash-union assets new-asset #:combine/key combine-assets))) (add-loc new-asset loc))) (define (resolve-includes context) (define (resolve-includes* document context) (define include-refs (hash-ref context 'includes)) (define includes (for/list ([mode/name include-refs]) (match-define (cons mode name) mode/name) (define-values (i-doc i-c) (send document get-document-and-context name)) (cons mode (if (equal? i-doc builtins) name (resolve-includes* i-doc i-c))))) (hash-set context 'includes includes)) (resolve-includes* this context)) (define (merge context inserted-context loc) (define (merge* key v1 v2) (case key [(includes rules) (remove-duplicates (append v1 v2))] [(sorts subsorts ops) (set-union v1 v2)] [(vars) (hash-union v1 v2 #:combine/key combine-varsets)] [(assets) (hash-union v1 v2 #:combine/key combine-assets)] [(locs) (hash-union v1 v2 #:combine (λ (a b) a))])) (define (add-loc-prefix context loc) (hash-update context 'locs (λ (ls) (for/hash ([(d l) ls]) (values d (cons loc l)))))) (hash-union context (add-loc-prefix inserted-context loc) #:combine/key merge*)) (~> (for/fold ([context (hash 'includes empty 'sorts (set) 'subsorts (set) 'ops (set) 'vars (hash) 'rules (list) 'assets (hash) 'locs (hash))]) ([decl/loc source-decls]) (match-define (cons decl loc) decl/loc) (match decl [(list 'use cname) (add-include context 'use cname loc)] [(list 'extend cname) (add-include context 'extend cname loc)] [(list (and (or 'insert-use 'insert-extend) insert-type) cname tr ...) (define (apply-transformations context tr) (with-handlers ([exn:fail? (re-raise-exn (list loc))]) (transform-context-declarations context tr))) (define (merge-recursively insertion context) (define (insert-includes context) (for/fold ([c context]) ([mode/context (hash-ref insertion 'includes)] #:unless (string? (cdr mode/context))) (if (equal? (car mode/context) 'use) (hide-context-vars (cdr mode/context)) (cdr mode/context)) (merge-recursively (cdr mode/context) c))) (define (cleanup-insertion insertion) (clean-declarations (hash-update insertion 'includes (λ (crefs) (for/list ([mode/name-or-context crefs] #:when (string? (cdr mode/name-or-context))) mode/name-or-context))))) (~> context insert-includes (merge (cleanup-insertion insertion) loc))) (define (maybe-hide-vars context) (if (equal? insert-type 'insert-use) (hide-context-vars context) context)) (~> (get-context cname) maybe-hide-vars resolve-includes (apply-transformations tr) (merge-recursively context))] [(list 'sort s) (add-sort context s loc)] [(list 'subsort s1 s2) (~> context (add-sort s1 loc) (add-sort s2 loc) (add-subsort s1 s2 loc))] [(list 'op name arity rsort) (for/fold ([context (~> context (add-sort rsort loc) (add-op name arity rsort loc))]) ([arg arity]) (match arg [(list 'var name sort) (add-var context name sort loc)] [(list 'sort s) context]))] [(list 'var name sort) (add-var context name sort loc)] [(list 'rule pattern replacement clauses) (add-rule context pattern replacement clauses loc)] [(list 'asset label value) (add-asset context label value loc)])))) ;; Add a context defined by a sequence of source declarations. (define (add-context-from-source name source-decls) (add-context name (preprocess-source-declarations source-decls))) ;; Add a context defined by a context data structure. (define (add-context name context) (define locs (hash-ref context 'locs)) (define included-contexts (for/list ([mode/name (hash-ref context 'includes)]) (with-handlers ([exn:fail? (re-raise-exn (get-loc locs name))]) (cons (car mode/name) (get-context (cdr mode/name)))))) (define sorts (compile-sort-graph included-contexts (hash-ref context 'sorts) (hash-ref context 'subsorts) locs)) (define signature (compile-signature sorts included-contexts (hash-ref context 'ops) (hash-ref context 'vars) locs)) (define rules (compile-rules signature included-contexts (hash-ref context 'rules) locs)) (define assets (compile-assets signature rules included-contexts (hash-ref context 'assets) locs)) (define compiled (hash 'compiled-signature signature 'compiled-rules rules 'compiled-assets assets)) (document (hash-set contexts name (hash-union context compiled)) (cons name order) library library-refs)) ;; Retrieve a context by name (define (get-document-and-context name) (define elements (map string-trim (string-split name "/"))) (case (length elements) [(1) (unless (hash-has-key? contexts (first elements)) (error (format "no context named ~a" name))) (values this (hash-ref contexts (first elements)))] [(2) (unless (hash-has-key? library (first elements)) (error (format "no library named ~a" (first elements)))) (define library-doc (hash-ref library (first elements))) (values library-doc (send library-doc get-context (second elements)))] [else (error (format "illegal context specification ~a" name))])) (define (get-context name) (define-values (document context) (get-document-and-context name)) context) Return an SXML representation of the document (define (get-document-sxml) `(*TOP* (leibniz-document (library ,@(for/list ([(name ref) library-refs] #:unless (equal? name "builtins")) `(document-ref (@ (id ,name)) ,ref))) ,@(for/list ([name (reverse order)]) (get-context-sxml name))))) Return an SXML representation of a context . (define (get-context-sxml name) (define (vars->sxml vars) (for/list ([(name sort) vars]) `(var (@ (id ,(symbol->string name)) (sort ,(symbol->string sort)))))) (define (op->sxml op) `(op (@ (id ,(symbol->string (first op)))) (arity ,@(for/list ([sv (second op)]) (if (equal? (first sv) 'sort) `(sort (@ (id ,(symbol->string (second sv))))) `(var (@ (id ,(symbol->string (second sv))) (sort ,(symbol->string (third sv)))))))) (sort (@ (id ,(symbol->string (third op))))))) (define (condition->sxml condition) (if (equal? condition #f) `(condition) `(condition ,(asset->sxml condition)))) (define (asset->sxml asset) (match asset [(list 'assets asset-data) (assets->sxml asset-data)] [(list 'equation vars left right condition) `(equation (vars ,@(vars->sxml vars)) (left ,(asset->sxml left)) ,(condition->sxml condition) (right ,(asset->sxml right)))] [(list 'rule vars pattern replacement condition) `(rule (vars ,@(vars->sxml vars)) (pattern ,(asset->sxml pattern)) ,(condition->sxml condition) (replacement ,(asset->sxml replacement)))] [(list 'transformation vars pattern replacement condition) `(transformation (vars ,@(vars->sxml vars)) (pattern ,(asset->sxml pattern)) ,(condition->sxml condition) (replacement ,(asset->sxml replacement)))] [(list 'term-or-var name) `(term-or-var (@ (name ,(symbol->string name))))] [(list 'term op args) `(term (@ (op ,(symbol->string op))) ,@(for/list ([arg args]) (asset->sxml arg)))] [(list (and number-tag (or 'integer 'rational 'floating-point)) x) `(,number-tag (@ (value ,(format "~a" x))))] [(list 'as-equation asset-ref) `(as-equation (@ (ref ,(symbol->string asset-ref))))] [(list 'as-rule asset-ref flip?) `(as-rule (@ (ref ,(symbol->string asset-ref)) (flip ,(if flip? "true" "false"))))] [(list 'substitute substitution-ref asset-ref reduce?) `(substitute (@ (substitute ,(symbol->string substitution-ref)) (ref ,(symbol->string asset-ref)) (reduce ,(if reduce? "true" "false"))))] [(list 'transform transformation-ref asset-ref reduce?) `(transform (@ (transformation ,(symbol->string transformation-ref)) (ref ,(symbol->string asset-ref)) (reduce ,(if reduce? "true" "false"))))])) (define (assets->sxml assets) `(assets ,@(for/list ([(label asset) assets]) `(asset (@ (id ,(symbol->string label))) ,(asset->sxml asset))))) (define cdecls (hash-ref contexts name)) `(context (@ (id ,name)) (includes ,@(for/list ([mode/name (hash-ref cdecls 'includes)]) (list (car mode/name) (cdr mode/name)))) (sorts ,@(for/list ([s (hash-ref cdecls 'sorts)]) `(sort (@ (id ,(symbol->string s)))))) (subsorts ,@(for/list ([sd (hash-ref cdecls 'subsorts)]) `(subsort (@ (subsort ,(symbol->string (car sd))) (supersort ,(symbol->string (cdr sd))))))) (vars ,@(vars->sxml (hash-ref cdecls 'vars))) (ops ,@(for/list ([od (hash-ref cdecls 'ops)]) (op->sxml od))) (rules ,@(for/list ([rd (hash-ref cdecls 'rules)]) (asset->sxml rd))) ,(assets->sxml (hash-ref cdecls 'assets)))) ;; Write the document to an XML file. (define (write-xml filename) (define sxml (get-document-sxml)) (call-with-output-file filename (λ (output-port) (srl:sxml->xml sxml output-port)) #:mode 'text #:exists 'replace)) Import an SXML document to the library . (define (import-sxml document-name sxml-document external-ref) (add-to-library document-name (sxml->document sxml-document) external-ref)) ;; Import an document from an XML file to the library. (define (import-xml document-name filename) (import-sxml document-name (call-with-input-file filename (λ (input-port) (ssax:xml->sxml input-port empty)) #:mode 'text) filename)) ;; Create internal data structures from source declarations ;; for various asset types. (define (make-term context-name term-expr loc) (define context (get-context context-name)) (define signature (hash-ref context 'compiled-signature)) (with-handlers ([exn:fail? (re-raise-exn loc)]) ((make-term* signature) term-expr))) (define (make-rule context-name rule-expr loc) (define context (get-context context-name)) (define signature (hash-ref context 'compiled-signature)) (with-handlers ([exn:fail? (re-raise-exn loc)]) (make-rule* signature (first (hash-ref (preprocess-source-declarations (list (cons rule-expr loc))) 'rules)) #f))) (define (make-transformation context-name label rule-expr loc) (define context (get-context context-name)) (define signature (hash-ref context 'compiled-signature)) (with-handlers ([exn:fail? (re-raise-exn loc)]) (make-transformation* signature (hash-ref (hash-ref (preprocess-source-declarations (list (cons (list 'asset label rule-expr) loc))) 'assets) label)))) (define (make-equation context-name equation-expr loc) (define context (get-context context-name)) (define signature (hash-ref context 'compiled-signature)) (with-handlers ([exn:fail? (re-raise-exn loc)]) (define ad (hash-ref (preprocess-source-declarations (list (cons (list 'asset 'dummy-label equation-expr) loc))) 'assets)) (unless (equal? (hash-count ad) 1) (error "can't happen")) (make-equation* signature (first (hash-values ad))))) (define (make-test context-name rule-expr loc) (define context (get-context context-name)) (define signature (hash-ref context 'compiled-signature)) (define rules (hash-ref context 'compiled-rules)) (with-handlers ([exn:fail? (re-raise-exn loc)]) (define rd (hash-ref (preprocess-source-declarations (list (cons rule-expr loc))) 'rules)) (unless (equal? (length rd) 1) (error "can't happen")) (match (first rd) [(list 'rule (hash-table) pattern replacement #f) (let* ([mt (make-pattern* signature (hash))] [term (mt pattern)] [expected (mt replacement)] [rterm (rewrite:reduce signature rules term)]) (list term expected rterm))] [_ (error "test may not contain rule clauses")]))) ;; Make a graphical representation of the signatures of all documents ( using graphviz ) . (define (write-signature-graphs directory) (define (delete-directory-recursive directory) (when (directory-exists? directory) (for ([item (directory-list directory)]) (define path (build-path directory item)) (cond [(file-exists? path) (delete-file path)] [(directory-exists? path) (delete-directory-recursive path)])) (delete-directory directory))) (define (recursive-file-list directory) (flatten (for/list ([item (directory-list directory)]) (define path (build-path directory item)) (cond [(file-exists? path) path] [(directory-exists? path) (recursive-file-list path)])))) (delete-directory-recursive directory) (for ([(name context) (in-hash contexts)]) (define path (build-path directory name)) (tools:signature->graphviz path (hash-ref context 'compiled-signature))) (define dot (find-executable-path "dot")) (unless dot (displayln "Warning: dot executable not found")) (for ([dot-file (recursive-file-list directory)]) (with-output-to-file (path-replace-extension dot-file #".png") (thunk (system* dot "-Tpng" dot-file))) (delete-file dot-file)))) ;; Retrieve an asset (define (lookup-asset assets label) (define value (for/fold ([a assets]) ([l (nested-labels label)]) (hash-ref a l))) (if (box? value) (unbox value) value)) (define (get-asset context label) (lookup-asset (hash-ref context 'compiled-assets) label)) ;; Utility functions for processing context declarations (define (clean-declarations cdecls) (for/fold ([c cdecls]) ([key (hash-keys cdecls)] #:when (string-prefix? (symbol->string key) "compiled")) (hash-remove c key))) ;; A document containing the builtin contexts (define builtins (~> (document (hash) empty (hash) (hash)) (add-builtin-context "truth" empty builtins:truth-signature builtins:truth-rules) (add-builtin-context "integers" (list (cons '(use "truth") #f)) builtins:integer-signature builtins:merged-integer-rules) (add-builtin-context "rational-numbers" (list (cons '(use "truth") #f)) builtins:rational-signature builtins:merged-rational-rules) (add-builtin-context "real-numbers" (list (cons '(use "truth") #f)) builtins:real-number-signature builtins:merged-real-number-rules) (add-builtin-context "IEEE-floating-point" (list (cons '(use "integers") #f)) builtins:IEEE-float-signature builtins:merged-IEEE-float-rules))) ;; An empty document has "builtins" in its library, ensuring that ;; it is always available. (define empty-document (~> (document (hash) empty (hash) (hash)) (add-to-library "builtins" builtins #f))) ;; Tests (module+ test (define test-document1 (~> empty-document (add-context-from-source "test" (list (cons '(sort foo) #f) (cons '(sort bar) #f) (cons '(subsort foo bar) #f))))) (check-equal? (~> empty-document (add-context-from-source "test" (list (cons '(subsort foo bar) #f)))) test-document1) (check-equal? (~> empty-document (add-context-from-source "test" (list (cons '(sort foo) #f) (cons '(sort bar) #f) (cons '(subsort foo bar) #f) (cons '(sort bar) #f) (cons '(subsort foo bar) #f) (cons '(sort foo) #f)))) test-document1) (check-equal? (~> empty-document (add-context-from-source "test" (list (cons '(subsort foo bar) #f) (cons '(op a-foo () foo) #f))) (make-term "test" '(term-or-var a-foo) #f) (terms:term->string)) "foo:a-foo") (check-equal? (~> empty-document (add-context-from-source "test" (list (cons '(subsort foo bar) #f) (cons '(op a-foo () foo) #f) (cons '(op a-foo ((sort bar)) foo) #f) (cons '(op a-bar ((var X foo)) bar) #f) (cons '(rule (term a-foo ((term-or-var X))) (term-or-var a-foo) ((var X foo))) #f) (cons '(asset eq1 (equation (term-or-var a-foo) (term a-foo ((term-or-var a-foo))) ())) #f) (cons '(asset tr1 (transformation (term-or-var a-foo) (term a-foo ((term-or-var a-foo))) ())) #f) (cons '(asset nested.asset (term-or-var a-foo)) #f) (cons '(asset deeply.nested.asset (term-or-var a-foo)) #f))) (get-context "test") (clean-declarations)) (hash 'includes empty 'locs (hash) 'sorts (set 'foo 'bar) 'subsorts (set (cons 'foo 'bar)) 'ops (set '(a-foo () foo) '(a-foo ((sort bar)) foo) '(a-bar ((var X foo)) bar)) 'vars (hash 'X 'foo) 'rules (list (list 'rule (hash 'X 'foo) '(term a-foo ((term-or-var X))) '(term-or-var a-foo) #f)) 'assets (hash 'eq1 (list 'equation (hash) '(term-or-var a-foo) '(term a-foo ((term-or-var a-foo))) #f) 'tr1 (list 'transformation (hash) '(term-or-var a-foo) '(term a-foo ((term-or-var a-foo))) #f) 'nested (list 'assets (hash 'asset '(term-or-var a-foo))) 'deeply (list 'assets (hash 'nested (list 'assets (hash 'asset '(term-or-var a-foo)))))))) (let ([decls (list (cons '(sort foo) #f) (cons '(sort bar) #f) (cons '(var X foo) #f) (cons '(var X foo) #f) (cons '(var X bar) #f))]) (check-not-exn (thunk (~> empty-document (add-context-from-source "test" (take decls 4))))) ;; var name redefined (check-exn exn:fail? (thunk (~> empty-document (add-context-from-source "test" decls))))) (let ([decls (list (cons '(subsort foo bar) #f) (cons '(op a-foo () foo) #f) (cons '(op a-foo ((sort bar)) foo) #f) (cons '(op a-bar ((var X foo)) bar) #f) (cons '(asset eq1 (equation (term-or-var a-foo) (term a-foo ((term-or-var a-foo))) ())) #f) (cons '(asset eq1 (equation (term-or-var a-foo) (term a-foo ((term-or-var a-foo))) ())) #f) (cons '(asset eq1 (equation (term a-foo ((term-or-var a-foo))) (term-or-var a-foo) ())) #f))]) (check-not-exn (thunk (~> empty-document (add-context-from-source "test" (take decls 5))))) ;; asset name redefined to the same value (check-not-exn (thunk (~> empty-document (add-context-from-source "test" (take decls 6))))) ;; asset name redefined to a different value (check-exn exn:fail? (thunk (~> empty-document (add-context-from-source "test" decls))))) ;; (check-exn exn:fail? ;; ; non-regular signature ;; (thunk ;; (~> empty-document ;; (add-context-from-source "test" ( list ( cons ' ( subsort A B ) # f ) ( cons ' ( subsort A C ) # f ) ;; (cons '(op foo ((sort B)) B) #f) ;; (cons '(op foo ((sort C)) C) #f)))))) (define test-document2 (~> empty-document (add-context-from-source "test" (list (cons '(use "builtins/integers") #f) (cons '(subsort foo bar) #f) (cons '(op a-foo () foo) #f) (cons '(op a-foo ((var X foo)) foo) #f) (cons '(rule (term a-foo ((term-or-var X))) (term-or-var a-foo) ((var X foo))) #f) (cons '(asset a-term (term-or-var a-foo)) #f) (cons '(asset a-rule (rule (term a-foo ((term-or-var X))) (term-or-var a-foo) ((var X foo)))) #f) (cons '(asset eq1 (equation (term a-foo ((term-or-var X))) (term-or-var a-foo) ((var X foo)))) #f) (cons '(asset eq2 (equation (integer 2) (integer 3) ())) #f) (cons '(asset tr (transformation (term-or-var X) (term a-foo ((term-or-var X))) ((var X foo)))) #f) (cons '(asset more-assets (assets [int1 (integer 2)] [int2 (integer 3)])) #f) (cons '(asset equation-from-rule (as-equation a-rule)) #f) (cons '(asset rule-from-equation (as-rule eq1 #f)) #f) (cons '(asset substituted-term (substitute a-rule a-term #f)) #f) (cons '(asset transformed-term (transform tr a-term #t)) #f))))) (check-true (~> test-document2 (make-test "test" '(rule (term a-foo ((term-or-var a-foo))) (term-or-var a-foo) ()) #f) check if the last two ( out of three ) elements are equal rest list->set set-count (equal? 1))) (check-equal? (~> test-document2 get-document-sxml sxml->document (get-context "test") (hash-remove 'locs)) (~> (get-context test-document2 "test") (hash-remove 'locs))) (check-equal? (~> test-document2 (get-context "test") (get-asset 'more-assets.int1)) 2)) Tests for module " transformations.rkt " ;; Put here to avoid cyclic dependencies. (module+ test (define a-document (~> empty-document (add-context-from-source "template" (list (cons '(subsort SQ Q) #f) (cons '(var a Q) #f) (cons '(var b SQ) #f) (cons '(op foo () SQ) #f) (cons '(op + ((sort SQ) (sort SQ)) SQ) #f) (cons '(op * ((sort SQ) (sort SQ)) Q) #f) (cons '(rule (term + ((term-or-var b) (term-or-var x))) (term-or-var b) ((var x SQ))) #f) (cons '(asset eq-asset (equation (term + ((term-or-var b) (term-or-var x))) (term-or-var b) ((var x SQ)))) #f) (cons '(asset term-asset (term-or-var foo)) #f) (cons '(asset rule-from-eq (as-rule eq-asset #f)) #f) (cons '(asset subst-term (substitute rule-from-eq term-asset #f)) #f))))) ;; hide-vars (check-equal? (~> a-document (add-context-from-source "test" (list (cons '(insert-use "template") #f))) (get-context "test")) (~> a-document (add-context-from-source "test" (list (cons '(subsort SQ Q) #f) (cons '(op foo () SQ) #f) (cons '(op + ((sort SQ) (sort SQ)) SQ) #f) (cons '(op * ((sort SQ) (sort SQ)) Q) #f) (cons '(rule (term + ((term-or-var b) (term-or-var x))) (term-or-var b) ((var a Q) (var b SQ) (var x SQ))) #f) (cons '(asset eq-asset (equation (term + ((term-or-var b) (term-or-var x))) (term-or-var b) ((var a Q) (var b SQ) (var x SQ)))) #f) (cons '(asset term-asset (term-or-var foo)) #f) (cons '(asset rule-from-eq (as-rule eq-asset #f)) #f) (cons '(asset subst-term (substitute rule-from-eq term-asset #f)) #f))) (get-context "test"))) (check-exn exn:fail? (thunk (~> a-document (add-context-from-source "with-var-term" (list (cons '(insert-extend "template") #f) (cons '(asset var-term-asset (term-or-var b)) #f))) (add-context-from-source "test" (list (cons '(insert-use "with-var-term") #f)))))) ;; rename-sort (check-equal? (~> a-document (add-context-from-source "test" (list (cons '(insert-extend "template" (rename-sort SQ M)) #f))) (get-context "test")) (~> a-document (add-context-from-source "test" (list (cons '(subsort M Q) #f) (cons '(var a Q) #f) (cons '(var b M) #f) (cons '(op foo () M) #f) (cons '(op + ((sort M) (sort M)) M) #f) (cons '(op * ((sort M) (sort M)) Q) #f) (cons '(rule (term + ((term-or-var b) (term-or-var x))) (term-or-var b) ((var x M))) #f) (cons '(asset eq-asset (equation (term + ((term-or-var b) (term-or-var x))) (term-or-var b) ((var x M)))) #f) (cons '(asset term-asset (term-or-var foo)) #f) (cons '(asset rule-from-eq (as-rule eq-asset #f)) #f) (cons '(asset subst-term (substitute rule-from-eq term-asset #f)) #f))) (get-context "test"))) ;; asset-prefix (check-equal? (~> a-document (add-context-from-source "test" (list (cons '(insert-extend "template" (asset-prefix foo)) #f))) (get-context "test")) (~> a-document (add-context-from-source "test" (list (cons '(subsort SQ Q) #f) (cons '(var a Q) #f) (cons '(var b SQ) #f) (cons '(op foo () SQ) #f) (cons '(op + ((sort SQ) (sort SQ)) SQ) #f) (cons '(op * ((sort SQ) (sort SQ)) Q) #f) (cons '(rule (term + ((term-or-var b) (term-or-var x))) (term-or-var b) ((var x SQ))) #f) (cons '(asset foo.eq-asset (equation (term + ((term-or-var b) (term-or-var x))) (term-or-var b) ((var x SQ)))) #f) (cons '(asset foo.term-asset (term-or-var foo)) #f) (cons '(asset foo.rule-from-eq (as-rule foo.eq-asset #f)) #f) (cons '(asset foo.subst-term (substitute foo.rule-from-eq foo.term-asset #f)) #f))) (get-context "test"))) ;; real->float (define heron (~> empty-document (add-context-from-source "using-rational" (list (cons '(use "builtins/real-numbers") #f) (cons '(op heron ((var x ℝnn) (var ε ℝp) (var e ℝnn)) ℝnn) #f) (cons '(rule (term heron ((term-or-var x) (term-or-var ε) (term-or-var e))) (term-or-var e) ((term _< ((term abs ((term _- ((term-or-var x) (term ^ ((term-or-var e) (integer 2))))))) (term-or-var ε))))) #f) (cons '(rule (term heron ((term-or-var x) (term-or-var ε) (term-or-var e))) (term heron ((term-or-var x) (term-or-var ε) (term _× ((rational 1/2) (term _+ ((term-or-var e) (term _÷ ((term-or-var x) (term-or-var e))))))))) ()) #f) (cons '(asset rule-asset (rule (term heron ((term-or-var x) (term-or-var ε) (term-or-var e))) (term heron ((term-or-var x) (term-or-var ε) (term _× ((rational 1/2) (term _+ ((term-or-var e) (term _÷ ((term-or-var x) (term-or-var e))))))))) ())) #f) (cons '(asset eq-asset (equation (term heron ((term-or-var x) (term-or-var ε) (term-or-var e))) (term heron ((term-or-var x) (term-or-var ε) (term _× ((rational 1/2) (term _+ ((term-or-var e) (term _÷ ((term-or-var x) (term-or-var e))))))))) ())) #f) (cons '(asset term-asset (term _× ((rational 1/2) (term heron ((term-or-var x) (term-or-var ε) (term-or-var e)))))) #f))) (add-context-from-source "using-float" (list (cons '(use "builtins/real-numbers") #f) (cons '(use "builtins/IEEE-floating-point") #f) (cons '(op heron ((var x FP64) (var ε FP64) (var e FP64)) FP64) #f) (cons '(rule (term heron ((term-or-var x) (term-or-var ε) (term-or-var e))) (term-or-var e) ((term _< ((term abs ((term _- ((term-or-var x) (term ^ ((term-or-var e) (integer 2))))))) (term-or-var ε))))) #f) (cons '(rule (term heron ((term-or-var x) (term-or-var ε) (term-or-var e))) (term heron ((term-or-var x) (term-or-var ε) (term _× ((floating-point 0.5) (term _+ ((term-or-var e) (term _÷ ((term-or-var x) (term-or-var e))))))))) ()) #f) (cons '(asset rule-asset (rule (term heron ((term-or-var x) (term-or-var ε) (term-or-var e))) (term heron ((term-or-var x) (term-or-var ε) (term _× ((floating-point 0.5) (term _+ ((term-or-var e) (term _÷ ((term-or-var x) (term-or-var e))))))))) ())) #f) (cons '(asset eq-asset (equation (term heron ((term-or-var x) (term-or-var ε) (term-or-var e))) (term heron ((term-or-var x) (term-or-var ε) (term _× ((floating-point 0.5) (term _+ ((term-or-var e) (term _÷ ((term-or-var x) (term-or-var e))))))))) ())) #f) (cons '(asset term-asset (term _× ((floating-point 0.5) (term heron ((term-or-var x) (term-or-var ε) (term-or-var e)))))) #f))) (add-context-from-source "converted-to-float" (list (cons '(insert-extend "using-rational" (real->float FP64)) #f))) )) (check-equal? (~> heron (get-context "converted-to-float")) (~> heron (get-context "using-float"))) )
null
https://raw.githubusercontent.com/khinsen/leibniz/881955b4c642114fbdc2f36ecc99582ae2371238/leibniz/documents.rkt
racket
Re-raise exceptions with the source location information from the document Compile declarations from a context to internal datas tructures. Merge the sort graphs of the included contexts. Process the sort declarations. Merge the signatures of the included contexts. Process the var declarations. Check for non-regularity. Merge the rule lists of the included contexts. Process the rule declarations Helper function for compiling a single asset. TODO Should test for valid term declarations, rather than suppose that it must be a term since it's no other valid declaration. Helper functions for computing dependent assets Merge the assets of the included contexts. Process the asset declarations Compute unevaluated assets Return compiled assets, guaranteed without unevaluated boxes A document is a collection of contexts that can refer to each other by name. Each document also keeps a library of other documents to whose contexts its own contexts can refer. The dependency graph is acyclic by construction. contexts: a hash mapping context names to hashes with keys 'includes 'sorts 'ops 'vars 'rules 'assets, values are lists/sets/hashes of the declarations in each category order: a list of context names in the inverse order of definition library: a hash mapping document names to documents library-refs: a hash mapping document names to external references (filenames for now, later maybe DOIs or hashes) Add another document to the library. Add a built-in context. Used only for preparing a single document called "builtins", which is automatically added to every other document's library. and convert them to the internal context data structure. Add a context defined by a sequence of source declarations. Add a context defined by a context data structure. Retrieve a context by name Write the document to an XML file. Import an document from an XML file to the library. Create internal data structures from source declarations for various asset types. Make a graphical representation of the signatures of all documents Retrieve an asset Utility functions for processing context declarations A document containing the builtin contexts An empty document has "builtins" in its library, ensuring that it is always available. Tests var name redefined asset name redefined to the same value asset name redefined to a different value (check-exn exn:fail? ; non-regular signature (thunk (~> empty-document (add-context-from-source "test" (cons '(op foo ((sort B)) B) #f) (cons '(op foo ((sort C)) C) #f)))))) Put here to avoid cyclic dependencies. hide-vars rename-sort asset-prefix real->float
#lang racket (provide empty-document add-to-library add-context-from-source get-asset get-context make-term make-rule make-transformation make-equation make-test get-document-sxml get-context-sxml write-xml import-xml write-signature-graphs clean-declarations) (require (prefix-in sorts: "./sorts.rkt") (only-in "./sorts.rkt" sort-graph? empty-sort-graph) (prefix-in operators: "./operators.rkt") (prefix-in terms: "./terms.rkt") (prefix-in equations: "./equations.rkt") (prefix-in rewrite: "./rewrite.rkt") (prefix-in tools: "./tools.rkt") (prefix-in builtins: "./builtin-contexts.rkt") "./transformations.rkt" "./lightweight-class.rkt" racket/hash sxml threading) (module+ test (require rackunit)) (define-struct (exn:fail:leibniz exn:fail) (a-srcloc-list) #:property prop:exn:srclocs (λ (a-struct) (match a-struct [(struct exn:fail:leibniz (msg marks a-srcloc-list)) a-srcloc-list]))) (define ((re-raise-exn loc) e) (if loc (raise (make-exn:fail:leibniz (exn-message e) (current-continuation-marks) (for/list ([l loc]) (and l (apply srcloc l))))) (raise e))) (define (get-loc locs decl) (cond [(procedure? locs) (locs decl)] [(hash? locs) (hash-ref locs decl #f)] [else #f])) (define (compile-sort-graph includes sort-decls subsort-decls locs) (define after-includes (for/fold ([ms sorts:empty-sort-graph]) ([m/c includes]) (sorts:merge-sort-graphs ms (operators:signature-sort-graph (hash-ref (cdr m/c) 'compiled-signature))))) (define after-sorts (for/fold ([sorts after-includes]) ([s sort-decls]) (with-handlers ([exn:fail? (re-raise-exn (get-loc locs s))]) (sorts:add-sort sorts s)))) Process the subsort declarations . (for/fold ([sorts after-sorts]) ([ss subsort-decls]) (with-handlers ([exn:fail? (re-raise-exn (get-loc locs ss))]) (sorts:add-subsort-relation sorts (car ss) (cdr ss))))) (define (compile-signature sorts includes op-decls var-decls locs) (define (argsort sort-or-var-decl) (match sort-or-var-decl [(list 'sort sort-id) sort-id] [(list 'var var-name sort-id) sort-id])) (define after-includes (for/fold ([msig (operators:empty-signature sorts)]) ([m/c includes]) (define csig (hash-ref (cdr m/c) 'compiled-signature)) (define isig (case (car m/c) [(use) (operators:remove-vars csig)] [(extend) csig])) (operators:merge-signatures msig isig sorts))) Process the op declarations . (define after-ops (for/fold ([sig after-includes]) ([od op-decls]) (with-handlers ([exn:fail? (re-raise-exn (get-loc locs od))]) (match-define (list name arity rsort) od) (operators:add-op sig name (map argsort arity) rsort #:meta (get-loc locs od))))) (define signature (for/fold ([sig after-ops]) ([(vname vsort) var-decls]) (with-handlers ([exn:fail? (re-raise-exn (get-loc locs (hash vname vsort)))]) (operators:add-var sig vname vsort)))) (define non-regular (operators:non-regular-op-example signature)) (when non-regular (match-let ([(list op arity rsorts) non-regular]) (displayln (format "Warning: operator ~a~a has ambiguous sorts ~a" op arity rsorts)))) signature) (define (make-term* signature) (letrec ([fn (match-lambda [(list 'term-or-var name) (terms:make-var-or-term signature name)] [(list 'term op args) (terms:make-term signature op (map fn args))] [(list 'integer n) n] [(list 'rational r) r] [(list 'floating-point fp) fp])]) fn)) (define (make-pattern* signature local-vars) (letrec ([fn (match-lambda [#f #f] [(list 'term-or-var name) (terms:make-var-or-term signature name local-vars)] [(list 'term op args) (terms:make-term signature op (map fn args))] [(list 'integer n) n] [(list 'rational r) r] [(list 'floating-point fp) fp])]) fn)) (define (make-rule* signature rule-expr check-equationality?) (match rule-expr [(list 'rule vars pattern replacement condition) (let* ([mp (make-pattern* signature vars)]) (equations:make-rule signature (mp pattern) (mp condition) (mp replacement) #f check-equationality?))] [_ #f])) (define (make-transformation* signature rule-expr) (and~> (make-rule* signature (cons 'rule (rest rule-expr)) #f) (equations:make-transformation signature _))) (define (as-rule* signature value flip?) (cond [(equations:rule? value) value] [(equations:equation? value) (define-values (left right) (if flip? (values (equations:equation-right value) (equations:equation-left value)) (values (equations:equation-left value) (equations:equation-right value)))) (equations:make-rule signature left (equations:equation-condition value) right #f #t)] [else (error (format "cannot convert ~a to a rule" value))])) (define (compile-rules signature includes rule-decls locs) (define after-includes (for/fold ([mrl equations:empty-rulelist]) ([m/c includes]) (equations:merge-rulelists mrl (hash-ref (cdr m/c) 'compiled-rules) signature))) (for/fold ([rl after-includes]) ([rd rule-decls]) (with-handlers ([exn:fail? (re-raise-exn (get-loc locs rd))]) (equations:add-rule rl (make-rule* signature rd #t))))) (define (make-equation* signature equation-expr) (match equation-expr [(list 'equation vars left right condition) (let ([mp (make-pattern* signature vars)]) (equations:make-equation signature (mp left) (mp condition) (mp right)))] [_ #f])) (define (as-equation* signature value) (cond [(equations:equation? value) value] [(equations:rule? value) (equations:make-equation signature (equations:rule-pattern value) (equations:rule-condition value) (equations:rule-replacement value))] [else (error (format "cannot convert ~a to an equation" value))])) (define (substitution* signature rule value) (unless (equations:rule? rule) (error (format "not a rule: ~a" rule))) (define transformation (equations:make-transformation signature rule)) (cond [(terms:term? value) (rewrite:substitute signature transformation value)] [(equations:equation? value) (rewrite:substitute-equation signature transformation value)] [else (error (format "not a term or equation: ~a" value))])) (define (transformation* signature transformation value) (unless (equations:transformation? transformation) (error (format "not a transformation: ~a" transformation))) (cond [(terms:term? value) (rewrite:transform signature transformation value)] [(equations:equation? value) (rewrite:transform-equation signature transformation value)] [else (error (format "not a term or equation: ~a" value))])) (define (reduce* signature rulelist value) (unless (equations:rulelist? rulelist) (error (format "not a rulelist: ~a" rulelist))) (cond [(terms:term? value) (rewrite:reduce signature rulelist value)] [(equations:equation? value) (rewrite:reduce-equation signature rulelist value)] [else (error (format "not a term or equation: ~a" value))])) (define (combine-assets label asset1 asset2) (cond [(equal? asset1 asset2) asset1] [(and (equal? (first asset1) 'assets) (equal? (first asset1) 'assets)) (list 'assets (hash-union (second asset1) (second asset2) #:combine/key combine-assets))] [else (error (format "Asset label ~a already used for value ~a" label asset1))])) (define (combine-compiled-assets label asset1 asset2) (cond [(equal? asset1 asset2) asset1] [(and (hash? asset1) (hash? asset2)) (hash-union asset1 asset2 #:combine/key combine-compiled-assets)] [(and (box? asset1) (not (unbox asset1))) asset2] [(and (box? asset2) (not (unbox asset2))) asset1] [else (error (format "Asset label ~a already used for value ~a" label asset1))])) (define (compile-assets signature rulelist includes asset-decls locs) (define unevaluated empty) (define (compile-asset decl) (match decl [(list 'rule arg ...) (box (make-rule* signature decl #f))] [(list 'equation arg ...) (box (make-equation* signature decl))] [(list 'transformation arg ...) (box (make-transformation* signature decl))] [(or (list 'as-equation _) (list 'as-rule _ _) (list 'substitute _ _ _) (list 'transform _ _ _)) (let ([no-value (box #f)]) (set! unevaluated (cons (list no-value decl) unevaluated)) no-value)] [(list 'assets assets) (for/hash ([(label value) assets]) (values label (compile-asset value)))] [term (box ((make-term* signature) decl))])) (define (compute-asset assets decl) (match decl [(list 'as-equation label) (and~> (lookup-asset assets label) (as-equation* signature _))] [(list 'as-rule label flip?) (and~> (lookup-asset assets label) (as-rule* signature _ flip?))] [(list 'substitute rule-label asset-label reduce?) (let* ([rule (lookup-asset assets rule-label)] [asset (lookup-asset assets asset-label)] [substituted (and rule asset (substitution* signature rule asset))]) (if reduce? (and substituted (reduce* signature rulelist substituted)) substituted))] [(list 'transform tr-label asset-label reduce?) (let* ([tr (lookup-asset assets tr-label)] [asset (lookup-asset assets asset-label)] [transformed (and tr asset (transformation* signature tr asset))]) (if reduce? (and transformed (reduce* signature rulelist transformed)) transformed))])) (define (compute-assets unevaluated) (for/fold ([remaining empty]) ([box+decl unevaluated]) (match-define (list box decl) box+decl) (define value (compute-asset assets decl)) (if value (begin (set-box! box value) remaining) (cons (list box decl) remaining)))) (define (compute-assets-iteratively unevaluated) (let ([remaining (compute-assets unevaluated)]) (if (equal? (length remaining) (length unevaluated)) remaining (compute-assets-iteratively remaining)))) (define after-includes (for/fold ([merged-assets (hash)]) ([m/c includes]) (hash-union merged-assets (hash-ref (cdr m/c) 'compiled-assets (hash)) #:combine/key combine-compiled-assets))) (define assets (for/fold ([assets after-includes]) ([(label ad) asset-decls]) (with-handlers ([exn:fail? (re-raise-exn (get-loc locs (hash label ad)))]) (hash-union assets (hash label (compile-asset ad)) #:combine/key combine-compiled-assets)))) (define remaining (compute-assets-iteratively unevaluated)) (unless (empty? remaining) (error (format "~a remaining unevaluated assets" (length remaining)))) assets) Convert an SXML document to the internal document data structure . (define (combine-varsets name sort1 sort2) (unless (equal? sort1 sort2) (error (format "Var ~a of sort ~a redefined with sort ~a" name sort1 sort2))) sort1) (define (sxml->document sxml-document) (match-define (list '*TOP* (list 'leibniz-document (list 'library document-refs ...) sxml-contexts ...)) sxml-document) (let ([doc-with-library (for/fold ([doc empty-document]) ([dref document-refs]) (match-define `(document-ref (@ (id ,name)) ,ref) dref) (send doc import-xml name ref))]) (for/fold ([doc doc-with-library]) ([sxml-context sxml-contexts]) (define-values (namespace context-decls) (sxml->context sxml-context)) (send doc add-context namespace (hash-set context-decls 'locs (hash)))))) (define (sxml->context sxml-context) (define (sxml->arg sxml-arg) (match sxml-arg [`(var (@ (id ,var-name) (sort ,sort-name))) (list 'var (string->symbol var-name) (string->symbol sort-name))] [`(var (@ (sort ,sort-name) (id ,var-name))) (list 'var (string->symbol var-name) (string->symbol sort-name))] [`(sort (@ (id ,sort-name))) (list 'sort (string->symbol sort-name))])) (define (sxml->vars sxml-vars) (for/fold ([vars (hash)]) ([v sxml-vars]) (define new-var (match v [(or `(var (@ (id ,vn) (sort ,sn))) `(var (@ (sort ,sn) (id ,vn)))) (hash (string->symbol vn) (string->symbol sn))])) (hash-union vars new-var #:combine/key combine-varsets))) (define (sxml->asset sxml-asset) (match sxml-asset [`(assets (asset (@ (id ,label)) ,value) ...) (list 'assets (for/hash ([l label] [v value]) (values (string->symbol l) (sxml->asset v))))] [`(equation (vars ,ev ...) (left ,el) ,ec (right ,er)) (list 'equation (sxml->vars ev) (sxml->asset el) (sxml->asset er) (match ec [`(condition) #f] [`(condition ,term) term]))] [`(rule (vars ,rv ...) (pattern ,rp) ,rc (replacement ,rr)) (list 'rule (sxml->vars rv) (sxml->asset rp) (sxml->asset rr) (match rc [`(condition) #f] [`(condition ,term) term]))] [`(transformation (vars ,rv ...) (pattern ,rp) ,rc (replacement ,rr)) (list 'transformation (sxml->vars rv) (sxml->asset rp) (sxml->asset rr) (match rc [`(condition) #f] [`(condition ,term) term]))] [`(term (@ (op ,op-string)) ,args ...) (list 'term (string->symbol op-string) (map sxml->asset args))] [`(term-or-var (@ (name ,name-string))) (list 'term-or-var (string->symbol name-string))] [`(,number-tag (@ (value ,v))) (list number-tag (read (open-input-string v)))] [`(as-equation (@ (ref ,asset-ref))) (list 'as-equation (string->symbol asset-ref))] [`(as-rule (@ (ref ,asset-ref) (flip ,flip?))) (list 'as-rule (string->symbol asset-ref) (equal? flip? "true"))] [`(substitute (@ (substitute ,substitution-ref) (ref ,asset-ref) (reduce ,reduce?))) (list 'substitute (string->symbol substitution-ref) (string->symbol asset-ref) (equal? reduce? "true"))] [`(transform (@ (transformation ,transformation-ref) (ref ,asset-ref) (reduce ,reduce?))) (list 'transform (string->symbol transformation-ref) (string->symbol asset-ref) (equal? reduce? "true"))])) (match-define `(context (@ (id, name)) (includes ,sxml-includes ...) (sorts ,sxml-sorts ...) (subsorts ,sxml-subsorts ...) (vars ,sxml-vars ...) (ops ,sxml-ops ...) (rules ,sxml-rules ...) (assets ,sxml-assets ...)) sxml-context) (define includes (for/list ([include sxml-includes]) (match include [(list mode include-ref) (cons mode include-ref)]))) (define sorts (for/set ([sort sxml-sorts]) (match sort [`(sort (@ (id ,s))) (string->symbol s)]))) (define subsorts (for/set ([subsort sxml-subsorts]) (match subsort [`(subsort (@ (subsort ,s1) (supersort ,s2))) (cons (string->symbol s1) (string->symbol s2))] [`(subsort (@ (supersort ,s2) (subsort ,s1))) (cons (string->symbol s1) (string->symbol s2))]))) (define vars (sxml->vars sxml-vars)) (define ops (for/set ([op sxml-ops]) (match op [`(op (@ (id ,on)) (arity ,oa ...) (sort (@ (id ,os)))) (list (string->symbol on) (map sxml->arg oa) (string->symbol os))]))) (define rules (for/list ([rule sxml-rules]) (sxml->asset rule))) (define assets (second (sxml->asset (cons 'assets sxml-assets)))) (values name (hash 'includes includes 'sorts sorts 'subsorts subsorts 'vars vars 'ops ops 'rules rules 'assets assets 'locs (hash)))) Decompose an compound asset label into a list of nested simple asset labels (define (nested-labels compound-label) (~> (symbol->string compound-label) (string-split ".") (map string->symbol _))) (define-class document (field contexts order library library-refs) (define (add-to-library name library-document external-ref) (document contexts order (hash-set library name library-document) (hash-set library-refs name external-ref))) (define (add-builtin-context name include-decls signature rules) (define temp-doc (add-context-from-source name include-decls)) (define inclusion-decls (send temp-doc get-context name)) (document (hash-set contexts name (hash 'includes (hash-ref inclusion-decls 'includes) 'compiled-signature signature 'compiled-rules rules 'compiled-assets (hash))) (cons name order) library library-refs)) Take context declarations parsed by ' extensions to Scribble (define (preprocess-source-declarations source-decls) (define (add-loc context decl loc) (hash-update context 'locs (λ (ls) (if (and loc (not (hash-has-key? ls decl))) (hash-set ls decl (list loc)) ls)))) (define (add-include context mode cname loc) (~> context (hash-update 'includes (λ (cnames) (append cnames (list (cons mode cname))))) (add-loc cname loc))) (define (add-sort context s loc) (~> context (hash-update 'sorts (λ (ss) (set-add ss s))) (add-loc s loc))) (define (add-subsort context s1 s2 loc) (define new-ss (cons s1 s2)) (~> context (hash-update 'subsorts (λ (ss) (set-add ss new-ss))) (add-loc new-ss loc))) (define (add-op context name arity rsort loc) (define new-op (list name arity rsort)) (~> context (hash-update 'ops (λ (ops) (set-add ops new-op))) (add-loc new-op loc))) (define (add-var context name sort loc) (define new-var (hash name sort)) (~> context (hash-update 'vars (λ (vars) (hash-union vars new-var #:combine/key combine-varsets))) (add-loc new-var loc))) (define (group-clauses clauses loc) (for/fold ([vars (hash)] [condition #f]) ([c clauses]) (match c [`(var ,name ,sort) (values (hash-union vars (hash name sort) #:combine/key combine-varsets) condition)] [term (if condition (values vars (list 'term '_∧ (list condition term))) (values vars term))]))) (define (add-rule context pattern replacement clauses loc) (define-values (vars condition) (group-clauses clauses loc)) (define new-rule (list 'rule vars pattern replacement condition)) (~> context (hash-update 'rules (λ (rules) (if (member new-rule rules) rules (append rules (list new-rule))))) (add-loc new-rule loc))) (define (preprocess-asset value loc) (match value [(list 'rule pattern replacement clauses) (define-values (vars condition) (group-clauses clauses loc)) (list 'rule vars pattern replacement condition)] [(list 'equation left right clauses) (define-values (vars condition) (group-clauses clauses loc)) (list 'equation vars left right condition)] [(list 'transformation pattern replacement clauses) (define-values (vars condition) (group-clauses clauses loc)) (list 'transformation vars pattern replacement condition)] [(list 'assets (list label value) ...) (list 'assets (for/hash ([l label] [v value]) (values l (preprocess-asset v loc))))] [(list 'as-rule label flip?) value] [(list 'as-equation label) value] [(list (or'substitute 'transform) label rule value reduce?) value] [term term])) (define (add-asset context label value loc) (define preprocessed-value (preprocess-asset value loc)) (define nested (nested-labels label)) (define new-asset (hash (first nested) (for/fold ([v preprocessed-value]) ([l (reverse (rest nested))]) (list 'assets (hash l v))))) (~> context (hash-update 'assets (λ (assets) (hash-union assets new-asset #:combine/key combine-assets))) (add-loc new-asset loc))) (define (resolve-includes context) (define (resolve-includes* document context) (define include-refs (hash-ref context 'includes)) (define includes (for/list ([mode/name include-refs]) (match-define (cons mode name) mode/name) (define-values (i-doc i-c) (send document get-document-and-context name)) (cons mode (if (equal? i-doc builtins) name (resolve-includes* i-doc i-c))))) (hash-set context 'includes includes)) (resolve-includes* this context)) (define (merge context inserted-context loc) (define (merge* key v1 v2) (case key [(includes rules) (remove-duplicates (append v1 v2))] [(sorts subsorts ops) (set-union v1 v2)] [(vars) (hash-union v1 v2 #:combine/key combine-varsets)] [(assets) (hash-union v1 v2 #:combine/key combine-assets)] [(locs) (hash-union v1 v2 #:combine (λ (a b) a))])) (define (add-loc-prefix context loc) (hash-update context 'locs (λ (ls) (for/hash ([(d l) ls]) (values d (cons loc l)))))) (hash-union context (add-loc-prefix inserted-context loc) #:combine/key merge*)) (~> (for/fold ([context (hash 'includes empty 'sorts (set) 'subsorts (set) 'ops (set) 'vars (hash) 'rules (list) 'assets (hash) 'locs (hash))]) ([decl/loc source-decls]) (match-define (cons decl loc) decl/loc) (match decl [(list 'use cname) (add-include context 'use cname loc)] [(list 'extend cname) (add-include context 'extend cname loc)] [(list (and (or 'insert-use 'insert-extend) insert-type) cname tr ...) (define (apply-transformations context tr) (with-handlers ([exn:fail? (re-raise-exn (list loc))]) (transform-context-declarations context tr))) (define (merge-recursively insertion context) (define (insert-includes context) (for/fold ([c context]) ([mode/context (hash-ref insertion 'includes)] #:unless (string? (cdr mode/context))) (if (equal? (car mode/context) 'use) (hide-context-vars (cdr mode/context)) (cdr mode/context)) (merge-recursively (cdr mode/context) c))) (define (cleanup-insertion insertion) (clean-declarations (hash-update insertion 'includes (λ (crefs) (for/list ([mode/name-or-context crefs] #:when (string? (cdr mode/name-or-context))) mode/name-or-context))))) (~> context insert-includes (merge (cleanup-insertion insertion) loc))) (define (maybe-hide-vars context) (if (equal? insert-type 'insert-use) (hide-context-vars context) context)) (~> (get-context cname) maybe-hide-vars resolve-includes (apply-transformations tr) (merge-recursively context))] [(list 'sort s) (add-sort context s loc)] [(list 'subsort s1 s2) (~> context (add-sort s1 loc) (add-sort s2 loc) (add-subsort s1 s2 loc))] [(list 'op name arity rsort) (for/fold ([context (~> context (add-sort rsort loc) (add-op name arity rsort loc))]) ([arg arity]) (match arg [(list 'var name sort) (add-var context name sort loc)] [(list 'sort s) context]))] [(list 'var name sort) (add-var context name sort loc)] [(list 'rule pattern replacement clauses) (add-rule context pattern replacement clauses loc)] [(list 'asset label value) (add-asset context label value loc)])))) (define (add-context-from-source name source-decls) (add-context name (preprocess-source-declarations source-decls))) (define (add-context name context) (define locs (hash-ref context 'locs)) (define included-contexts (for/list ([mode/name (hash-ref context 'includes)]) (with-handlers ([exn:fail? (re-raise-exn (get-loc locs name))]) (cons (car mode/name) (get-context (cdr mode/name)))))) (define sorts (compile-sort-graph included-contexts (hash-ref context 'sorts) (hash-ref context 'subsorts) locs)) (define signature (compile-signature sorts included-contexts (hash-ref context 'ops) (hash-ref context 'vars) locs)) (define rules (compile-rules signature included-contexts (hash-ref context 'rules) locs)) (define assets (compile-assets signature rules included-contexts (hash-ref context 'assets) locs)) (define compiled (hash 'compiled-signature signature 'compiled-rules rules 'compiled-assets assets)) (document (hash-set contexts name (hash-union context compiled)) (cons name order) library library-refs)) (define (get-document-and-context name) (define elements (map string-trim (string-split name "/"))) (case (length elements) [(1) (unless (hash-has-key? contexts (first elements)) (error (format "no context named ~a" name))) (values this (hash-ref contexts (first elements)))] [(2) (unless (hash-has-key? library (first elements)) (error (format "no library named ~a" (first elements)))) (define library-doc (hash-ref library (first elements))) (values library-doc (send library-doc get-context (second elements)))] [else (error (format "illegal context specification ~a" name))])) (define (get-context name) (define-values (document context) (get-document-and-context name)) context) Return an SXML representation of the document (define (get-document-sxml) `(*TOP* (leibniz-document (library ,@(for/list ([(name ref) library-refs] #:unless (equal? name "builtins")) `(document-ref (@ (id ,name)) ,ref))) ,@(for/list ([name (reverse order)]) (get-context-sxml name))))) Return an SXML representation of a context . (define (get-context-sxml name) (define (vars->sxml vars) (for/list ([(name sort) vars]) `(var (@ (id ,(symbol->string name)) (sort ,(symbol->string sort)))))) (define (op->sxml op) `(op (@ (id ,(symbol->string (first op)))) (arity ,@(for/list ([sv (second op)]) (if (equal? (first sv) 'sort) `(sort (@ (id ,(symbol->string (second sv))))) `(var (@ (id ,(symbol->string (second sv))) (sort ,(symbol->string (third sv)))))))) (sort (@ (id ,(symbol->string (third op))))))) (define (condition->sxml condition) (if (equal? condition #f) `(condition) `(condition ,(asset->sxml condition)))) (define (asset->sxml asset) (match asset [(list 'assets asset-data) (assets->sxml asset-data)] [(list 'equation vars left right condition) `(equation (vars ,@(vars->sxml vars)) (left ,(asset->sxml left)) ,(condition->sxml condition) (right ,(asset->sxml right)))] [(list 'rule vars pattern replacement condition) `(rule (vars ,@(vars->sxml vars)) (pattern ,(asset->sxml pattern)) ,(condition->sxml condition) (replacement ,(asset->sxml replacement)))] [(list 'transformation vars pattern replacement condition) `(transformation (vars ,@(vars->sxml vars)) (pattern ,(asset->sxml pattern)) ,(condition->sxml condition) (replacement ,(asset->sxml replacement)))] [(list 'term-or-var name) `(term-or-var (@ (name ,(symbol->string name))))] [(list 'term op args) `(term (@ (op ,(symbol->string op))) ,@(for/list ([arg args]) (asset->sxml arg)))] [(list (and number-tag (or 'integer 'rational 'floating-point)) x) `(,number-tag (@ (value ,(format "~a" x))))] [(list 'as-equation asset-ref) `(as-equation (@ (ref ,(symbol->string asset-ref))))] [(list 'as-rule asset-ref flip?) `(as-rule (@ (ref ,(symbol->string asset-ref)) (flip ,(if flip? "true" "false"))))] [(list 'substitute substitution-ref asset-ref reduce?) `(substitute (@ (substitute ,(symbol->string substitution-ref)) (ref ,(symbol->string asset-ref)) (reduce ,(if reduce? "true" "false"))))] [(list 'transform transformation-ref asset-ref reduce?) `(transform (@ (transformation ,(symbol->string transformation-ref)) (ref ,(symbol->string asset-ref)) (reduce ,(if reduce? "true" "false"))))])) (define (assets->sxml assets) `(assets ,@(for/list ([(label asset) assets]) `(asset (@ (id ,(symbol->string label))) ,(asset->sxml asset))))) (define cdecls (hash-ref contexts name)) `(context (@ (id ,name)) (includes ,@(for/list ([mode/name (hash-ref cdecls 'includes)]) (list (car mode/name) (cdr mode/name)))) (sorts ,@(for/list ([s (hash-ref cdecls 'sorts)]) `(sort (@ (id ,(symbol->string s)))))) (subsorts ,@(for/list ([sd (hash-ref cdecls 'subsorts)]) `(subsort (@ (subsort ,(symbol->string (car sd))) (supersort ,(symbol->string (cdr sd))))))) (vars ,@(vars->sxml (hash-ref cdecls 'vars))) (ops ,@(for/list ([od (hash-ref cdecls 'ops)]) (op->sxml od))) (rules ,@(for/list ([rd (hash-ref cdecls 'rules)]) (asset->sxml rd))) ,(assets->sxml (hash-ref cdecls 'assets)))) (define (write-xml filename) (define sxml (get-document-sxml)) (call-with-output-file filename (λ (output-port) (srl:sxml->xml sxml output-port)) #:mode 'text #:exists 'replace)) Import an SXML document to the library . (define (import-sxml document-name sxml-document external-ref) (add-to-library document-name (sxml->document sxml-document) external-ref)) (define (import-xml document-name filename) (import-sxml document-name (call-with-input-file filename (λ (input-port) (ssax:xml->sxml input-port empty)) #:mode 'text) filename)) (define (make-term context-name term-expr loc) (define context (get-context context-name)) (define signature (hash-ref context 'compiled-signature)) (with-handlers ([exn:fail? (re-raise-exn loc)]) ((make-term* signature) term-expr))) (define (make-rule context-name rule-expr loc) (define context (get-context context-name)) (define signature (hash-ref context 'compiled-signature)) (with-handlers ([exn:fail? (re-raise-exn loc)]) (make-rule* signature (first (hash-ref (preprocess-source-declarations (list (cons rule-expr loc))) 'rules)) #f))) (define (make-transformation context-name label rule-expr loc) (define context (get-context context-name)) (define signature (hash-ref context 'compiled-signature)) (with-handlers ([exn:fail? (re-raise-exn loc)]) (make-transformation* signature (hash-ref (hash-ref (preprocess-source-declarations (list (cons (list 'asset label rule-expr) loc))) 'assets) label)))) (define (make-equation context-name equation-expr loc) (define context (get-context context-name)) (define signature (hash-ref context 'compiled-signature)) (with-handlers ([exn:fail? (re-raise-exn loc)]) (define ad (hash-ref (preprocess-source-declarations (list (cons (list 'asset 'dummy-label equation-expr) loc))) 'assets)) (unless (equal? (hash-count ad) 1) (error "can't happen")) (make-equation* signature (first (hash-values ad))))) (define (make-test context-name rule-expr loc) (define context (get-context context-name)) (define signature (hash-ref context 'compiled-signature)) (define rules (hash-ref context 'compiled-rules)) (with-handlers ([exn:fail? (re-raise-exn loc)]) (define rd (hash-ref (preprocess-source-declarations (list (cons rule-expr loc))) 'rules)) (unless (equal? (length rd) 1) (error "can't happen")) (match (first rd) [(list 'rule (hash-table) pattern replacement #f) (let* ([mt (make-pattern* signature (hash))] [term (mt pattern)] [expected (mt replacement)] [rterm (rewrite:reduce signature rules term)]) (list term expected rterm))] [_ (error "test may not contain rule clauses")]))) ( using graphviz ) . (define (write-signature-graphs directory) (define (delete-directory-recursive directory) (when (directory-exists? directory) (for ([item (directory-list directory)]) (define path (build-path directory item)) (cond [(file-exists? path) (delete-file path)] [(directory-exists? path) (delete-directory-recursive path)])) (delete-directory directory))) (define (recursive-file-list directory) (flatten (for/list ([item (directory-list directory)]) (define path (build-path directory item)) (cond [(file-exists? path) path] [(directory-exists? path) (recursive-file-list path)])))) (delete-directory-recursive directory) (for ([(name context) (in-hash contexts)]) (define path (build-path directory name)) (tools:signature->graphviz path (hash-ref context 'compiled-signature))) (define dot (find-executable-path "dot")) (unless dot (displayln "Warning: dot executable not found")) (for ([dot-file (recursive-file-list directory)]) (with-output-to-file (path-replace-extension dot-file #".png") (thunk (system* dot "-Tpng" dot-file))) (delete-file dot-file)))) (define (lookup-asset assets label) (define value (for/fold ([a assets]) ([l (nested-labels label)]) (hash-ref a l))) (if (box? value) (unbox value) value)) (define (get-asset context label) (lookup-asset (hash-ref context 'compiled-assets) label)) (define (clean-declarations cdecls) (for/fold ([c cdecls]) ([key (hash-keys cdecls)] #:when (string-prefix? (symbol->string key) "compiled")) (hash-remove c key))) (define builtins (~> (document (hash) empty (hash) (hash)) (add-builtin-context "truth" empty builtins:truth-signature builtins:truth-rules) (add-builtin-context "integers" (list (cons '(use "truth") #f)) builtins:integer-signature builtins:merged-integer-rules) (add-builtin-context "rational-numbers" (list (cons '(use "truth") #f)) builtins:rational-signature builtins:merged-rational-rules) (add-builtin-context "real-numbers" (list (cons '(use "truth") #f)) builtins:real-number-signature builtins:merged-real-number-rules) (add-builtin-context "IEEE-floating-point" (list (cons '(use "integers") #f)) builtins:IEEE-float-signature builtins:merged-IEEE-float-rules))) (define empty-document (~> (document (hash) empty (hash) (hash)) (add-to-library "builtins" builtins #f))) (module+ test (define test-document1 (~> empty-document (add-context-from-source "test" (list (cons '(sort foo) #f) (cons '(sort bar) #f) (cons '(subsort foo bar) #f))))) (check-equal? (~> empty-document (add-context-from-source "test" (list (cons '(subsort foo bar) #f)))) test-document1) (check-equal? (~> empty-document (add-context-from-source "test" (list (cons '(sort foo) #f) (cons '(sort bar) #f) (cons '(subsort foo bar) #f) (cons '(sort bar) #f) (cons '(subsort foo bar) #f) (cons '(sort foo) #f)))) test-document1) (check-equal? (~> empty-document (add-context-from-source "test" (list (cons '(subsort foo bar) #f) (cons '(op a-foo () foo) #f))) (make-term "test" '(term-or-var a-foo) #f) (terms:term->string)) "foo:a-foo") (check-equal? (~> empty-document (add-context-from-source "test" (list (cons '(subsort foo bar) #f) (cons '(op a-foo () foo) #f) (cons '(op a-foo ((sort bar)) foo) #f) (cons '(op a-bar ((var X foo)) bar) #f) (cons '(rule (term a-foo ((term-or-var X))) (term-or-var a-foo) ((var X foo))) #f) (cons '(asset eq1 (equation (term-or-var a-foo) (term a-foo ((term-or-var a-foo))) ())) #f) (cons '(asset tr1 (transformation (term-or-var a-foo) (term a-foo ((term-or-var a-foo))) ())) #f) (cons '(asset nested.asset (term-or-var a-foo)) #f) (cons '(asset deeply.nested.asset (term-or-var a-foo)) #f))) (get-context "test") (clean-declarations)) (hash 'includes empty 'locs (hash) 'sorts (set 'foo 'bar) 'subsorts (set (cons 'foo 'bar)) 'ops (set '(a-foo () foo) '(a-foo ((sort bar)) foo) '(a-bar ((var X foo)) bar)) 'vars (hash 'X 'foo) 'rules (list (list 'rule (hash 'X 'foo) '(term a-foo ((term-or-var X))) '(term-or-var a-foo) #f)) 'assets (hash 'eq1 (list 'equation (hash) '(term-or-var a-foo) '(term a-foo ((term-or-var a-foo))) #f) 'tr1 (list 'transformation (hash) '(term-or-var a-foo) '(term a-foo ((term-or-var a-foo))) #f) 'nested (list 'assets (hash 'asset '(term-or-var a-foo))) 'deeply (list 'assets (hash 'nested (list 'assets (hash 'asset '(term-or-var a-foo)))))))) (let ([decls (list (cons '(sort foo) #f) (cons '(sort bar) #f) (cons '(var X foo) #f) (cons '(var X foo) #f) (cons '(var X bar) #f))]) (check-not-exn (thunk (~> empty-document (add-context-from-source "test" (take decls 4))))) (check-exn exn:fail? (thunk (~> empty-document (add-context-from-source "test" decls))))) (let ([decls (list (cons '(subsort foo bar) #f) (cons '(op a-foo () foo) #f) (cons '(op a-foo ((sort bar)) foo) #f) (cons '(op a-bar ((var X foo)) bar) #f) (cons '(asset eq1 (equation (term-or-var a-foo) (term a-foo ((term-or-var a-foo))) ())) #f) (cons '(asset eq1 (equation (term-or-var a-foo) (term a-foo ((term-or-var a-foo))) ())) #f) (cons '(asset eq1 (equation (term a-foo ((term-or-var a-foo))) (term-or-var a-foo) ())) #f))]) (check-not-exn (thunk (~> empty-document (add-context-from-source "test" (take decls 5))))) (check-not-exn (thunk (~> empty-document (add-context-from-source "test" (take decls 6))))) (check-exn exn:fail? (thunk (~> empty-document (add-context-from-source "test" decls))))) ( list ( cons ' ( subsort A B ) # f ) ( cons ' ( subsort A C ) # f ) (define test-document2 (~> empty-document (add-context-from-source "test" (list (cons '(use "builtins/integers") #f) (cons '(subsort foo bar) #f) (cons '(op a-foo () foo) #f) (cons '(op a-foo ((var X foo)) foo) #f) (cons '(rule (term a-foo ((term-or-var X))) (term-or-var a-foo) ((var X foo))) #f) (cons '(asset a-term (term-or-var a-foo)) #f) (cons '(asset a-rule (rule (term a-foo ((term-or-var X))) (term-or-var a-foo) ((var X foo)))) #f) (cons '(asset eq1 (equation (term a-foo ((term-or-var X))) (term-or-var a-foo) ((var X foo)))) #f) (cons '(asset eq2 (equation (integer 2) (integer 3) ())) #f) (cons '(asset tr (transformation (term-or-var X) (term a-foo ((term-or-var X))) ((var X foo)))) #f) (cons '(asset more-assets (assets [int1 (integer 2)] [int2 (integer 3)])) #f) (cons '(asset equation-from-rule (as-equation a-rule)) #f) (cons '(asset rule-from-equation (as-rule eq1 #f)) #f) (cons '(asset substituted-term (substitute a-rule a-term #f)) #f) (cons '(asset transformed-term (transform tr a-term #t)) #f))))) (check-true (~> test-document2 (make-test "test" '(rule (term a-foo ((term-or-var a-foo))) (term-or-var a-foo) ()) #f) check if the last two ( out of three ) elements are equal rest list->set set-count (equal? 1))) (check-equal? (~> test-document2 get-document-sxml sxml->document (get-context "test") (hash-remove 'locs)) (~> (get-context test-document2 "test") (hash-remove 'locs))) (check-equal? (~> test-document2 (get-context "test") (get-asset 'more-assets.int1)) 2)) Tests for module " transformations.rkt " (module+ test (define a-document (~> empty-document (add-context-from-source "template" (list (cons '(subsort SQ Q) #f) (cons '(var a Q) #f) (cons '(var b SQ) #f) (cons '(op foo () SQ) #f) (cons '(op + ((sort SQ) (sort SQ)) SQ) #f) (cons '(op * ((sort SQ) (sort SQ)) Q) #f) (cons '(rule (term + ((term-or-var b) (term-or-var x))) (term-or-var b) ((var x SQ))) #f) (cons '(asset eq-asset (equation (term + ((term-or-var b) (term-or-var x))) (term-or-var b) ((var x SQ)))) #f) (cons '(asset term-asset (term-or-var foo)) #f) (cons '(asset rule-from-eq (as-rule eq-asset #f)) #f) (cons '(asset subst-term (substitute rule-from-eq term-asset #f)) #f))))) (check-equal? (~> a-document (add-context-from-source "test" (list (cons '(insert-use "template") #f))) (get-context "test")) (~> a-document (add-context-from-source "test" (list (cons '(subsort SQ Q) #f) (cons '(op foo () SQ) #f) (cons '(op + ((sort SQ) (sort SQ)) SQ) #f) (cons '(op * ((sort SQ) (sort SQ)) Q) #f) (cons '(rule (term + ((term-or-var b) (term-or-var x))) (term-or-var b) ((var a Q) (var b SQ) (var x SQ))) #f) (cons '(asset eq-asset (equation (term + ((term-or-var b) (term-or-var x))) (term-or-var b) ((var a Q) (var b SQ) (var x SQ)))) #f) (cons '(asset term-asset (term-or-var foo)) #f) (cons '(asset rule-from-eq (as-rule eq-asset #f)) #f) (cons '(asset subst-term (substitute rule-from-eq term-asset #f)) #f))) (get-context "test"))) (check-exn exn:fail? (thunk (~> a-document (add-context-from-source "with-var-term" (list (cons '(insert-extend "template") #f) (cons '(asset var-term-asset (term-or-var b)) #f))) (add-context-from-source "test" (list (cons '(insert-use "with-var-term") #f)))))) (check-equal? (~> a-document (add-context-from-source "test" (list (cons '(insert-extend "template" (rename-sort SQ M)) #f))) (get-context "test")) (~> a-document (add-context-from-source "test" (list (cons '(subsort M Q) #f) (cons '(var a Q) #f) (cons '(var b M) #f) (cons '(op foo () M) #f) (cons '(op + ((sort M) (sort M)) M) #f) (cons '(op * ((sort M) (sort M)) Q) #f) (cons '(rule (term + ((term-or-var b) (term-or-var x))) (term-or-var b) ((var x M))) #f) (cons '(asset eq-asset (equation (term + ((term-or-var b) (term-or-var x))) (term-or-var b) ((var x M)))) #f) (cons '(asset term-asset (term-or-var foo)) #f) (cons '(asset rule-from-eq (as-rule eq-asset #f)) #f) (cons '(asset subst-term (substitute rule-from-eq term-asset #f)) #f))) (get-context "test"))) (check-equal? (~> a-document (add-context-from-source "test" (list (cons '(insert-extend "template" (asset-prefix foo)) #f))) (get-context "test")) (~> a-document (add-context-from-source "test" (list (cons '(subsort SQ Q) #f) (cons '(var a Q) #f) (cons '(var b SQ) #f) (cons '(op foo () SQ) #f) (cons '(op + ((sort SQ) (sort SQ)) SQ) #f) (cons '(op * ((sort SQ) (sort SQ)) Q) #f) (cons '(rule (term + ((term-or-var b) (term-or-var x))) (term-or-var b) ((var x SQ))) #f) (cons '(asset foo.eq-asset (equation (term + ((term-or-var b) (term-or-var x))) (term-or-var b) ((var x SQ)))) #f) (cons '(asset foo.term-asset (term-or-var foo)) #f) (cons '(asset foo.rule-from-eq (as-rule foo.eq-asset #f)) #f) (cons '(asset foo.subst-term (substitute foo.rule-from-eq foo.term-asset #f)) #f))) (get-context "test"))) (define heron (~> empty-document (add-context-from-source "using-rational" (list (cons '(use "builtins/real-numbers") #f) (cons '(op heron ((var x ℝnn) (var ε ℝp) (var e ℝnn)) ℝnn) #f) (cons '(rule (term heron ((term-or-var x) (term-or-var ε) (term-or-var e))) (term-or-var e) ((term _< ((term abs ((term _- ((term-or-var x) (term ^ ((term-or-var e) (integer 2))))))) (term-or-var ε))))) #f) (cons '(rule (term heron ((term-or-var x) (term-or-var ε) (term-or-var e))) (term heron ((term-or-var x) (term-or-var ε) (term _× ((rational 1/2) (term _+ ((term-or-var e) (term _÷ ((term-or-var x) (term-or-var e))))))))) ()) #f) (cons '(asset rule-asset (rule (term heron ((term-or-var x) (term-or-var ε) (term-or-var e))) (term heron ((term-or-var x) (term-or-var ε) (term _× ((rational 1/2) (term _+ ((term-or-var e) (term _÷ ((term-or-var x) (term-or-var e))))))))) ())) #f) (cons '(asset eq-asset (equation (term heron ((term-or-var x) (term-or-var ε) (term-or-var e))) (term heron ((term-or-var x) (term-or-var ε) (term _× ((rational 1/2) (term _+ ((term-or-var e) (term _÷ ((term-or-var x) (term-or-var e))))))))) ())) #f) (cons '(asset term-asset (term _× ((rational 1/2) (term heron ((term-or-var x) (term-or-var ε) (term-or-var e)))))) #f))) (add-context-from-source "using-float" (list (cons '(use "builtins/real-numbers") #f) (cons '(use "builtins/IEEE-floating-point") #f) (cons '(op heron ((var x FP64) (var ε FP64) (var e FP64)) FP64) #f) (cons '(rule (term heron ((term-or-var x) (term-or-var ε) (term-or-var e))) (term-or-var e) ((term _< ((term abs ((term _- ((term-or-var x) (term ^ ((term-or-var e) (integer 2))))))) (term-or-var ε))))) #f) (cons '(rule (term heron ((term-or-var x) (term-or-var ε) (term-or-var e))) (term heron ((term-or-var x) (term-or-var ε) (term _× ((floating-point 0.5) (term _+ ((term-or-var e) (term _÷ ((term-or-var x) (term-or-var e))))))))) ()) #f) (cons '(asset rule-asset (rule (term heron ((term-or-var x) (term-or-var ε) (term-or-var e))) (term heron ((term-or-var x) (term-or-var ε) (term _× ((floating-point 0.5) (term _+ ((term-or-var e) (term _÷ ((term-or-var x) (term-or-var e))))))))) ())) #f) (cons '(asset eq-asset (equation (term heron ((term-or-var x) (term-or-var ε) (term-or-var e))) (term heron ((term-or-var x) (term-or-var ε) (term _× ((floating-point 0.5) (term _+ ((term-or-var e) (term _÷ ((term-or-var x) (term-or-var e))))))))) ())) #f) (cons '(asset term-asset (term _× ((floating-point 0.5) (term heron ((term-or-var x) (term-or-var ε) (term-or-var e)))))) #f))) (add-context-from-source "converted-to-float" (list (cons '(insert-extend "using-rational" (real->float FP64)) #f))) )) (check-equal? (~> heron (get-context "converted-to-float")) (~> heron (get-context "using-float"))) )
3912262438b35f09abd5f0d29f23a0416100ea1a7c557b6d5c571c6bfd36daa6
bobzhang/fan
id_set.ml
(** A common utility module when doing code generation *) include Set.Make( struct type t = Locf.t * string let compare (_,x) (_,y) = String.compare x y end )
null
https://raw.githubusercontent.com/bobzhang/fan/7ed527d96c5a006da43d3813f32ad8a5baa31b7f/src/common/id_set.ml
ocaml
* A common utility module when doing code generation
include Set.Make( struct type t = Locf.t * string let compare (_,x) (_,y) = String.compare x y end )
74f7610f6b9332eb8de7ffeca58fdc76ed220e6a8db41ddddcab01e594bc6f3d
jordanthayer/ocaml-search
tpl_main_reg.ml
$ I d : main.ml , v 1.1 2005/04/06 00:38:57 ruml Exp ruml $ main for stand - alone regression tplan executable main for stand-alone regression tplan executable *) let run_alg alg domain problem limit = let do_run = alg (domain,problem) limit in let (sol, e, g, p, q),t = Wrsys.with_time do_run in flush_all (); (match sol with None -> Verb.pr Verb.always "infinity\t-1\t%d\t%d\t%f\n" e g t; Datafile.write_pairs stdout ["found solution", "no"; "final sol cost", "infinity"] | Some (s, ms) -> Verb.force 2 (lazy (Tpl_regression.print_plan stderr s.Tpl_regression.s)); Datafile.write_pairs stdout ["found solution", "yes"; "final sol cost", string_of_float ms]); let trail_pairs = ["total raw cpu time", string_of_float t; "total nodes expanded", string_of_int e; "total nodes generated", string_of_int g; "total nodes pruned", string_of_int p; "max search queue", string_of_int q; "time per node", string_of_float (t /. (float) g)] @ (Limit.to_trailpairs limit) in Datafile.write_pairs stdout trail_pairs let read ch = let buf = Lexing.from_channel ch in let domain = Wrlexing.parse_verb 5 stderr "planning domain" (Parse_pddl.domain Lex.lexer) buf in let problem = Wrlexing.parse_verb 5 stderr "problem instance" (Parse_pddl.problem Lex.lexer) buf in let problem = Tpl_domain.correct_problem domain problem in domain, problem let run_alg_ch alg limit ch = let domain, problem = read ch in run_alg alg domain problem limit let get_alg name = let sh = (fun id -> id) and ib = Tpl_regression.default_interface and arg_count, alg_call = Wrlist.get_entry Alg_table_nodups.table "alg" name in arg_count, (Alg_initializers.string_array_init alg_call sh ib) let set_up_alg args = (** looks at command line. returns alg_func (which is world -> node option * int * int) and list of string pairs for logging parameters. *) let n = Array.length args in if n < 1 then (Wrutils.pr "expects a problem on stdin, writes log info to stdout.\n"; Wrutils.pr "First arg must be an algorithm name (such as \"a_star\"),\n"; Wrutils.pr "other args depend on alg (eg, weight for wted_a_star).\n"; failwith "not enough command line arguments"); let alg_name = args.(0) in let count, initer = get_alg alg_name in if n <> count then failwith (Wrutils.str "%s takes %d arguments after alg name (got %d)" alg_name count (n - 1)); initer args let parse_non_alg_args () = let v = ref 3 and limit = ref [Limit.Never] and others = ref [] in Arg.parse [ "-v", Arg.Set_int v, "verbosity setting (between 1=nothing and 5=everything, default 3)"; "--wall", Arg.Float (fun l -> limit := (Limit.WallTime l)::!limit), "wall time limit (in seconds, default no limit)"; "--time", Arg.Float (fun l -> limit := (Limit.Time l)::!limit), "search time limit (in seconds, default no limit)"; "--gen", Arg.Int (fun l -> limit := (Limit.Generated l)::!limit), "search generation limit"; "--exp", Arg.Int (fun l -> limit := (Limit.Expanded l)::!limit), "search expansion limit";] (fun s -> Wrutils.push s others) ""; !v, !limit, Array.of_list (List.rev !others) let main () = * alg from command line , instance from stdin , results to stdout let v, limit, args = parse_non_alg_args () in let a = set_up_alg args in Verb.with_level v (fun () -> run_alg_ch a limit stdin) let _ = main () EOF
null
https://raw.githubusercontent.com/jordanthayer/ocaml-search/57cfc85417aa97ee5d8fbcdb84c333aae148175f/tplan/tpl_main_reg.ml
ocaml
* looks at command line. returns alg_func (which is world -> node option * int * int) and list of string pairs for logging parameters.
$ I d : main.ml , v 1.1 2005/04/06 00:38:57 ruml Exp ruml $ main for stand - alone regression tplan executable main for stand-alone regression tplan executable *) let run_alg alg domain problem limit = let do_run = alg (domain,problem) limit in let (sol, e, g, p, q),t = Wrsys.with_time do_run in flush_all (); (match sol with None -> Verb.pr Verb.always "infinity\t-1\t%d\t%d\t%f\n" e g t; Datafile.write_pairs stdout ["found solution", "no"; "final sol cost", "infinity"] | Some (s, ms) -> Verb.force 2 (lazy (Tpl_regression.print_plan stderr s.Tpl_regression.s)); Datafile.write_pairs stdout ["found solution", "yes"; "final sol cost", string_of_float ms]); let trail_pairs = ["total raw cpu time", string_of_float t; "total nodes expanded", string_of_int e; "total nodes generated", string_of_int g; "total nodes pruned", string_of_int p; "max search queue", string_of_int q; "time per node", string_of_float (t /. (float) g)] @ (Limit.to_trailpairs limit) in Datafile.write_pairs stdout trail_pairs let read ch = let buf = Lexing.from_channel ch in let domain = Wrlexing.parse_verb 5 stderr "planning domain" (Parse_pddl.domain Lex.lexer) buf in let problem = Wrlexing.parse_verb 5 stderr "problem instance" (Parse_pddl.problem Lex.lexer) buf in let problem = Tpl_domain.correct_problem domain problem in domain, problem let run_alg_ch alg limit ch = let domain, problem = read ch in run_alg alg domain problem limit let get_alg name = let sh = (fun id -> id) and ib = Tpl_regression.default_interface and arg_count, alg_call = Wrlist.get_entry Alg_table_nodups.table "alg" name in arg_count, (Alg_initializers.string_array_init alg_call sh ib) let set_up_alg args = let n = Array.length args in if n < 1 then (Wrutils.pr "expects a problem on stdin, writes log info to stdout.\n"; Wrutils.pr "First arg must be an algorithm name (such as \"a_star\"),\n"; Wrutils.pr "other args depend on alg (eg, weight for wted_a_star).\n"; failwith "not enough command line arguments"); let alg_name = args.(0) in let count, initer = get_alg alg_name in if n <> count then failwith (Wrutils.str "%s takes %d arguments after alg name (got %d)" alg_name count (n - 1)); initer args let parse_non_alg_args () = let v = ref 3 and limit = ref [Limit.Never] and others = ref [] in Arg.parse [ "-v", Arg.Set_int v, "verbosity setting (between 1=nothing and 5=everything, default 3)"; "--wall", Arg.Float (fun l -> limit := (Limit.WallTime l)::!limit), "wall time limit (in seconds, default no limit)"; "--time", Arg.Float (fun l -> limit := (Limit.Time l)::!limit), "search time limit (in seconds, default no limit)"; "--gen", Arg.Int (fun l -> limit := (Limit.Generated l)::!limit), "search generation limit"; "--exp", Arg.Int (fun l -> limit := (Limit.Expanded l)::!limit), "search expansion limit";] (fun s -> Wrutils.push s others) ""; !v, !limit, Array.of_list (List.rev !others) let main () = * alg from command line , instance from stdin , results to stdout let v, limit, args = parse_non_alg_args () in let a = set_up_alg args in Verb.with_level v (fun () -> run_alg_ch a limit stdin) let _ = main () EOF
c7fce42ba023089cff984ec9989d962f477484866c34507bcfeeb11b969bda92
ghcjs/ghcjs
objInfo.hs
# LANGUAGE OverloadedStrings , LambdaCase # Print the size of each section in a GHCJS object file optionally dump the sections Print the size of each section in a GHCJS object file optionally dump the sections -} module Main where import Control.Applicative import Control.Monad (when) import Data.Binary import Data.Binary.Get import qualified Data.ByteString.Lazy as BL import Data.Int import System.Environment main = do getArgs >>= \case ["-d", x] -> getObjInfo False x [x] -> getObjInfo True x _ -> error "usage: objInfo [-d] objfile\n -d : dump the sections to files" hdrLen :: Int64 hdrLen = 32 getObjInfo dump file = do b <- BL.readFile file let ~(header, symbsLen, depsLen, idxLen) = runGet getHeader b if BL.length b < hdrLen || header /= "GHCJSOBJ" then putStrLn "not a GHCJS object" else do putStrLn ("GHCJS object `" ++ file ++ "' section sizes in bytes:") putStrLn ("header: " ++ show hdrLen) putStrLn ("symbols: " ++ show symbsLen) putStrLn ("deps: " ++ show depsLen) putStrLn ("index: " ++ show idxLen) putStrLn ("units: " ++ show (BL.length b - 32 - symbsLen - depsLen - idxLen)) putStrLn "" putStrLn ("total: " ++ show (BL.length b)) when dump $ do BL.writeFile (file ++ ".symbols") (BL.take symbsLen $ BL.drop hdrLen b) BL.writeFile (file ++ ".deps") (BL.take depsLen $ BL.drop (hdrLen + symbsLen) b) BL.writeFile (file ++ ".index") (BL.take idxLen $ BL.drop (hdrLen + symbsLen + depsLen) b) BL.writeFile (file ++ ".units") ( BL.drop (hdrLen + symbsLen + depsLen + idxLen) b) getHeader :: Get (BL.ByteString, Int64, Int64, Int64) getHeader = (,,,) <$> getLazyByteString 8 <*> gi <*> gi <*> gi where gi = fmap fromIntegral getWord64le
null
https://raw.githubusercontent.com/ghcjs/ghcjs/e4cd4232a31f6371c761acd93853702f4c7ca74c/utils/objInfo.hs
haskell
# LANGUAGE OverloadedStrings , LambdaCase # Print the size of each section in a GHCJS object file optionally dump the sections Print the size of each section in a GHCJS object file optionally dump the sections -} module Main where import Control.Applicative import Control.Monad (when) import Data.Binary import Data.Binary.Get import qualified Data.ByteString.Lazy as BL import Data.Int import System.Environment main = do getArgs >>= \case ["-d", x] -> getObjInfo False x [x] -> getObjInfo True x _ -> error "usage: objInfo [-d] objfile\n -d : dump the sections to files" hdrLen :: Int64 hdrLen = 32 getObjInfo dump file = do b <- BL.readFile file let ~(header, symbsLen, depsLen, idxLen) = runGet getHeader b if BL.length b < hdrLen || header /= "GHCJSOBJ" then putStrLn "not a GHCJS object" else do putStrLn ("GHCJS object `" ++ file ++ "' section sizes in bytes:") putStrLn ("header: " ++ show hdrLen) putStrLn ("symbols: " ++ show symbsLen) putStrLn ("deps: " ++ show depsLen) putStrLn ("index: " ++ show idxLen) putStrLn ("units: " ++ show (BL.length b - 32 - symbsLen - depsLen - idxLen)) putStrLn "" putStrLn ("total: " ++ show (BL.length b)) when dump $ do BL.writeFile (file ++ ".symbols") (BL.take symbsLen $ BL.drop hdrLen b) BL.writeFile (file ++ ".deps") (BL.take depsLen $ BL.drop (hdrLen + symbsLen) b) BL.writeFile (file ++ ".index") (BL.take idxLen $ BL.drop (hdrLen + symbsLen + depsLen) b) BL.writeFile (file ++ ".units") ( BL.drop (hdrLen + symbsLen + depsLen + idxLen) b) getHeader :: Get (BL.ByteString, Int64, Int64, Int64) getHeader = (,,,) <$> getLazyByteString 8 <*> gi <*> gi <*> gi where gi = fmap fromIntegral getWord64le
4e30cef736aead0cac45a9de8fe32acecaace8f988969c70501bf47b8296968a
capsjac/opengles
Sync.hs
module Graphics.OpenGLES.Sync where import Control.Applicative import Control.Monad import Data.IORef import Foreign import Graphics.OpenGLES.Base import Graphics.OpenGLES.Internal data Sync = Sync Word64 (IORef GLsync) -- | Obtain new 'Sync' with or without timeout in nanoseconds. Fence sync objects are used to wait for partial completion of the GL -- command stream, as a more flexible form of glFinish. -- -- > -- Sync objects can be used many times > sync1 < - getSync ( Just 16000 ) > < - getSync Nothing -- -- For each frame: -- -- > glFence sync1 $ \isTimedOut -> do -- > {- modify buffers, textures, etc -} > glFence \isTimedOut - > do -- > {- modify buffers, textures, etc -} > getSync :: Maybe Word64 -> IO Sync getSync timeout_ns = Sync timeout <$> newIORef nullPtr where timeout = maybe timeoutIgnored id timeout_ns -- GL_TIMEOUT_IGNORED timeoutIgnored = 0xFFFFFFFFFFFFFFFF | Block and wait for GPU commands issued here complete . -- Better glFinish for /ES 3+/. -- Block and wait for a 'Sync' object to become signaled, then run specified block. glFence :: Sync -> (Bool -> GL a) -> GL a glFence sync io = do isExpired <- waitFence False sync result <- io isExpired createFence sync return result | Blocks on GPU until GL commands issued here complete . -- Better glFlush for /ES 3+/. Sync timeout is ignored. Instruct the GL server to block ( on the GPU ) until the previous call of glFence * with specified ' Sync ' object becomes finished on the GL server , -- then run specified block. glFenceInGpu :: Sync -> GL a -> GL a glFenceInGpu sync io = do waitFenceAtGpu sync result <- io createFence sync return result waitFence :: Bool -> Sync -> GL Bool waitFence flushCmdQ (Sync timeout ref) = do sync <- readIORef ref if sync /= nullPtr then do result <- glClientWaitSync sync flushBit timeout glDeleteSync sync writeIORef ref nullPtr return $ case result of -- GL_ALREADY_SIGNALED 0x911A -> False -- error "glFence: AlreadySignaled" -- GL_CONDITION_SATISFIED 0x911C -> False -- GL_TIMEOUT_EXPIRED 0x911B -> True -- GL_WAIT_FAILED 0x911D -> error "glFence: WaitFailed" -- GL_INVALID_VALUE _ {-0x0501-} -> error "glFence: InvalidValue" else return False where GL_SYNC_FLUSH_COMMANDS_BIT flushBit = if flushCmdQ then 1 else 0 createFence :: Sync -> GL () createFence (Sync _ ref) = do GL_SYNC_GPU_COMMANDS_COMPLETE sync <- glFenceSync 0x9117 0 writeIORef ref sync waitFenceAtGpu :: Sync -> GL () waitFenceAtGpu (Sync _ ref) = do sync <- readIORef ref when (sync /= nullPtr) $ do result <- glWaitSync sync 0 0xFFFFFFFFFFFFFFFF glDeleteSync sync writeIORef ref nullPtr -- | Same as glFlush. This operation is expensive, so frequent use should be avoided as far as possible. glFlushCommandQ :: GL () glFlushCommandQ = glFlush -- | Same as glFinish. This operation is expensive, so frequent use should be avoided as far as possible. glWaitComplete :: GL () glWaitComplete = glFinish
null
https://raw.githubusercontent.com/capsjac/opengles/23b78e5d1b058349a778a49310d867164ea1a529/src/Graphics/OpenGLES/Sync.hs
haskell
| Obtain new 'Sync' with or without timeout in nanoseconds. command stream, as a more flexible form of glFinish. > -- Sync objects can be used many times For each frame: > glFence sync1 $ \isTimedOut -> do > {- modify buffers, textures, etc -} > {- modify buffers, textures, etc -} GL_TIMEOUT_IGNORED Better glFinish for /ES 3+/. Block and wait for a 'Sync' object to become signaled, then run specified block. Better glFlush for /ES 3+/. Sync timeout is ignored. then run specified block. GL_ALREADY_SIGNALED error "glFence: AlreadySignaled" GL_CONDITION_SATISFIED GL_TIMEOUT_EXPIRED GL_WAIT_FAILED GL_INVALID_VALUE 0x0501 | Same as glFlush. This operation is expensive, so frequent use should be avoided as far as possible. | Same as glFinish. This operation is expensive, so frequent use should be avoided as far as possible.
module Graphics.OpenGLES.Sync where import Control.Applicative import Control.Monad import Data.IORef import Foreign import Graphics.OpenGLES.Base import Graphics.OpenGLES.Internal data Sync = Sync Word64 (IORef GLsync) Fence sync objects are used to wait for partial completion of the GL > sync1 < - getSync ( Just 16000 ) > < - getSync Nothing > glFence \isTimedOut - > do > getSync :: Maybe Word64 -> IO Sync getSync timeout_ns = Sync timeout <$> newIORef nullPtr where timeout = maybe timeoutIgnored id timeout_ns timeoutIgnored = 0xFFFFFFFFFFFFFFFF | Block and wait for GPU commands issued here complete . glFence :: Sync -> (Bool -> GL a) -> GL a glFence sync io = do isExpired <- waitFence False sync result <- io isExpired createFence sync return result | Blocks on GPU until GL commands issued here complete . Instruct the GL server to block ( on the GPU ) until the previous call of glFence * with specified ' Sync ' object becomes finished on the GL server , glFenceInGpu :: Sync -> GL a -> GL a glFenceInGpu sync io = do waitFenceAtGpu sync result <- io createFence sync return result waitFence :: Bool -> Sync -> GL Bool waitFence flushCmdQ (Sync timeout ref) = do sync <- readIORef ref if sync /= nullPtr then do result <- glClientWaitSync sync flushBit timeout glDeleteSync sync writeIORef ref nullPtr return $ case result of 0x911C -> False 0x911B -> True 0x911D -> error "glFence: WaitFailed" else return False where GL_SYNC_FLUSH_COMMANDS_BIT flushBit = if flushCmdQ then 1 else 0 createFence :: Sync -> GL () createFence (Sync _ ref) = do GL_SYNC_GPU_COMMANDS_COMPLETE sync <- glFenceSync 0x9117 0 writeIORef ref sync waitFenceAtGpu :: Sync -> GL () waitFenceAtGpu (Sync _ ref) = do sync <- readIORef ref when (sync /= nullPtr) $ do result <- glWaitSync sync 0 0xFFFFFFFFFFFFFFFF glDeleteSync sync writeIORef ref nullPtr glFlushCommandQ :: GL () glFlushCommandQ = glFlush glWaitComplete :: GL () glWaitComplete = glFinish
eb15dde3d2112619e193146e17dd07a8ec501c558d0ee4e645ce97ab6c3db5f7
kupl/LearnML
patch.ml
type aexp = | Const of int | Var of string | Power of (string * int) | Times of aexp list | Sum of aexp list let rec map (f : 'c * 'b -> 'a) ((l : 'c list), (var : string)) : 'a list = match l with [] -> [] | hd :: tl -> f (hd, var) :: map f (tl, var) let rec diff ((exp : aexp), (var : string)) : aexp = match exp with | Const n -> Const 0 | Var a -> if var = a then Const 1 else Const 0 | Power (a, n) -> if var = a then match n with | 0 -> Const 0 | 1 -> Const 1 | 2 -> Times [ Const 2; Var a ] | _ -> Times [ Const n; Power (a, n - 1) ] else Const 0 | Sum l -> Sum (map diff (l, var)) | Times l -> ( match l with | [] -> Const 0 | hd :: tl -> Sum [ Times (diff (hd, var) :: tl); Times [ hd; diff (Times tl, var) ] ] )
null
https://raw.githubusercontent.com/kupl/LearnML/c98ef2b95ef67e657b8158a2c504330e9cfb7700/result/cafe2/diff/sub102/patch.ml
ocaml
type aexp = | Const of int | Var of string | Power of (string * int) | Times of aexp list | Sum of aexp list let rec map (f : 'c * 'b -> 'a) ((l : 'c list), (var : string)) : 'a list = match l with [] -> [] | hd :: tl -> f (hd, var) :: map f (tl, var) let rec diff ((exp : aexp), (var : string)) : aexp = match exp with | Const n -> Const 0 | Var a -> if var = a then Const 1 else Const 0 | Power (a, n) -> if var = a then match n with | 0 -> Const 0 | 1 -> Const 1 | 2 -> Times [ Const 2; Var a ] | _ -> Times [ Const n; Power (a, n - 1) ] else Const 0 | Sum l -> Sum (map diff (l, var)) | Times l -> ( match l with | [] -> Const 0 | hd :: tl -> Sum [ Times (diff (hd, var) :: tl); Times [ hd; diff (Times tl, var) ] ] )
e3905b7fc9b93bbf0cd55014258d3af2e46a3a59eb241eff0898bd6807386194
input-output-hk/ouroboros-network
Index.hs
{-# LANGUAGE DataKinds #-} # LANGUAGE DerivingVia # {-# LANGUAGE RankNTypes #-} # LANGUAGE ScopedTypeVariables # # LANGUAGE TypeApplications # module Ouroboros.Consensus.Storage.ImmutableDB.Impl.Index ( -- * Index Index (..) , readEntry , readOffset -- * File-backed index , fileBackedIndex -- * Cached index , CacheConfig (..) , cachedIndex ) where import Control.Tracer (Tracer) import Data.Functor.Identity (Identity (..)) import Data.Proxy (Proxy (..)) import Data.Typeable (Typeable) import Data.Word (Word64) import GHC.Stack (HasCallStack) import NoThunks.Class (OnlyCheckWhnfNamed (..)) import Ouroboros.Consensus.Block (ConvertRawHash, IsEBB, StandardHash) import Ouroboros.Consensus.Util.IOLike import Ouroboros.Consensus.Util.ResourceRegistry import Ouroboros.Consensus.Storage.FS.API (HasFS) import Ouroboros.Consensus.Storage.FS.API.Types (AllowExisting, Handle) import Ouroboros.Consensus.Storage.ImmutableDB.Chunks import Ouroboros.Consensus.Storage.ImmutableDB.Impl.Index.Cache (CacheConfig (..)) import qualified Ouroboros.Consensus.Storage.ImmutableDB.Impl.Index.Cache as Cache import Ouroboros.Consensus.Storage.ImmutableDB.Impl.Index.Primary (SecondaryOffset) import qualified Ouroboros.Consensus.Storage.ImmutableDB.Impl.Index.Primary as Primary import Ouroboros.Consensus.Storage.ImmutableDB.Impl.Index.Secondary (BlockSize) import qualified Ouroboros.Consensus.Storage.ImmutableDB.Impl.Index.Secondary as Secondary import Ouroboros.Consensus.Storage.ImmutableDB.Impl.Types (TraceCacheEvent, WithBlockSize (..)) {------------------------------------------------------------------------------ Index ------------------------------------------------------------------------------} -- | Bundle the operations on the primary and secondary index that touch the -- files. This allows us to easily introduce an intermediary caching layer. data Index m blk h = Index { -- | See 'Primary.readOffsets' readOffsets :: forall t. (HasCallStack, Traversable t) => ChunkNo -> t RelativeSlot -> m (t (Maybe SecondaryOffset)) -- | See 'Primary.readFirstFilledSlot' , readFirstFilledSlot :: HasCallStack => ChunkNo -> m (Maybe RelativeSlot) -- | See 'Primary.open' , openPrimaryIndex :: HasCallStack => ChunkNo -> AllowExisting -> m (Handle h) -- | See 'Primary.appendOffsets' , appendOffsets :: forall f. (HasCallStack, Foldable f) => Handle h -> f SecondaryOffset -> m () -- | See 'Secondary.readEntries' , readEntries :: forall t. (HasCallStack, Traversable t) => ChunkNo -> t (IsEBB, SecondaryOffset) -> m (t (Secondary.Entry blk, BlockSize)) -- | See 'Secondary.readAllEntries' , readAllEntries :: HasCallStack => SecondaryOffset -> ChunkNo -> (Secondary.Entry blk -> Bool) -> Word64 -> IsEBB -> m [WithBlockSize (Secondary.Entry blk)] -- | See 'Secondary.appendEntry' , appendEntry :: HasCallStack => ChunkNo -> Handle h -> WithBlockSize (Secondary.Entry blk) -> m Word64 -- | Close the index and stop any background threads. -- -- Should be called when the ImmutableDB is closed. , close :: HasCallStack => m () -- | Restart a closed index using the given chunk as the current chunk, -- drop all previously cached information. -- -- NOTE: this will only used in the testsuite, when we need to truncate. , restart :: HasCallStack => ChunkNo -> m () } deriving NoThunks via OnlyCheckWhnfNamed "Index" (Index m blk h) -- | See 'Primary.readOffset'. readOffset :: Functor m => Index m blk h -> ChunkNo -> RelativeSlot -> m (Maybe SecondaryOffset) readOffset index chunk slot = runIdentity <$> readOffsets index chunk (Identity slot) -- | See 'Secondary.readEntry'. readEntry :: Functor m => Index m blk h -> ChunkNo -> IsEBB -> SecondaryOffset -> m (Secondary.Entry blk, BlockSize) readEntry index chunk isEBB slotOffset = runIdentity <$> readEntries index chunk (Identity (isEBB, slotOffset)) {------------------------------------------------------------------------------ File-backed index ------------------------------------------------------------------------------} fileBackedIndex :: forall m blk h. (ConvertRawHash blk, MonadCatch m, StandardHash blk, Typeable blk) => HasFS m h -> ChunkInfo -> Index m blk h fileBackedIndex hasFS chunkInfo = Index { readOffsets = Primary.readOffsets p hasFS , readFirstFilledSlot = Primary.readFirstFilledSlot p hasFS chunkInfo , openPrimaryIndex = Primary.open hasFS , appendOffsets = Primary.appendOffsets hasFS , readEntries = Secondary.readEntries hasFS , readAllEntries = Secondary.readAllEntries hasFS , appendEntry = \_chunk h (WithBlockSize _ entry) -> Secondary.appendEntry hasFS h entry -- Nothing to do , close = return () , restart = \_newCurChunk -> return () } where p :: Proxy blk p = Proxy {------------------------------------------------------------------------------ Cached index ------------------------------------------------------------------------------} -- | Caches the current chunk's indices as well as a number of past chunk's -- indices. -- -- Spawns a background thread to expire past chunks from the cache that -- haven't been used for a while. cachedIndex :: forall m blk h. (IOLike m, ConvertRawHash blk, StandardHash blk, Typeable blk) => HasFS m h -> ResourceRegistry m -> Tracer m TraceCacheEvent -> CacheConfig -> ChunkInfo -> ChunkNo -- ^ Current chunk -> m (Index m blk h) cachedIndex hasFS registry tracer cacheConfig chunkInfo chunk = do cacheEnv <- Cache.newEnv hasFS registry tracer cacheConfig chunkInfo chunk return Index { readOffsets = Cache.readOffsets cacheEnv , readFirstFilledSlot = Cache.readFirstFilledSlot cacheEnv , openPrimaryIndex = Cache.openPrimaryIndex cacheEnv , appendOffsets = Cache.appendOffsets cacheEnv , readEntries = Cache.readEntries cacheEnv , readAllEntries = Cache.readAllEntries cacheEnv , appendEntry = Cache.appendEntry cacheEnv , close = Cache.close cacheEnv , restart = Cache.restart cacheEnv }
null
https://raw.githubusercontent.com/input-output-hk/ouroboros-network/c82309f403e99d916a76bb4d96d6812fb0a9db81/ouroboros-consensus/src/Ouroboros/Consensus/Storage/ImmutableDB/Impl/Index.hs
haskell
# LANGUAGE DataKinds # # LANGUAGE RankNTypes # * Index * File-backed index * Cached index ----------------------------------------------------------------------------- Index ----------------------------------------------------------------------------- | Bundle the operations on the primary and secondary index that touch the files. This allows us to easily introduce an intermediary caching layer. | See 'Primary.readOffsets' | See 'Primary.readFirstFilledSlot' | See 'Primary.open' | See 'Primary.appendOffsets' | See 'Secondary.readEntries' | See 'Secondary.readAllEntries' | See 'Secondary.appendEntry' | Close the index and stop any background threads. Should be called when the ImmutableDB is closed. | Restart a closed index using the given chunk as the current chunk, drop all previously cached information. NOTE: this will only used in the testsuite, when we need to truncate. | See 'Primary.readOffset'. | See 'Secondary.readEntry'. ----------------------------------------------------------------------------- File-backed index ----------------------------------------------------------------------------- Nothing to do ----------------------------------------------------------------------------- Cached index ----------------------------------------------------------------------------- | Caches the current chunk's indices as well as a number of past chunk's indices. Spawns a background thread to expire past chunks from the cache that haven't been used for a while. ^ Current chunk
# LANGUAGE DerivingVia # # LANGUAGE ScopedTypeVariables # # LANGUAGE TypeApplications # module Ouroboros.Consensus.Storage.ImmutableDB.Impl.Index ( Index (..) , readEntry , readOffset , fileBackedIndex , CacheConfig (..) , cachedIndex ) where import Control.Tracer (Tracer) import Data.Functor.Identity (Identity (..)) import Data.Proxy (Proxy (..)) import Data.Typeable (Typeable) import Data.Word (Word64) import GHC.Stack (HasCallStack) import NoThunks.Class (OnlyCheckWhnfNamed (..)) import Ouroboros.Consensus.Block (ConvertRawHash, IsEBB, StandardHash) import Ouroboros.Consensus.Util.IOLike import Ouroboros.Consensus.Util.ResourceRegistry import Ouroboros.Consensus.Storage.FS.API (HasFS) import Ouroboros.Consensus.Storage.FS.API.Types (AllowExisting, Handle) import Ouroboros.Consensus.Storage.ImmutableDB.Chunks import Ouroboros.Consensus.Storage.ImmutableDB.Impl.Index.Cache (CacheConfig (..)) import qualified Ouroboros.Consensus.Storage.ImmutableDB.Impl.Index.Cache as Cache import Ouroboros.Consensus.Storage.ImmutableDB.Impl.Index.Primary (SecondaryOffset) import qualified Ouroboros.Consensus.Storage.ImmutableDB.Impl.Index.Primary as Primary import Ouroboros.Consensus.Storage.ImmutableDB.Impl.Index.Secondary (BlockSize) import qualified Ouroboros.Consensus.Storage.ImmutableDB.Impl.Index.Secondary as Secondary import Ouroboros.Consensus.Storage.ImmutableDB.Impl.Types (TraceCacheEvent, WithBlockSize (..)) data Index m blk h = Index readOffsets :: forall t. (HasCallStack, Traversable t) => ChunkNo -> t RelativeSlot -> m (t (Maybe SecondaryOffset)) , readFirstFilledSlot :: HasCallStack => ChunkNo -> m (Maybe RelativeSlot) , openPrimaryIndex :: HasCallStack => ChunkNo -> AllowExisting -> m (Handle h) , appendOffsets :: forall f. (HasCallStack, Foldable f) => Handle h -> f SecondaryOffset -> m () , readEntries :: forall t. (HasCallStack, Traversable t) => ChunkNo -> t (IsEBB, SecondaryOffset) -> m (t (Secondary.Entry blk, BlockSize)) , readAllEntries :: HasCallStack => SecondaryOffset -> ChunkNo -> (Secondary.Entry blk -> Bool) -> Word64 -> IsEBB -> m [WithBlockSize (Secondary.Entry blk)] , appendEntry :: HasCallStack => ChunkNo -> Handle h -> WithBlockSize (Secondary.Entry blk) -> m Word64 , close :: HasCallStack => m () , restart :: HasCallStack => ChunkNo -> m () } deriving NoThunks via OnlyCheckWhnfNamed "Index" (Index m blk h) readOffset :: Functor m => Index m blk h -> ChunkNo -> RelativeSlot -> m (Maybe SecondaryOffset) readOffset index chunk slot = runIdentity <$> readOffsets index chunk (Identity slot) readEntry :: Functor m => Index m blk h -> ChunkNo -> IsEBB -> SecondaryOffset -> m (Secondary.Entry blk, BlockSize) readEntry index chunk isEBB slotOffset = runIdentity <$> readEntries index chunk (Identity (isEBB, slotOffset)) fileBackedIndex :: forall m blk h. (ConvertRawHash blk, MonadCatch m, StandardHash blk, Typeable blk) => HasFS m h -> ChunkInfo -> Index m blk h fileBackedIndex hasFS chunkInfo = Index { readOffsets = Primary.readOffsets p hasFS , readFirstFilledSlot = Primary.readFirstFilledSlot p hasFS chunkInfo , openPrimaryIndex = Primary.open hasFS , appendOffsets = Primary.appendOffsets hasFS , readEntries = Secondary.readEntries hasFS , readAllEntries = Secondary.readAllEntries hasFS , appendEntry = \_chunk h (WithBlockSize _ entry) -> Secondary.appendEntry hasFS h entry , close = return () , restart = \_newCurChunk -> return () } where p :: Proxy blk p = Proxy cachedIndex :: forall m blk h. (IOLike m, ConvertRawHash blk, StandardHash blk, Typeable blk) => HasFS m h -> ResourceRegistry m -> Tracer m TraceCacheEvent -> CacheConfig -> ChunkInfo -> m (Index m blk h) cachedIndex hasFS registry tracer cacheConfig chunkInfo chunk = do cacheEnv <- Cache.newEnv hasFS registry tracer cacheConfig chunkInfo chunk return Index { readOffsets = Cache.readOffsets cacheEnv , readFirstFilledSlot = Cache.readFirstFilledSlot cacheEnv , openPrimaryIndex = Cache.openPrimaryIndex cacheEnv , appendOffsets = Cache.appendOffsets cacheEnv , readEntries = Cache.readEntries cacheEnv , readAllEntries = Cache.readAllEntries cacheEnv , appendEntry = Cache.appendEntry cacheEnv , close = Cache.close cacheEnv , restart = Cache.restart cacheEnv }
09887fd6cb9914db6e9446478fbd0631eda1f49ce0335cd496a1c085cafe9722
HachiSecurity/plc-llvm
String.hs
module Hachi.Compiler.CodeGen.Constant.String ( globalStrs ) where ------------------------------------------------------------------------------- globalStrs :: [(String, String)] globalStrs = [ ("nlStr", "\n") , ("i64FormatStr", "%d") , ("strFormatStr", "%s") , ("hexFormatStr", "%02X") , ("trueStr", "True") , ("falseStr", "False") , ("unitStr", "()") , ("dataConstrStr", "Constr ") , ("dataMapStr", "Map ") , ("dataListStr", "List ") , ("dataIntegerStr", "I ") , ("dataByteStringStr", "B ") , ("forceErrStr", "Attempted to instantiate a non-polymorphic term.\n") , ("funErrStr", "Evaluation resulted in a function.") , ("dataMatchErrStr", "Unknown tag %d for Data value.\n") , ("headErrStr", "headList called on an empty list.\n") , ("tailErrStr", "tailList called on an empty list.\n") , ("unConstrDataErrStr", "Pattern-match failure in unConstrData\n") , ("unMapDataErrStr", "Pattern-match failure in unMapData\n") , ("unListDataErrStr", "Pattern-match failure in unListData\n") , ("unIDataErrStr", "Pattern-match failure in unIData\n") , ("unBDataErrStr", "Pattern-match failure in unBData\n") , ("bsIndexErrStr", "Trying to access element at index %zu of bytestring with length %zu!\n") , ("oomErrStr", "Out of memory.\n") , ("spaceStr", " ") , ("openParenStr", "(") , ("closeParenStr", ")") , ("commaStr", ",") , ("consStr", ":") , ("emptyListStr", "[]") ] -------------------------------------------------------------------------------
null
https://raw.githubusercontent.com/HachiSecurity/plc-llvm/c99c8d58ec7cbbb8942604338cfde00ad23e7f13/compiler/src/Hachi/Compiler/CodeGen/Constant/String.hs
haskell
----------------------------------------------------------------------------- -----------------------------------------------------------------------------
module Hachi.Compiler.CodeGen.Constant.String ( globalStrs ) where globalStrs :: [(String, String)] globalStrs = [ ("nlStr", "\n") , ("i64FormatStr", "%d") , ("strFormatStr", "%s") , ("hexFormatStr", "%02X") , ("trueStr", "True") , ("falseStr", "False") , ("unitStr", "()") , ("dataConstrStr", "Constr ") , ("dataMapStr", "Map ") , ("dataListStr", "List ") , ("dataIntegerStr", "I ") , ("dataByteStringStr", "B ") , ("forceErrStr", "Attempted to instantiate a non-polymorphic term.\n") , ("funErrStr", "Evaluation resulted in a function.") , ("dataMatchErrStr", "Unknown tag %d for Data value.\n") , ("headErrStr", "headList called on an empty list.\n") , ("tailErrStr", "tailList called on an empty list.\n") , ("unConstrDataErrStr", "Pattern-match failure in unConstrData\n") , ("unMapDataErrStr", "Pattern-match failure in unMapData\n") , ("unListDataErrStr", "Pattern-match failure in unListData\n") , ("unIDataErrStr", "Pattern-match failure in unIData\n") , ("unBDataErrStr", "Pattern-match failure in unBData\n") , ("bsIndexErrStr", "Trying to access element at index %zu of bytestring with length %zu!\n") , ("oomErrStr", "Out of memory.\n") , ("spaceStr", " ") , ("openParenStr", "(") , ("closeParenStr", ")") , ("commaStr", ",") , ("consStr", ":") , ("emptyListStr", "[]") ]
269b09a73109e3859d8faa3bd7e11b97469f2f2110f38c4e92a4893684f2756c
thoughtstem/vr-engine
info.rkt
#lang info (define version "0.0.1") (define deps '("hostname" "simple-qr" "urlang" "-assets-from.git" "-coloring.git" "-GE-Katas.git?path=ts-kata-util" )) (define scribblings '(("scribblings/manual.scrbl" (multi-page))))
null
https://raw.githubusercontent.com/thoughtstem/vr-engine/18e290f7d61ddd2b32a2f12a8abb0c4a30ed3a08/info.rkt
racket
#lang info (define version "0.0.1") (define deps '("hostname" "simple-qr" "urlang" "-assets-from.git" "-coloring.git" "-GE-Katas.git?path=ts-kata-util" )) (define scribblings '(("scribblings/manual.scrbl" (multi-page))))
7af2f652506ef116b6f166846bf43dc24453580d36d660dfadfeefbb33c62265
kaoskorobase/mescaline
Params.hs
module Mescaline.Synth.Sampler.Params ( Params(..) , defaultParams ) where import Mescaline (Duration) import qualified Mescaline.Database as DB data Params = Params { file :: DB.SourceFile , unit :: DB.Unit , offset :: Duration , duration :: Duration , rate :: Double , pan :: Double , attackTime :: Double , releaseTime :: Double , sustainLevel :: Double , gateLevel :: Double , sendLevel1 :: Double , sendLevel2 :: Double , fxParam1 :: Double , fxParam2 :: Double } deriving (Eq, Show) defaultParams :: DB.SourceFile -> DB.Unit -> Params defaultParams f u = Params { file = f , unit = u , offset = 0 , duration = DB.unitDuration u , rate = 1 , pan = 0 , attackTime = 0 , releaseTime = 0 , sustainLevel = 1 , gateLevel = 0 , sendLevel1 = 0 , sendLevel2 = 0 , fxParam1 = 0 , fxParam2 = 0 }
null
https://raw.githubusercontent.com/kaoskorobase/mescaline/13554fc4826d0c977d0010c0b4fb74ba12ced6b9/lib/mescaline/Mescaline/Synth/Sampler/Params.hs
haskell
module Mescaline.Synth.Sampler.Params ( Params(..) , defaultParams ) where import Mescaline (Duration) import qualified Mescaline.Database as DB data Params = Params { file :: DB.SourceFile , unit :: DB.Unit , offset :: Duration , duration :: Duration , rate :: Double , pan :: Double , attackTime :: Double , releaseTime :: Double , sustainLevel :: Double , gateLevel :: Double , sendLevel1 :: Double , sendLevel2 :: Double , fxParam1 :: Double , fxParam2 :: Double } deriving (Eq, Show) defaultParams :: DB.SourceFile -> DB.Unit -> Params defaultParams f u = Params { file = f , unit = u , offset = 0 , duration = DB.unitDuration u , rate = 1 , pan = 0 , attackTime = 0 , releaseTime = 0 , sustainLevel = 1 , gateLevel = 0 , sendLevel1 = 0 , sendLevel2 = 0 , fxParam1 = 0 , fxParam2 = 0 }
fe95e85b27a0edfd40774685d39d8d73a6872452c2e918c7dc582a5fa2adbf0c
zotonic/zotonic
import_csv.erl
%% @doc Import a csv file according to the derived file/record definitions. @author < > @author < > Copyright 2010 - 2020 , %% 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(import_csv). -author("Arjan Scherpenisse <>"). -author("Marc Worrell <>"). -export([ import/3 ]). -include_lib("zotonic_core/include/zotonic.hrl"). -include("../../include/import_csv.hrl"). -record(importresult, {seen=[], new=[], updated=[], errors=[], ignored=[], deleted=0}). -record(importstate, {is_reset, name_to_id, managed_edges, to_flush=[], result, managed_resources}). -type importresult() :: {file, file:filename_all()} | {date_start, calendar:datetime()} | {date_end, calendar:datetime()} | {seen, list( {CategoryName :: binary(), non_neg_integer() })} | {new, list( {CategoryName :: binary(), non_neg_integer() })} | {updated, list( {CategoryName :: binary(), non_neg_integer() })} | {errors, list()} | {deleted, non_neg_integer()} | {ignored, list()}. -type importresults() :: list( importresult() ). -type rowresult() :: ignore | {error, term(), term()} | {new, Type::term(), Id::term(), Name::term()} | {equal, Type::term(), Id::term()} | {updated, Type::term(), Id::term()}. -type row() :: list( {binary(), term()} ). % -type id() :: insert_rsc | m_rsc:resource_id(). -export_type([ importresult/0, importresults/0 ]). %% @doc The import function, read the csv file and fetch all records. %% This function is run as a spawned process. The Context should have the right permissions for inserting %% or updating the resources. -spec import(#filedef{}, boolean(), z:context()) -> importresults(). import(Def, IsReset, Context) -> StartDate = erlang:universaltime(), %% Read and parse all rows {ok, Device} = file:open(Def#filedef.filename, [read, binary, {encoding, utf8}]), Rows = z_csv_parser:scan_lines(Device, Def#filedef.colsep), file:close(Device), file:delete(Def#filedef.filename), Drop ( optionally ) the first row , empty rows and the comment rows ( starting with a ' # ' ) Rows1 = case Def#filedef.skip_first_row of true -> tl(Rows); _ -> Rows end, State = import_rows(Rows1, 1, Def, new_importstate(IsReset), Context), %% Return the stats from this import run R = State#importstate.result, [ {file, filename:basename(Def#filedef.filename)}, {date_start, StartDate}, {date_end, erlang:universaltime()}, {seen, R#importresult.seen}, {new, R#importresult.new}, {updated, R#importresult.updated}, {errors, R#importresult.errors}, {deleted, 0}, {ignored, R#importresult.ignored} ]. new_importstate(IsReset) -> #importstate{ is_reset=IsReset, name_to_id=gb_trees:empty(), managed_edges=gb_trees:empty(), managed_resources=sets:new(), result=#importresult{} }. %%==================================================================== %% Import a record %%==================================================================== %% @doc Import all rows. -spec import_rows(list( row() ), non_neg_integer(), #filedef{}, #importstate{}, z:context()) -> #importstate{}. import_rows([], _RowNr, _Def, ImportState, _Context) -> ImportState; import_rows([[<<$#, _/binary>>|_]|Rows], RowNr, Def, ImportState, Context) -> import_rows(Rows, RowNr+1, Def, ImportState, Context); import_rows([[]|Rows], RowNr, Def, ImportState, Context) -> import_rows(Rows, RowNr+1, Def, ImportState, Context); import_rows([R|Rows], RowNr, Def, ImportState, Context) -> Zipped = zip(R, Def#filedef.columns, []), ImportState1 = import_parts(Zipped, RowNr, Def#filedef.importdef, ImportState, Context), import_rows(Rows, RowNr+1, Def, ImportState1, Context). %% @doc Combine the field name definitions and the field values. zip(_Cols, [], Acc) -> lists:reverse(Acc); zip([_C|Cs], [''|Ns], Acc) -> zip(Cs, Ns, Acc); zip([_C|Cs], [<<>>|Ns], Acc) -> zip(Cs, Ns, Acc); zip([_C|Cs], [undefined|Ns], Acc) -> zip(Cs, Ns, Acc); zip([], [N|Ns], Acc) -> zip([], Ns, [{N,<<>>}|Acc]); zip([C|Cs], [N|Ns], Acc) -> zip(Cs, Ns, [{N, C}|Acc]). %% @doc Import all resources on a row -spec import_parts( row(), non_neg_integer(), list( tuple() ), #importstate{}, z:context() ) -> #importstate{}. import_parts(_Row, _RowNr, [], ImportState, _Context) -> ImportState; import_parts(Row, RowNr, [Def | Definitions], ImportState, Context) -> {FieldMapping, ConnectionMapping} = Def, try case import_def_rsc(FieldMapping, Row, ImportState, Context) of {S, ignore} -> import_parts(Row, RowNr, Definitions, S, Context); {S, {error, Type, E}} -> add_result_seen(Type, add_result_error(Type, E, S)); {S, {new, Type, Id, Name}} -> State0 = add_managed_resource(Id, FieldMapping, S), State1 = add_name_lookup(State0, Name, Id), State2 = import_parts(Row, RowNr, Definitions, State1, Context), import_def_edges(Id, ConnectionMapping, Row, State2, Context), add_result_seen(Type, add_result_new(Type, State2)); {S, {equal, Type, Id}} -> State0 = add_managed_resource(Id, FieldMapping, S), State1 = import_parts(Row, RowNr, Definitions, State0, Context), import_def_edges(Id, ConnectionMapping, Row, State1, Context), add_result_seen(Type, add_result_ignored(Type, State1)); {S, {updated, Type, Id}} -> %% Equal State0 = add_managed_resource(Id, FieldMapping, S), State1 = import_parts(Row, RowNr, Definitions, State0, Context), add_result_seen(Type, import_def_edges(Id, ConnectionMapping, Row, State1, Context)), add_result_updated(Type, State1) end catch throw:{import_error, ImportError} -> ?LOG_ERROR(#{ text => <<"Error importing CSV row data">>, in => zotonic_mod_import_csv, result => error, reason => ImportError, row_nr => RowNr, row => Row, row_def => Def }), ImportState end. -spec import_def_rsc(list(), row(), #importstate{}, z:context()) -> {#importstate{}, rowresult()}. import_def_rsc(FieldMapping, Row, State, Context) -> {Callbacks, FieldMapping1} = case proplists:get_value(callbacks, FieldMapping) of undefined -> {[], FieldMapping}; CB -> {CB, proplists:delete(callbacks, FieldMapping)} end, RowMapped = map_fields(FieldMapping1, Row, State), import_def_rsc_1_cat(RowMapped, Callbacks, State, Context). -spec import_def_rsc_1_cat(row(), list(), #importstate{}, z:context()) -> {#importstate{}, rowresult()}. import_def_rsc_1_cat(Row, Callbacks, State, Context) -> %% Get category name; put category ID in the record. {<<"category">>, CategoryName} = proplists:lookup(<<"category">>, Row), {CatId, State1} = name_lookup_exists(CategoryName, State, Context), Row1 = [{<<"category_id">>, CatId} | proplists:delete(<<"category">>, Row)], Name = case proplists:get_value(<<"name">>, Row1) of undefined -> throw({import_error, {definition_without_unique_name}}); N -> N end, {OptRscId, State2} = name_lookup(Name, State1, Context), RscId = case OptRscId of undefined -> insert_rsc; _ -> OptRscId end, {ok, RowMap} = z_props:from_qs(Row1), NormalizedRowMap = z_sanitize:escape_props_check(RowMap, Context), = sort_props(m_rsc_update : normalize_props(RscId , Row1 , [ is_import ] , Context ) ) , case has_required_rsc_props(NormalizedRowMap) of true -> import_def_rsc_2_name(RscId, State2, Name, CategoryName, NormalizedRowMap, Callbacks, Context); false -> ?LOG_WARNING(#{ text => <<"import_csv: missing required attributes">>, in => zotonic_mod_import_csv, name => Name, result => error, reason => missing_attributes }), {State2, ignore} end. import_def_rsc_2_name(insert_rsc, State, Name, CategoryName, NormalizedRowMap, Callbacks, Context) -> ?LOG_DEBUG(#{ text => <<"import_csv: importing resource">>, in => zotonic_mod_import_csv, name => Name, category_name => CategoryName }), case rsc_insert(NormalizedRowMap, Context) of {ok, NewId} -> RawRscFinal = get_updated_props(NewId, NormalizedRowMap, Context), Checksum = checksum(NormalizedRowMap), m_import_csv_data:update(NewId, Checksum, NormalizedRowMap, RawRscFinal, Context), case proplists:get_value(rsc_insert, Callbacks) of undefined -> none; Callback -> Callback(NewId, NormalizedRowMap, Context) end, {flush_add(NewId, State), {new, CategoryName, NewId, Name}}; {error, Reason} = E -> ?LOG_WARNING(#{ text => <<"import_csv: could not insert resource">>, in => zotonic_mod_import_csv, name => Name, category_name => CategoryName, result => error, reason => Reason }), {State, {error, CategoryName, E}} end; import_def_rsc_2_name(Id, State, Name, CategoryName, NormalizedRowMap, Callbacks, Context) when is_integer(Id) -> 1 . Check if this update was the same as the last known import PrevImportData = m_import_csv_data:get(Id, Context), PrevChecksum = get_value(checksum, PrevImportData), case checksum(NormalizedRowMap) of PrevChecksum when not State#importstate.is_reset -> ?LOG_INFO(#{ text => <<"import_csv: skipping row (importing same values)">>, in => zotonic_mod_import_csv, name => Name, rsc_id => Id, category_name => CategoryName }), {State, {equal, CategoryName, Id}}; Checksum -> ?LOG_INFO(#{ text => <<"import_csv: updating resource">>, in => zotonic_mod_import_csv, name => Name, category_name => CategoryName, rsc_id => Id }), 2 . Some properties might have been overwritten by an editor . For this we will update a second time with all the changed values % (also pass any import-data from an older import module) RawRscPre = get_updated_props(Id, NormalizedRowMap, Context), Edited = diff_raw_props(RawRscPre, get_value(rsc_data, PrevImportData, []), m_rsc:p_no_acl(Id, import_csv_original, Context)), Cleanup old import_csv data on update Row1 = NormalizedRowMap#{ <<"import_csv_original">> => undefined, <<"import_csv_touched">> => undefined }, case rsc_update(Id, Row1, Context) of {ok, _} -> RawRscFinal = get_updated_props(Id, NormalizedRowMap, Context), % Ensure edited properties are set back to their edited values case maps:size(Edited) of 0 -> ok; _ when State#importstate.is_reset -> ok; _ -> {ok, _} = m_rsc_update:update(Id, Edited, [{is_import, true}], Context) end, m_import_csv_data:update(Id, Checksum, NormalizedRowMap, RawRscFinal, Context), case proplists:get_value(rsc_update, Callbacks) of undefined -> none; Callback -> Callback(Id, NormalizedRowMap, Context) end, {flush_add(Id, State), {updated, CategoryName, Id}}; {error, _} = E -> {State, {error, CategoryName, E}} end end. @doc Return all properties in PreviousImport that are different in Current diff_raw_props(Current, [], {props, OriginalProps}) when is_list(OriginalProps) -> % Old version of the csv import, do our best on the diff PreviousImport = z_props:from_props(OriginalProps), diff_raw_props(Current, PreviousImport, undefined); diff_raw_props(PreviousImport, PreviousImport, undefined) -> #{}; diff_raw_props(Current, PreviousImport, undefined) when is_list(PreviousImport) -> PreviousImportMap = z_props:from_props(PreviousImport), diff_raw_props(Current, PreviousImportMap, undefined); diff_raw_props(Current, PreviousImport, undefined) when is_map(PreviousImport) -> maps:fold( fun(K, V, Acc) -> case maps:find(K, Current) of {ok, V} -> Acc; {ok, _} -> Acc#{ K => V }; error -> Acc#{ K => V } end end, #{}, PreviousImport). @doc Get all prop values in the Raw resource data get_updated_props(Id, ImportedRow, Context) -> {ok, Raw} = m_rsc:get_raw(Id, Context), maps:fold( fun(K, _, Acc) -> Acc#{ K => maps:get(K, Raw, undefined) } end, #{}, ImportedRow). -spec rsc_insert( m_rsc:props_all(), z:context() ) -> {ok, m_rsc:resource_id()} | {error, term()}. rsc_insert(Props, Context) -> case check_medium(Props) of {url, Url, PropsMedia} -> m_media:insert_url(Url, PropsMedia, [{is_import, true}], Context); none -> m_rsc_update:insert(Props, [{is_import, true}], Context) end. -spec rsc_update( m_rsc:resource_id(), m_rsc:props_all(), z:context() ) -> {ok, m_rsc:resource_id()} | {error, term()}. rsc_update(Id, Props, Context) -> case check_medium(Props) of {url, Url, PropsMedia} -> m_media:replace_url(Url, Id, PropsMedia, [{is_import, true}], Context); none -> m_rsc_update:update(Id, Props, [{is_import, true}], Context) end. -spec check_medium( map() ) -> none | {url, binary(), map()}. check_medium(Props) -> case maps:get(<<"medium_url">>, Props, undefined) of undefined -> none; <<>> -> none; "" -> none; Url -> {url, Url, maps:remove(<<"medium_url">>, Props)} end. get_value(K, L) -> get_value(K, L, undefined). get_value(K, L, D) when is_list(L) -> proplists:get_value(K, L, D); get_value(_K, undefined, D) -> D. import_def_edges(Id, ConnectionMapping, Row, State, Context) -> %% @todo Use a mapfoldl here to return the new state with name lookups from the edges EdgeIds = lists:flatten([import_do_edge(Id, Row, Map, State, Context) || Map <- ConnectionMapping]), case lists:filter(fun(X) -> not(X == fail) end, EdgeIds) of [] -> State; NewEdgeIds -> managed_edge_add(Id, NewEdgeIds, State) end. import_do_edge(Id, Row, F, State, Context) when is_function(F) -> [ import_do_edge(Id, Row, E, State, Context) || E <- F(Id, Row, State, Context) ]; import_do_edge(Id, Row, {{PredCat, PredRowField}, ObjectDefinition}, State, Context) -> % Find the predicate case map_one_normalize(<<"name">>, PredCat, map_one(PredRowField, Row, State)) of <<>> -> fail; Name -> case name_lookup(Name, State, Context) of {undefined, _State1} -> ?LOG_WARNING(#{ text => <<"Import CSV: edge predicate does not exist">>, in => zotonic_mod_import_csv, result => error, reason => predicate, name => Name, subject_id => Id }), fail; {PredId, State1} -> import_do_edge(Id, Row, {PredId, ObjectDefinition}, State1, Context) end end; import_do_edge(Id, Row, {Predicate, {ObjectCat, ObjectRowField}}, State, Context) -> % Find the object Name = map_one_normalize(<<"name">>, ObjectCat, map_one(ObjectRowField, Row, State)), case Name of <<>> -> fail; Name -> case name_lookup(Name, State, Context) of %% Object doesn't exist {undefined, _State1} -> fail; %% Object exists {RscId, _State1} -> {ok, EdgeId} = m_edge:insert(Id, Predicate, RscId, Context), EdgeId end end; import_do_edge(Id, Row, {Predicate, {ObjectCat, ObjectRowField, ObjectProps}}, State, Context) -> Name = map_one_normalize(<<"name">>, ObjectCat, map_one(ObjectRowField, Row, State)), case Name of <<>> -> fail; Name -> case name_lookup(Name, State, Context) of %% Object doesn't exist, create it using the objectprops {undefined, _State1} -> ?LOG_DEBUG(#{ text => <<"Import CSV: creating object">>, in => zotonic_mod_import_csv, category => ObjectCat, name => Name, subject_id => Id }), case m_rsc:insert([{category, ObjectCat}, {name, Name} | ObjectProps], Context) of {ok, RscId} -> {ok, EdgeId} = m_edge:insert(Id, Predicate, RscId, Context), EdgeId; {error, _Reason} -> fail end; %% Object exists {RscId, _State1} -> {ok, EdgeId} = m_edge:insert(Id, Predicate, RscId, Context), EdgeId end end; import_do_edge(_, _, Def, _State, _Context) -> throw({import_error, {invalid_edge_definition, Def}}). %% Adds a resource Id to the list of managed resources, if the import definition allows it. add_managed_resource(Id, FieldMapping, State=#importstate{managed_resources=M}) -> case proplists:get_value(import_skip_delete, FieldMapping) of true -> State; _ -> State#importstate{managed_resources=sets:add_element(Id, M)} end. add_name_lookup(State=#importstate{name_to_id=Tree}, Name, Id) -> case gb_trees:lookup(Name, Tree) of {value, undefined} -> State#importstate{name_to_id=gb_trees:update(Name, Id, Tree)}; {value, _} -> State; none -> State#importstate{name_to_id=gb_trees:insert(Name, Id, Tree)} end. name_lookup(Name, #importstate{name_to_id=Tree} = State, Context) -> case gb_trees:lookup(Name, Tree) of {value, V} -> {V, State}; none -> V = m_rsc:rid(Name, Context), {V, add_name_lookup(State, Name, V)} end. name_lookup_exists(Name, State, Context) -> case name_lookup(Name, State, Context) of {undefined, _State1} -> throw({import_error, {unknown_resource_name, Name}}); {Id, State1} -> {Id, State1} end. %% @doc Maps fields from the given mapping into a new row, filtering out undefined values. map_fields(Mapping, Row, State) -> Defaults = [ {<<"is_protected">>, true}, {<<"is_published">>, true} ], Mapped = [ map_def(MapOne, Row, State) || MapOne <- Mapping ], Type = case proplists:get_value(<<"category">>, Mapped) of undefined -> throw({import_error, no_category_in_import_definition}); T -> T end, % Normalize and remove undefined values P = lists:filter(fun({_K,undefined}) -> false; (_) -> true end, [{K, map_one_normalize(K, Type, V)} || {K,V} <- Mapped]), add_defaults(Defaults, P). map_def({K,F}, Row, State) -> {K, map_one(F, Row, State)}; map_def(K, Row, State) when is_atom(K); is_list(K) -> map_def({K,K}, Row, State). -spec map_one_normalize( binary(), any(), any() | {name_prefix, binary() | string() | atom(), binary() | string() | atom()} ) -> any(). map_one_normalize(<<"name">>, _Type, <<>>) -> <<>>; map_one_normalize(<<"name">>, _Type, {name_prefix, Prefix, V}) -> CheckL = 80 - strlen(Prefix) - 1, Postfix = case strlen(V) of L when L > CheckL -> % If name is too long, make a unique thing out of it. base64:encode(checksum(V)); _ -> V end, Name = z_string:to_name( iolist_to_binary([Prefix, "_", Postfix]) ), z_convert:to_binary(Name); map_one_normalize(_, _Type, V) -> V. strlen(B) when is_binary(B) -> erlang:size(B); strlen(L) when is_list(L) -> erlang:length(L); strlen(A) when is_atom(A) -> erlang:length(atom_to_list(A)). map_one(F, _Row, _State) when is_binary(F) -> F; map_one(undefined, _Row, _State) -> undefined; map_one(true, _Row, _State) -> true; map_one(false, _Row, _State) -> false; map_one(F, Row, _State) when is_atom(F) -> concat_spaces(proplists:get_all_values(z_convert:to_list(F), Row)); map_one(F, Row, _State) when is_list(F) -> concat_spaces(proplists:get_all_values(F, Row)); map_one(F, Row, _State) when is_function(F) -> F(Row); map_one({prefer, Fields}, Row, State) -> map_one_prefer(Fields, Row, State); map_one({html_escape, Value}, Row, State) -> z_html:escape(map_one(Value, Row, State)); map_one({concat, Fields}, Row, State) -> map_one_concat(Fields, Row, State); map_one({surroundspace, Field}, Row, State) -> case z_string:trim(map_one(Field, Row, State)) of <<>> -> <<" ">>; Val -> <<32, Val/binary, 32>> end; map_one({name_prefix, Prefix, Rest}, Row, State) -> {name_prefix, Prefix, map_one(Rest, Row, State)}; map_one({datetime, F}, Row, State) -> z_convert:to_datetime(map_one(F, Row, State)); map_one({date, F}, Row, State) -> z_convert:to_date(map_one(F, Row, State)); map_one({time, F}, Row, State) -> z_convert:to_time(map_one(F, Row, State)); map_one({datetime, D, T}, Row, State) -> {map_one({date, D}, Row, State), map_one({time, T}, Row, State)}; map_one({if_then_else, Cond, If, Else}, Row, State) -> case prop_empty(map_one(Cond, Row, State)) of false -> map_one(If, Row, State); true -> map_one(Else, Row, State) end; map_one(F, _, _) -> throw({import_error, {invalid_import_definition, F}}). map_one_prefer([F], Row, State) -> map_one(F, Row, State); map_one_prefer([F|Rest], Row, State) -> Prop = map_one(F, Row, State), case prop_empty(Prop) of false -> Prop; true -> map_one_prefer(Rest, Row, State) end. map_one_concat(List, Row, State) -> concat([ map_one(F, Row, State) || F <- List]). multiple values , take into account that a value might be a tuple or atom concat([]) -> <<>>; concat([X]) when is_atom(X); is_tuple(X) -> X; concat(L) -> iolist_to_binary(L). concat_spaces([]) -> <<>>; concat_spaces([X]) when is_atom(X); is_tuple(X) -> X; concat_spaces([H|L]) -> iolist_to_binary(concat_spaces(L, [H])). concat_spaces([], Acc) -> lists:reverse(Acc); concat_spaces([C], Acc) -> lists:reverse([C,<<" ">>|Acc]); concat_spaces([H|T], Acc) -> concat_spaces(T, [<<" ">>,H|Acc]). has_required_rsc_props(Props) -> not(prop_empty(maps:get(<<"category_id">>, Props, undefined))) andalso not(prop_empty(maps:get(<<"name">>, Props, undefined))) andalso not(prop_empty(maps:get(<<"title">>, Props, undefined))). add_defaults(D, P) -> add_defaults(D, P, P). add_defaults([], _P, Acc) -> Acc; add_defaults([{K,V}|Rest], P, Acc) -> case proplists:get_value(K, P) of undefined -> add_defaults(Rest, P, [{K,V}|Acc]); _ -> add_defaults(Rest, P, Acc) end. increase(Key, Record) -> case proplists:get_value(Key, Record) of undefined -> [{Key, 1} | Record]; N -> [{Key, N+1} | proplists:delete(Key, Record)] end. add_result_ignored(Type, S=#importstate{result=R}) -> S#importstate{result=R#importresult{ignored=increase(Type, R#importresult.ignored)}}. add_result_seen(Type, S=#importstate{result=R}) -> S#importstate{result=R#importresult{seen=increase(Type, R#importresult.seen)}}. add_result_new(Type, S=#importstate{result=R}) -> S#importstate{result=R#importresult{new=increase(Type, R#importresult.new)}}. add_result_updated(Type, S=#importstate{result=R}) -> S#importstate{result=R#importresult{updated=increase(Type, R#importresult.updated)}}. add_result_error(_Type, Error, S=#importstate{result=R}) -> S#importstate{result=R#importresult{errors=[Error|R#importresult.errors]}}. flush_add(Id, State=#importstate{to_flush=F}) -> State#importstate{to_flush=[Id|F]}. managed_edge_add(Id, NewEdges, State=#importstate{managed_edges=Tree}) -> case gb_trees:lookup(Id, Tree) of {value, NewEdges} -> State; {value, undefined} -> State#importstate{managed_edges=gb_trees:update(Id, NewEdges, Tree)}; {value, V} -> State#importstate{managed_edges=gb_trees:update(Id, sets:to_list(sets:from_list(NewEdges ++ V)), Tree)}; none -> State#importstate{managed_edges=gb_trees:insert(Id, NewEdges, Tree)} end. prop_empty(<<>>) -> true; prop_empty(<<" ">>) -> true; prop_empty(<<"\n">>) -> true; prop_empty(undefined) -> true; prop_empty({trans, [{_,<<>>}]}) -> true; prop_empty({trans, []}) -> true; prop_empty(_) -> false. checksum(X) -> crypto:hash(sha, term_to_binary(X)).
null
https://raw.githubusercontent.com/zotonic/zotonic/1bb4aa8a0688d007dd8ec8ba271546f658312da8/apps/zotonic_mod_import_csv/src/support/import_csv.erl
erlang
@doc Import a csv file according to the derived file/record definitions. 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. -type id() :: insert_rsc | m_rsc:resource_id(). @doc The import function, read the csv file and fetch all records. This function is run as a spawned process. The Context should have the right permissions for inserting or updating the resources. Read and parse all rows Return the stats from this import run ==================================================================== Import a record ==================================================================== @doc Import all rows. @doc Combine the field name definitions and the field values. @doc Import all resources on a row Equal Get category name; put category ID in the record. (also pass any import-data from an older import module) Ensure edited properties are set back to their edited values Old version of the csv import, do our best on the diff @todo Use a mapfoldl here to return the new state with name lookups from the edges Find the predicate Find the object Object doesn't exist Object exists Object doesn't exist, create it using the objectprops Object exists Adds a resource Id to the list of managed resources, if the import definition allows it. @doc Maps fields from the given mapping into a new row, filtering out undefined values. Normalize and remove undefined values If name is too long, make a unique thing out of it.
@author < > @author < > Copyright 2010 - 2020 , Licensed under the Apache License , Version 2.0 ( the " License " ) ; distributed under the License is distributed on an " AS IS " BASIS , -module(import_csv). -author("Arjan Scherpenisse <>"). -author("Marc Worrell <>"). -export([ import/3 ]). -include_lib("zotonic_core/include/zotonic.hrl"). -include("../../include/import_csv.hrl"). -record(importresult, {seen=[], new=[], updated=[], errors=[], ignored=[], deleted=0}). -record(importstate, {is_reset, name_to_id, managed_edges, to_flush=[], result, managed_resources}). -type importresult() :: {file, file:filename_all()} | {date_start, calendar:datetime()} | {date_end, calendar:datetime()} | {seen, list( {CategoryName :: binary(), non_neg_integer() })} | {new, list( {CategoryName :: binary(), non_neg_integer() })} | {updated, list( {CategoryName :: binary(), non_neg_integer() })} | {errors, list()} | {deleted, non_neg_integer()} | {ignored, list()}. -type importresults() :: list( importresult() ). -type rowresult() :: ignore | {error, term(), term()} | {new, Type::term(), Id::term(), Name::term()} | {equal, Type::term(), Id::term()} | {updated, Type::term(), Id::term()}. -type row() :: list( {binary(), term()} ). -export_type([ importresult/0, importresults/0 ]). -spec import(#filedef{}, boolean(), z:context()) -> importresults(). import(Def, IsReset, Context) -> StartDate = erlang:universaltime(), {ok, Device} = file:open(Def#filedef.filename, [read, binary, {encoding, utf8}]), Rows = z_csv_parser:scan_lines(Device, Def#filedef.colsep), file:close(Device), file:delete(Def#filedef.filename), Drop ( optionally ) the first row , empty rows and the comment rows ( starting with a ' # ' ) Rows1 = case Def#filedef.skip_first_row of true -> tl(Rows); _ -> Rows end, State = import_rows(Rows1, 1, Def, new_importstate(IsReset), Context), R = State#importstate.result, [ {file, filename:basename(Def#filedef.filename)}, {date_start, StartDate}, {date_end, erlang:universaltime()}, {seen, R#importresult.seen}, {new, R#importresult.new}, {updated, R#importresult.updated}, {errors, R#importresult.errors}, {deleted, 0}, {ignored, R#importresult.ignored} ]. new_importstate(IsReset) -> #importstate{ is_reset=IsReset, name_to_id=gb_trees:empty(), managed_edges=gb_trees:empty(), managed_resources=sets:new(), result=#importresult{} }. -spec import_rows(list( row() ), non_neg_integer(), #filedef{}, #importstate{}, z:context()) -> #importstate{}. import_rows([], _RowNr, _Def, ImportState, _Context) -> ImportState; import_rows([[<<$#, _/binary>>|_]|Rows], RowNr, Def, ImportState, Context) -> import_rows(Rows, RowNr+1, Def, ImportState, Context); import_rows([[]|Rows], RowNr, Def, ImportState, Context) -> import_rows(Rows, RowNr+1, Def, ImportState, Context); import_rows([R|Rows], RowNr, Def, ImportState, Context) -> Zipped = zip(R, Def#filedef.columns, []), ImportState1 = import_parts(Zipped, RowNr, Def#filedef.importdef, ImportState, Context), import_rows(Rows, RowNr+1, Def, ImportState1, Context). zip(_Cols, [], Acc) -> lists:reverse(Acc); zip([_C|Cs], [''|Ns], Acc) -> zip(Cs, Ns, Acc); zip([_C|Cs], [<<>>|Ns], Acc) -> zip(Cs, Ns, Acc); zip([_C|Cs], [undefined|Ns], Acc) -> zip(Cs, Ns, Acc); zip([], [N|Ns], Acc) -> zip([], Ns, [{N,<<>>}|Acc]); zip([C|Cs], [N|Ns], Acc) -> zip(Cs, Ns, [{N, C}|Acc]). -spec import_parts( row(), non_neg_integer(), list( tuple() ), #importstate{}, z:context() ) -> #importstate{}. import_parts(_Row, _RowNr, [], ImportState, _Context) -> ImportState; import_parts(Row, RowNr, [Def | Definitions], ImportState, Context) -> {FieldMapping, ConnectionMapping} = Def, try case import_def_rsc(FieldMapping, Row, ImportState, Context) of {S, ignore} -> import_parts(Row, RowNr, Definitions, S, Context); {S, {error, Type, E}} -> add_result_seen(Type, add_result_error(Type, E, S)); {S, {new, Type, Id, Name}} -> State0 = add_managed_resource(Id, FieldMapping, S), State1 = add_name_lookup(State0, Name, Id), State2 = import_parts(Row, RowNr, Definitions, State1, Context), import_def_edges(Id, ConnectionMapping, Row, State2, Context), add_result_seen(Type, add_result_new(Type, State2)); {S, {equal, Type, Id}} -> State0 = add_managed_resource(Id, FieldMapping, S), State1 = import_parts(Row, RowNr, Definitions, State0, Context), import_def_edges(Id, ConnectionMapping, Row, State1, Context), add_result_seen(Type, add_result_ignored(Type, State1)); {S, {updated, Type, Id}} -> State0 = add_managed_resource(Id, FieldMapping, S), State1 = import_parts(Row, RowNr, Definitions, State0, Context), add_result_seen(Type, import_def_edges(Id, ConnectionMapping, Row, State1, Context)), add_result_updated(Type, State1) end catch throw:{import_error, ImportError} -> ?LOG_ERROR(#{ text => <<"Error importing CSV row data">>, in => zotonic_mod_import_csv, result => error, reason => ImportError, row_nr => RowNr, row => Row, row_def => Def }), ImportState end. -spec import_def_rsc(list(), row(), #importstate{}, z:context()) -> {#importstate{}, rowresult()}. import_def_rsc(FieldMapping, Row, State, Context) -> {Callbacks, FieldMapping1} = case proplists:get_value(callbacks, FieldMapping) of undefined -> {[], FieldMapping}; CB -> {CB, proplists:delete(callbacks, FieldMapping)} end, RowMapped = map_fields(FieldMapping1, Row, State), import_def_rsc_1_cat(RowMapped, Callbacks, State, Context). -spec import_def_rsc_1_cat(row(), list(), #importstate{}, z:context()) -> {#importstate{}, rowresult()}. import_def_rsc_1_cat(Row, Callbacks, State, Context) -> {<<"category">>, CategoryName} = proplists:lookup(<<"category">>, Row), {CatId, State1} = name_lookup_exists(CategoryName, State, Context), Row1 = [{<<"category_id">>, CatId} | proplists:delete(<<"category">>, Row)], Name = case proplists:get_value(<<"name">>, Row1) of undefined -> throw({import_error, {definition_without_unique_name}}); N -> N end, {OptRscId, State2} = name_lookup(Name, State1, Context), RscId = case OptRscId of undefined -> insert_rsc; _ -> OptRscId end, {ok, RowMap} = z_props:from_qs(Row1), NormalizedRowMap = z_sanitize:escape_props_check(RowMap, Context), = sort_props(m_rsc_update : normalize_props(RscId , Row1 , [ is_import ] , Context ) ) , case has_required_rsc_props(NormalizedRowMap) of true -> import_def_rsc_2_name(RscId, State2, Name, CategoryName, NormalizedRowMap, Callbacks, Context); false -> ?LOG_WARNING(#{ text => <<"import_csv: missing required attributes">>, in => zotonic_mod_import_csv, name => Name, result => error, reason => missing_attributes }), {State2, ignore} end. import_def_rsc_2_name(insert_rsc, State, Name, CategoryName, NormalizedRowMap, Callbacks, Context) -> ?LOG_DEBUG(#{ text => <<"import_csv: importing resource">>, in => zotonic_mod_import_csv, name => Name, category_name => CategoryName }), case rsc_insert(NormalizedRowMap, Context) of {ok, NewId} -> RawRscFinal = get_updated_props(NewId, NormalizedRowMap, Context), Checksum = checksum(NormalizedRowMap), m_import_csv_data:update(NewId, Checksum, NormalizedRowMap, RawRscFinal, Context), case proplists:get_value(rsc_insert, Callbacks) of undefined -> none; Callback -> Callback(NewId, NormalizedRowMap, Context) end, {flush_add(NewId, State), {new, CategoryName, NewId, Name}}; {error, Reason} = E -> ?LOG_WARNING(#{ text => <<"import_csv: could not insert resource">>, in => zotonic_mod_import_csv, name => Name, category_name => CategoryName, result => error, reason => Reason }), {State, {error, CategoryName, E}} end; import_def_rsc_2_name(Id, State, Name, CategoryName, NormalizedRowMap, Callbacks, Context) when is_integer(Id) -> 1 . Check if this update was the same as the last known import PrevImportData = m_import_csv_data:get(Id, Context), PrevChecksum = get_value(checksum, PrevImportData), case checksum(NormalizedRowMap) of PrevChecksum when not State#importstate.is_reset -> ?LOG_INFO(#{ text => <<"import_csv: skipping row (importing same values)">>, in => zotonic_mod_import_csv, name => Name, rsc_id => Id, category_name => CategoryName }), {State, {equal, CategoryName, Id}}; Checksum -> ?LOG_INFO(#{ text => <<"import_csv: updating resource">>, in => zotonic_mod_import_csv, name => Name, category_name => CategoryName, rsc_id => Id }), 2 . Some properties might have been overwritten by an editor . For this we will update a second time with all the changed values RawRscPre = get_updated_props(Id, NormalizedRowMap, Context), Edited = diff_raw_props(RawRscPre, get_value(rsc_data, PrevImportData, []), m_rsc:p_no_acl(Id, import_csv_original, Context)), Cleanup old import_csv data on update Row1 = NormalizedRowMap#{ <<"import_csv_original">> => undefined, <<"import_csv_touched">> => undefined }, case rsc_update(Id, Row1, Context) of {ok, _} -> RawRscFinal = get_updated_props(Id, NormalizedRowMap, Context), case maps:size(Edited) of 0 -> ok; _ when State#importstate.is_reset -> ok; _ -> {ok, _} = m_rsc_update:update(Id, Edited, [{is_import, true}], Context) end, m_import_csv_data:update(Id, Checksum, NormalizedRowMap, RawRscFinal, Context), case proplists:get_value(rsc_update, Callbacks) of undefined -> none; Callback -> Callback(Id, NormalizedRowMap, Context) end, {flush_add(Id, State), {updated, CategoryName, Id}}; {error, _} = E -> {State, {error, CategoryName, E}} end end. @doc Return all properties in PreviousImport that are different in Current diff_raw_props(Current, [], {props, OriginalProps}) when is_list(OriginalProps) -> PreviousImport = z_props:from_props(OriginalProps), diff_raw_props(Current, PreviousImport, undefined); diff_raw_props(PreviousImport, PreviousImport, undefined) -> #{}; diff_raw_props(Current, PreviousImport, undefined) when is_list(PreviousImport) -> PreviousImportMap = z_props:from_props(PreviousImport), diff_raw_props(Current, PreviousImportMap, undefined); diff_raw_props(Current, PreviousImport, undefined) when is_map(PreviousImport) -> maps:fold( fun(K, V, Acc) -> case maps:find(K, Current) of {ok, V} -> Acc; {ok, _} -> Acc#{ K => V }; error -> Acc#{ K => V } end end, #{}, PreviousImport). @doc Get all prop values in the Raw resource data get_updated_props(Id, ImportedRow, Context) -> {ok, Raw} = m_rsc:get_raw(Id, Context), maps:fold( fun(K, _, Acc) -> Acc#{ K => maps:get(K, Raw, undefined) } end, #{}, ImportedRow). -spec rsc_insert( m_rsc:props_all(), z:context() ) -> {ok, m_rsc:resource_id()} | {error, term()}. rsc_insert(Props, Context) -> case check_medium(Props) of {url, Url, PropsMedia} -> m_media:insert_url(Url, PropsMedia, [{is_import, true}], Context); none -> m_rsc_update:insert(Props, [{is_import, true}], Context) end. -spec rsc_update( m_rsc:resource_id(), m_rsc:props_all(), z:context() ) -> {ok, m_rsc:resource_id()} | {error, term()}. rsc_update(Id, Props, Context) -> case check_medium(Props) of {url, Url, PropsMedia} -> m_media:replace_url(Url, Id, PropsMedia, [{is_import, true}], Context); none -> m_rsc_update:update(Id, Props, [{is_import, true}], Context) end. -spec check_medium( map() ) -> none | {url, binary(), map()}. check_medium(Props) -> case maps:get(<<"medium_url">>, Props, undefined) of undefined -> none; <<>> -> none; "" -> none; Url -> {url, Url, maps:remove(<<"medium_url">>, Props)} end. get_value(K, L) -> get_value(K, L, undefined). get_value(K, L, D) when is_list(L) -> proplists:get_value(K, L, D); get_value(_K, undefined, D) -> D. import_def_edges(Id, ConnectionMapping, Row, State, Context) -> EdgeIds = lists:flatten([import_do_edge(Id, Row, Map, State, Context) || Map <- ConnectionMapping]), case lists:filter(fun(X) -> not(X == fail) end, EdgeIds) of [] -> State; NewEdgeIds -> managed_edge_add(Id, NewEdgeIds, State) end. import_do_edge(Id, Row, F, State, Context) when is_function(F) -> [ import_do_edge(Id, Row, E, State, Context) || E <- F(Id, Row, State, Context) ]; import_do_edge(Id, Row, {{PredCat, PredRowField}, ObjectDefinition}, State, Context) -> case map_one_normalize(<<"name">>, PredCat, map_one(PredRowField, Row, State)) of <<>> -> fail; Name -> case name_lookup(Name, State, Context) of {undefined, _State1} -> ?LOG_WARNING(#{ text => <<"Import CSV: edge predicate does not exist">>, in => zotonic_mod_import_csv, result => error, reason => predicate, name => Name, subject_id => Id }), fail; {PredId, State1} -> import_do_edge(Id, Row, {PredId, ObjectDefinition}, State1, Context) end end; import_do_edge(Id, Row, {Predicate, {ObjectCat, ObjectRowField}}, State, Context) -> Name = map_one_normalize(<<"name">>, ObjectCat, map_one(ObjectRowField, Row, State)), case Name of <<>> -> fail; Name -> case name_lookup(Name, State, Context) of {undefined, _State1} -> fail; {RscId, _State1} -> {ok, EdgeId} = m_edge:insert(Id, Predicate, RscId, Context), EdgeId end end; import_do_edge(Id, Row, {Predicate, {ObjectCat, ObjectRowField, ObjectProps}}, State, Context) -> Name = map_one_normalize(<<"name">>, ObjectCat, map_one(ObjectRowField, Row, State)), case Name of <<>> -> fail; Name -> case name_lookup(Name, State, Context) of {undefined, _State1} -> ?LOG_DEBUG(#{ text => <<"Import CSV: creating object">>, in => zotonic_mod_import_csv, category => ObjectCat, name => Name, subject_id => Id }), case m_rsc:insert([{category, ObjectCat}, {name, Name} | ObjectProps], Context) of {ok, RscId} -> {ok, EdgeId} = m_edge:insert(Id, Predicate, RscId, Context), EdgeId; {error, _Reason} -> fail end; {RscId, _State1} -> {ok, EdgeId} = m_edge:insert(Id, Predicate, RscId, Context), EdgeId end end; import_do_edge(_, _, Def, _State, _Context) -> throw({import_error, {invalid_edge_definition, Def}}). add_managed_resource(Id, FieldMapping, State=#importstate{managed_resources=M}) -> case proplists:get_value(import_skip_delete, FieldMapping) of true -> State; _ -> State#importstate{managed_resources=sets:add_element(Id, M)} end. add_name_lookup(State=#importstate{name_to_id=Tree}, Name, Id) -> case gb_trees:lookup(Name, Tree) of {value, undefined} -> State#importstate{name_to_id=gb_trees:update(Name, Id, Tree)}; {value, _} -> State; none -> State#importstate{name_to_id=gb_trees:insert(Name, Id, Tree)} end. name_lookup(Name, #importstate{name_to_id=Tree} = State, Context) -> case gb_trees:lookup(Name, Tree) of {value, V} -> {V, State}; none -> V = m_rsc:rid(Name, Context), {V, add_name_lookup(State, Name, V)} end. name_lookup_exists(Name, State, Context) -> case name_lookup(Name, State, Context) of {undefined, _State1} -> throw({import_error, {unknown_resource_name, Name}}); {Id, State1} -> {Id, State1} end. map_fields(Mapping, Row, State) -> Defaults = [ {<<"is_protected">>, true}, {<<"is_published">>, true} ], Mapped = [ map_def(MapOne, Row, State) || MapOne <- Mapping ], Type = case proplists:get_value(<<"category">>, Mapped) of undefined -> throw({import_error, no_category_in_import_definition}); T -> T end, P = lists:filter(fun({_K,undefined}) -> false; (_) -> true end, [{K, map_one_normalize(K, Type, V)} || {K,V} <- Mapped]), add_defaults(Defaults, P). map_def({K,F}, Row, State) -> {K, map_one(F, Row, State)}; map_def(K, Row, State) when is_atom(K); is_list(K) -> map_def({K,K}, Row, State). -spec map_one_normalize( binary(), any(), any() | {name_prefix, binary() | string() | atom(), binary() | string() | atom()} ) -> any(). map_one_normalize(<<"name">>, _Type, <<>>) -> <<>>; map_one_normalize(<<"name">>, _Type, {name_prefix, Prefix, V}) -> CheckL = 80 - strlen(Prefix) - 1, Postfix = case strlen(V) of L when L > CheckL -> base64:encode(checksum(V)); _ -> V end, Name = z_string:to_name( iolist_to_binary([Prefix, "_", Postfix]) ), z_convert:to_binary(Name); map_one_normalize(_, _Type, V) -> V. strlen(B) when is_binary(B) -> erlang:size(B); strlen(L) when is_list(L) -> erlang:length(L); strlen(A) when is_atom(A) -> erlang:length(atom_to_list(A)). map_one(F, _Row, _State) when is_binary(F) -> F; map_one(undefined, _Row, _State) -> undefined; map_one(true, _Row, _State) -> true; map_one(false, _Row, _State) -> false; map_one(F, Row, _State) when is_atom(F) -> concat_spaces(proplists:get_all_values(z_convert:to_list(F), Row)); map_one(F, Row, _State) when is_list(F) -> concat_spaces(proplists:get_all_values(F, Row)); map_one(F, Row, _State) when is_function(F) -> F(Row); map_one({prefer, Fields}, Row, State) -> map_one_prefer(Fields, Row, State); map_one({html_escape, Value}, Row, State) -> z_html:escape(map_one(Value, Row, State)); map_one({concat, Fields}, Row, State) -> map_one_concat(Fields, Row, State); map_one({surroundspace, Field}, Row, State) -> case z_string:trim(map_one(Field, Row, State)) of <<>> -> <<" ">>; Val -> <<32, Val/binary, 32>> end; map_one({name_prefix, Prefix, Rest}, Row, State) -> {name_prefix, Prefix, map_one(Rest, Row, State)}; map_one({datetime, F}, Row, State) -> z_convert:to_datetime(map_one(F, Row, State)); map_one({date, F}, Row, State) -> z_convert:to_date(map_one(F, Row, State)); map_one({time, F}, Row, State) -> z_convert:to_time(map_one(F, Row, State)); map_one({datetime, D, T}, Row, State) -> {map_one({date, D}, Row, State), map_one({time, T}, Row, State)}; map_one({if_then_else, Cond, If, Else}, Row, State) -> case prop_empty(map_one(Cond, Row, State)) of false -> map_one(If, Row, State); true -> map_one(Else, Row, State) end; map_one(F, _, _) -> throw({import_error, {invalid_import_definition, F}}). map_one_prefer([F], Row, State) -> map_one(F, Row, State); map_one_prefer([F|Rest], Row, State) -> Prop = map_one(F, Row, State), case prop_empty(Prop) of false -> Prop; true -> map_one_prefer(Rest, Row, State) end. map_one_concat(List, Row, State) -> concat([ map_one(F, Row, State) || F <- List]). multiple values , take into account that a value might be a tuple or atom concat([]) -> <<>>; concat([X]) when is_atom(X); is_tuple(X) -> X; concat(L) -> iolist_to_binary(L). concat_spaces([]) -> <<>>; concat_spaces([X]) when is_atom(X); is_tuple(X) -> X; concat_spaces([H|L]) -> iolist_to_binary(concat_spaces(L, [H])). concat_spaces([], Acc) -> lists:reverse(Acc); concat_spaces([C], Acc) -> lists:reverse([C,<<" ">>|Acc]); concat_spaces([H|T], Acc) -> concat_spaces(T, [<<" ">>,H|Acc]). has_required_rsc_props(Props) -> not(prop_empty(maps:get(<<"category_id">>, Props, undefined))) andalso not(prop_empty(maps:get(<<"name">>, Props, undefined))) andalso not(prop_empty(maps:get(<<"title">>, Props, undefined))). add_defaults(D, P) -> add_defaults(D, P, P). add_defaults([], _P, Acc) -> Acc; add_defaults([{K,V}|Rest], P, Acc) -> case proplists:get_value(K, P) of undefined -> add_defaults(Rest, P, [{K,V}|Acc]); _ -> add_defaults(Rest, P, Acc) end. increase(Key, Record) -> case proplists:get_value(Key, Record) of undefined -> [{Key, 1} | Record]; N -> [{Key, N+1} | proplists:delete(Key, Record)] end. add_result_ignored(Type, S=#importstate{result=R}) -> S#importstate{result=R#importresult{ignored=increase(Type, R#importresult.ignored)}}. add_result_seen(Type, S=#importstate{result=R}) -> S#importstate{result=R#importresult{seen=increase(Type, R#importresult.seen)}}. add_result_new(Type, S=#importstate{result=R}) -> S#importstate{result=R#importresult{new=increase(Type, R#importresult.new)}}. add_result_updated(Type, S=#importstate{result=R}) -> S#importstate{result=R#importresult{updated=increase(Type, R#importresult.updated)}}. add_result_error(_Type, Error, S=#importstate{result=R}) -> S#importstate{result=R#importresult{errors=[Error|R#importresult.errors]}}. flush_add(Id, State=#importstate{to_flush=F}) -> State#importstate{to_flush=[Id|F]}. managed_edge_add(Id, NewEdges, State=#importstate{managed_edges=Tree}) -> case gb_trees:lookup(Id, Tree) of {value, NewEdges} -> State; {value, undefined} -> State#importstate{managed_edges=gb_trees:update(Id, NewEdges, Tree)}; {value, V} -> State#importstate{managed_edges=gb_trees:update(Id, sets:to_list(sets:from_list(NewEdges ++ V)), Tree)}; none -> State#importstate{managed_edges=gb_trees:insert(Id, NewEdges, Tree)} end. prop_empty(<<>>) -> true; prop_empty(<<" ">>) -> true; prop_empty(<<"\n">>) -> true; prop_empty(undefined) -> true; prop_empty({trans, [{_,<<>>}]}) -> true; prop_empty({trans, []}) -> true; prop_empty(_) -> false. checksum(X) -> crypto:hash(sha, term_to_binary(X)).
d6ea4c628b727d971a79fd5df270a7fa43ab1748614b9569f9175209664188f0
yakaz/yamerl
flow_mapping_empty_5.erl
-module('flow_mapping_empty_5'). -include_lib("eunit/include/eunit.hrl"). -define(FILENAME, "test/parsing/" ?MODULE_STRING ".yaml"). single_test_() -> ?_assertMatch( {yamerl_parser, {file,?FILENAME}, [], <<>>, 9, true, [], 0, 10, 4, 1, false, 3, 2, utf8, false, undefined, _, _, [], {bcoll,root,0,-1,1,1,-1,1,1}, false, false, false, [{impl_key,false,false,undefined,undefined,1,1}], false, false, _, [], 0, 11, 10, undefined, undefined, _, false, [], [ {yamerl_stream_end,3,2}, {yamerl_doc_end,3,2}, {yamerl_collection_end,3,1,flow,mapping}, {yamerl_scalar,2,4, {yamerl_tag,2,4,{non_specific,"?"}}, flow,plain,[]}, {yamerl_mapping_value,2,4}, {yamerl_scalar,2,1, {yamerl_tag,2,1,{non_specific,"?"}}, flow,plain,"key"}, {yamerl_mapping_key,2,1}, {yamerl_collection_start,1,1, {yamerl_tag,1,1,{non_specific,"?"}}, flow,mapping}, {yamerl_doc_start,1,1,{1,2},_}, {yamerl_stream_start,1,1,utf8} ] }, yamerl_parser:file(?FILENAME) ).
null
https://raw.githubusercontent.com/yakaz/yamerl/0032607a7b27fa2b548fc9a02d7ae6b53469c0c5/test/parsing/flow_mapping_empty_5.erl
erlang
-module('flow_mapping_empty_5'). -include_lib("eunit/include/eunit.hrl"). -define(FILENAME, "test/parsing/" ?MODULE_STRING ".yaml"). single_test_() -> ?_assertMatch( {yamerl_parser, {file,?FILENAME}, [], <<>>, 9, true, [], 0, 10, 4, 1, false, 3, 2, utf8, false, undefined, _, _, [], {bcoll,root,0,-1,1,1,-1,1,1}, false, false, false, [{impl_key,false,false,undefined,undefined,1,1}], false, false, _, [], 0, 11, 10, undefined, undefined, _, false, [], [ {yamerl_stream_end,3,2}, {yamerl_doc_end,3,2}, {yamerl_collection_end,3,1,flow,mapping}, {yamerl_scalar,2,4, {yamerl_tag,2,4,{non_specific,"?"}}, flow,plain,[]}, {yamerl_mapping_value,2,4}, {yamerl_scalar,2,1, {yamerl_tag,2,1,{non_specific,"?"}}, flow,plain,"key"}, {yamerl_mapping_key,2,1}, {yamerl_collection_start,1,1, {yamerl_tag,1,1,{non_specific,"?"}}, flow,mapping}, {yamerl_doc_start,1,1,{1,2},_}, {yamerl_stream_start,1,1,utf8} ] }, yamerl_parser:file(?FILENAME) ).
75baff3beb2d32b368e76b321209bc1eac0823ce9497a7c1a7eaf2039bf440cb
GlideAngle/flare-timing
DiscardFurther.hs
module Flight.DiscardFurther ( AltBonus(..) , readCompBestDistances , readPilotAlignTimeWriteDiscardFurther , readPilotAlignTimeWritePegThenDiscard , readPilotDiscardFurther , readPilotPegThenDiscard , readDiscardFurther ) where import Control.Exception.Safe (MonadThrow, throwString) import Control.Monad.Except (MonadIO, liftIO) import Control.Monad (zipWithM) import qualified Data.ByteString.Lazy as BL import System.Directory (createDirectoryIfMissing) import System.FilePath ((</>)) import Data.Csv (Header, decodeByName, EncodeOptions(..), encodeByNameWith, defaultEncodeOptions) import qualified Data.ByteString.Lazy.Char8 as L (writeFile) import Data.Vector (Vector) import qualified Data.Vector as V (toList, null, last, filter) import Flight.Track.Time ( TimeRow(..), TickRow(..), TimeToTick, TickToTick , TickHeader(..) , timesToKeptTicks, tickHeader ) import Flight.Comp ( IxTask(..) , Pilot(..) , CompInputFile(..) , AlignTimeDir(..) , AlignTimeFile(..) , DiscardFurtherFile(..) , PegThenDiscardFile(..) , DiscardFurtherDir(..) , PegThenDiscardDir(..) , discardFurtherDir , pegThenDiscardDir , alignTimePath , discardFurtherPath , pegThenDiscardPath , compFileToCompDir ) import Flight.AlignTime (readAlignTime) newtype AltBonus = AltBonus Bool readDiscardFurther :: (MonadThrow m, MonadIO m) => DiscardFurtherFile -> m (Header, Vector TickRow) readDiscardFurther (DiscardFurtherFile csvPath) = do contents <- liftIO $ BL.readFile csvPath either throwString return $ decodeByName contents readPegThenDiscard :: (MonadThrow m, MonadIO m) => PegThenDiscardFile -> m (Header, Vector TickRow) readPegThenDiscard (PegThenDiscardFile csvPath) = do contents <- liftIO $ BL.readFile csvPath either throwString return $ decodeByName contents writeDiscardFurther :: DiscardFurtherFile -> Vector TickRow -> IO () writeDiscardFurther (DiscardFurtherFile path) xs = L.writeFile path rows where (TickHeader hs) = tickHeader opts = defaultEncodeOptions {encUseCrLf = False} rows = encodeByNameWith opts hs $ V.toList xs writePegThenDiscard :: PegThenDiscardFile -> TickHeader -> Vector TickRow -> IO () writePegThenDiscard (PegThenDiscardFile path) (TickHeader hs) xs = L.writeFile path rows where opts = defaultEncodeOptions {encUseCrLf = False} rows = encodeByNameWith opts hs $ V.toList xs lastRow :: Vector TickRow -> Maybe TickRow lastRow xs = if V.null xs then Nothing else Just $ V.last xs readCompBestDistances :: AltBonus -> CompInputFile -> (IxTask -> Bool) -> [[Pilot]] -> IO [[Maybe (Pilot, TickRow)]] readCompBestDistances altBonus compFile includeTask = zipWithM (\ ixTask ps -> if not (includeTask ixTask) then return [] else readTaskBestDistances altBonus compFile ixTask ps) (IxTask <$> [1 .. ]) readTaskBestDistances :: AltBonus -> CompInputFile -> IxTask -> [Pilot] -> IO [Maybe (Pilot, TickRow)] readTaskBestDistances altBonus compFile ixTask = mapM (readPilotBestDistance altBonus compFile ixTask) readPilotBestDistance :: AltBonus -> CompInputFile -> IxTask -> Pilot -> IO (Maybe (Pilot, TickRow)) readPilotBestDistance (AltBonus False) compFile ixTask pilot = do (_, rows) <- readDiscardFurther (DiscardFurtherFile $ path </> file) return $ (pilot,) <$> lastRow rows where dir = compFileToCompDir compFile (DiscardFurtherDir path, DiscardFurtherFile file) = discardFurtherPath dir ixTask pilot readPilotBestDistance (AltBonus True) compFile ixTask pilot = do (_, rows) <- readPegThenDiscard (PegThenDiscardFile $ path </> file) return $ (pilot,) <$> lastRow rows where dir = compFileToCompDir compFile (PegThenDiscardDir path, PegThenDiscardFile file) = pegThenDiscardPath dir ixTask pilot readAlign :: TimeToTick -> TickToTick -> (TimeRow -> Bool) -> (Vector TickRow -> IO a) -> FilePath -> FilePath -> FilePath -> IO (Maybe (Vector TickRow)) readAlign timeToTick tickToTick selectRow f file dIn dOut = do _ <- createDirectoryIfMissing True dOut (_, timeRows :: Vector TimeRow) <- readAlignTime (AlignTimeFile (dIn </> file)) let keptTimeRows = V.filter selectRow timeRows let tickRows :: Vector TickRow = timesToKeptTicks timeToTick tickToTick keptTimeRows _ <- f tickRows return $ Just tickRows readPilotAlignTimeWriteDiscardFurther :: TimeToTick -> TickToTick -> CompInputFile -> (IxTask -> Bool) -> (TimeRow -> Bool) -> IxTask -> Pilot -> IO (Maybe (Vector TickRow)) readPilotAlignTimeWriteDiscardFurther timeToTick tickToTick compFile selectTask selectRow ixTask pilot = if not (selectTask ixTask) then return Nothing else readAlign timeToTick tickToTick selectRow f file dIn dOut where f = writeDiscardFurther (DiscardFurtherFile $ dOut </> file) dir = compFileToCompDir compFile (AlignTimeDir dIn, AlignTimeFile file) = alignTimePath dir ixTask pilot (DiscardFurtherDir dOut) = discardFurtherDir dir ixTask readPilotAlignTimeWritePegThenDiscard :: TimeToTick -> TickToTick -> CompInputFile -> (IxTask -> Bool) -> (TimeRow -> Bool) -> IxTask -> Pilot -> IO (Maybe (Vector TickRow)) readPilotAlignTimeWritePegThenDiscard timeToTick tickToTick compFile selectTask selectRow ixTask pilot = if not (selectTask ixTask) then return Nothing else readAlign timeToTick tickToTick selectRow f file dIn dOut where f = writePegThenDiscard (PegThenDiscardFile $ dOut </> file) tickHeader dir = compFileToCompDir compFile (AlignTimeDir dIn, AlignTimeFile file) = alignTimePath dir ixTask pilot (PegThenDiscardDir dOut) = pegThenDiscardDir dir ixTask readPilotDiscardFurther :: CompInputFile -> IxTask -> Pilot -> IO [TickRow] readPilotDiscardFurther compFile ixTask pilot = do let dir = compFileToCompDir compFile let (DiscardFurtherDir path, DiscardFurtherFile file) = discardFurtherPath dir ixTask pilot (_, rows) <- readDiscardFurther (DiscardFurtherFile $ path </> file) return $ V.toList rows readPilotPegThenDiscard :: CompInputFile -> IxTask -> Pilot -> IO [TickRow] readPilotPegThenDiscard compFile ixTask pilot = do let dir = compFileToCompDir compFile let (PegThenDiscardDir path, PegThenDiscardFile file) = pegThenDiscardPath dir ixTask pilot (_, rows) <- readPegThenDiscard (PegThenDiscardFile $ path </> file) return $ V.toList rows
null
https://raw.githubusercontent.com/GlideAngle/flare-timing/172a9b199eb1ff72c967669dc349cbf8d9c4bc52/lang-haskell/scribe/library/Flight/DiscardFurther.hs
haskell
module Flight.DiscardFurther ( AltBonus(..) , readCompBestDistances , readPilotAlignTimeWriteDiscardFurther , readPilotAlignTimeWritePegThenDiscard , readPilotDiscardFurther , readPilotPegThenDiscard , readDiscardFurther ) where import Control.Exception.Safe (MonadThrow, throwString) import Control.Monad.Except (MonadIO, liftIO) import Control.Monad (zipWithM) import qualified Data.ByteString.Lazy as BL import System.Directory (createDirectoryIfMissing) import System.FilePath ((</>)) import Data.Csv (Header, decodeByName, EncodeOptions(..), encodeByNameWith, defaultEncodeOptions) import qualified Data.ByteString.Lazy.Char8 as L (writeFile) import Data.Vector (Vector) import qualified Data.Vector as V (toList, null, last, filter) import Flight.Track.Time ( TimeRow(..), TickRow(..), TimeToTick, TickToTick , TickHeader(..) , timesToKeptTicks, tickHeader ) import Flight.Comp ( IxTask(..) , Pilot(..) , CompInputFile(..) , AlignTimeDir(..) , AlignTimeFile(..) , DiscardFurtherFile(..) , PegThenDiscardFile(..) , DiscardFurtherDir(..) , PegThenDiscardDir(..) , discardFurtherDir , pegThenDiscardDir , alignTimePath , discardFurtherPath , pegThenDiscardPath , compFileToCompDir ) import Flight.AlignTime (readAlignTime) newtype AltBonus = AltBonus Bool readDiscardFurther :: (MonadThrow m, MonadIO m) => DiscardFurtherFile -> m (Header, Vector TickRow) readDiscardFurther (DiscardFurtherFile csvPath) = do contents <- liftIO $ BL.readFile csvPath either throwString return $ decodeByName contents readPegThenDiscard :: (MonadThrow m, MonadIO m) => PegThenDiscardFile -> m (Header, Vector TickRow) readPegThenDiscard (PegThenDiscardFile csvPath) = do contents <- liftIO $ BL.readFile csvPath either throwString return $ decodeByName contents writeDiscardFurther :: DiscardFurtherFile -> Vector TickRow -> IO () writeDiscardFurther (DiscardFurtherFile path) xs = L.writeFile path rows where (TickHeader hs) = tickHeader opts = defaultEncodeOptions {encUseCrLf = False} rows = encodeByNameWith opts hs $ V.toList xs writePegThenDiscard :: PegThenDiscardFile -> TickHeader -> Vector TickRow -> IO () writePegThenDiscard (PegThenDiscardFile path) (TickHeader hs) xs = L.writeFile path rows where opts = defaultEncodeOptions {encUseCrLf = False} rows = encodeByNameWith opts hs $ V.toList xs lastRow :: Vector TickRow -> Maybe TickRow lastRow xs = if V.null xs then Nothing else Just $ V.last xs readCompBestDistances :: AltBonus -> CompInputFile -> (IxTask -> Bool) -> [[Pilot]] -> IO [[Maybe (Pilot, TickRow)]] readCompBestDistances altBonus compFile includeTask = zipWithM (\ ixTask ps -> if not (includeTask ixTask) then return [] else readTaskBestDistances altBonus compFile ixTask ps) (IxTask <$> [1 .. ]) readTaskBestDistances :: AltBonus -> CompInputFile -> IxTask -> [Pilot] -> IO [Maybe (Pilot, TickRow)] readTaskBestDistances altBonus compFile ixTask = mapM (readPilotBestDistance altBonus compFile ixTask) readPilotBestDistance :: AltBonus -> CompInputFile -> IxTask -> Pilot -> IO (Maybe (Pilot, TickRow)) readPilotBestDistance (AltBonus False) compFile ixTask pilot = do (_, rows) <- readDiscardFurther (DiscardFurtherFile $ path </> file) return $ (pilot,) <$> lastRow rows where dir = compFileToCompDir compFile (DiscardFurtherDir path, DiscardFurtherFile file) = discardFurtherPath dir ixTask pilot readPilotBestDistance (AltBonus True) compFile ixTask pilot = do (_, rows) <- readPegThenDiscard (PegThenDiscardFile $ path </> file) return $ (pilot,) <$> lastRow rows where dir = compFileToCompDir compFile (PegThenDiscardDir path, PegThenDiscardFile file) = pegThenDiscardPath dir ixTask pilot readAlign :: TimeToTick -> TickToTick -> (TimeRow -> Bool) -> (Vector TickRow -> IO a) -> FilePath -> FilePath -> FilePath -> IO (Maybe (Vector TickRow)) readAlign timeToTick tickToTick selectRow f file dIn dOut = do _ <- createDirectoryIfMissing True dOut (_, timeRows :: Vector TimeRow) <- readAlignTime (AlignTimeFile (dIn </> file)) let keptTimeRows = V.filter selectRow timeRows let tickRows :: Vector TickRow = timesToKeptTicks timeToTick tickToTick keptTimeRows _ <- f tickRows return $ Just tickRows readPilotAlignTimeWriteDiscardFurther :: TimeToTick -> TickToTick -> CompInputFile -> (IxTask -> Bool) -> (TimeRow -> Bool) -> IxTask -> Pilot -> IO (Maybe (Vector TickRow)) readPilotAlignTimeWriteDiscardFurther timeToTick tickToTick compFile selectTask selectRow ixTask pilot = if not (selectTask ixTask) then return Nothing else readAlign timeToTick tickToTick selectRow f file dIn dOut where f = writeDiscardFurther (DiscardFurtherFile $ dOut </> file) dir = compFileToCompDir compFile (AlignTimeDir dIn, AlignTimeFile file) = alignTimePath dir ixTask pilot (DiscardFurtherDir dOut) = discardFurtherDir dir ixTask readPilotAlignTimeWritePegThenDiscard :: TimeToTick -> TickToTick -> CompInputFile -> (IxTask -> Bool) -> (TimeRow -> Bool) -> IxTask -> Pilot -> IO (Maybe (Vector TickRow)) readPilotAlignTimeWritePegThenDiscard timeToTick tickToTick compFile selectTask selectRow ixTask pilot = if not (selectTask ixTask) then return Nothing else readAlign timeToTick tickToTick selectRow f file dIn dOut where f = writePegThenDiscard (PegThenDiscardFile $ dOut </> file) tickHeader dir = compFileToCompDir compFile (AlignTimeDir dIn, AlignTimeFile file) = alignTimePath dir ixTask pilot (PegThenDiscardDir dOut) = pegThenDiscardDir dir ixTask readPilotDiscardFurther :: CompInputFile -> IxTask -> Pilot -> IO [TickRow] readPilotDiscardFurther compFile ixTask pilot = do let dir = compFileToCompDir compFile let (DiscardFurtherDir path, DiscardFurtherFile file) = discardFurtherPath dir ixTask pilot (_, rows) <- readDiscardFurther (DiscardFurtherFile $ path </> file) return $ V.toList rows readPilotPegThenDiscard :: CompInputFile -> IxTask -> Pilot -> IO [TickRow] readPilotPegThenDiscard compFile ixTask pilot = do let dir = compFileToCompDir compFile let (PegThenDiscardDir path, PegThenDiscardFile file) = pegThenDiscardPath dir ixTask pilot (_, rows) <- readPegThenDiscard (PegThenDiscardFile $ path </> file) return $ V.toList rows
6631cf849d83121a4c9c4082961ec15e41f7f201cf0dc623bae6a65978fa624e
igrishaev/farseer
http.clj
(ns farseer.spec.http (:require [clojure.string :as str] [clojure.spec.alpha :as s])) (s/def :http/method #{:post :get :put :delete}) (defn path? [line] (str/starts-with? line "/")) (s/def :http/path (s/and string? path?)) (s/def :http/health? boolean?) (s/def ::config (s/keys :req [:http/method :http/path :http/health?]))
null
https://raw.githubusercontent.com/igrishaev/farseer/0c5aead5cbabf80edf32952888c9f860aa1248c7/farseer-http/src/farseer/spec/http.clj
clojure
(ns farseer.spec.http (:require [clojure.string :as str] [clojure.spec.alpha :as s])) (s/def :http/method #{:post :get :put :delete}) (defn path? [line] (str/starts-with? line "/")) (s/def :http/path (s/and string? path?)) (s/def :http/health? boolean?) (s/def ::config (s/keys :req [:http/method :http/path :http/health?]))
14923686483e30870160399feddf76d6fee7290329853395182cc7892c82d69e
Kappa-Dev/KappaTools
tools.ml
(******************************************************************************) (* _ __ * The Kappa Language *) | |/ / * Copyright 2010 - 2020 CNRS - Harvard Medical School - INRIA - IRIF (* | ' / *********************************************************************) (* | . \ * This file is distributed under the terms of the *) (* |_|\_\ * GNU Lesser General Public License Version 3 *) (******************************************************************************) let float_is_zero x = match classify_float x with | FP_zero -> true | FP_normal | FP_subnormal |FP_infinite | FP_nan -> false let pow i j = let () = assert (0 <= j) in let rec aux i k accu = if k=0 then accu else if k land 1 = 0 then aux i (k/2) accu*accu else aux i (k/2) (i*accu*accu) in aux i j 1 let fact i = let rec aux i accu = if i<2 then accu else aux (i-1) (i*accu) in aux i 1 let get_product_image_occ start combine f l = let l = List.sort compare l in let rec aux l old occ accu = match l with | h::t when h=old -> aux t old (1+occ) accu | _ -> begin let accu = combine accu (f occ) in match l with | h::t -> aux t h 1 accu | [] -> accu end in match l with | [] -> 1 | h::t -> aux t h 1 start let get_product_image_occ_2 start combine f l1 l2 = let l1 = List.sort compare l1 in let l2 = List.sort compare l2 in let count_head_and_get_tail l = match l with | [] -> [],0 | h::t -> let rec aux l h occ = match l with | [] -> [],occ | h'::t when h=h' -> aux t h (occ+1) | _ -> l,occ in aux t h 1 in let rec aux l1 l2 accu = match l1,l2 with | h1::_,h2::_ when h1=h2 -> let l1,occ1 = count_head_and_get_tail l1 in let l2,occ2 = count_head_and_get_tail l2 in aux l1 l2 (combine accu (f occ1 occ2)) | h1::_,h2::_ when compare h1 h2 < 0 -> let l1,occ1 = count_head_and_get_tail l1 in aux l1 l2 (combine accu (f occ1 0)) | _::_,_::_ -> let l2,occ2 = count_head_and_get_tail l2 in aux l1 l2 (combine accu (f 0 occ2)) | [],_ | _,[] -> accu in aux l1 l2 start let div2 x = Int64.div x (Int64.add Int64.one Int64.one) let pow64 x n = assert (n >= Int64.zero); let rec aux k accu = if k=Int64.zero then accu else if Int64.logand k Int64.one = Int64.zero then aux (div2 k) (Int64.mul accu accu) else aux (div2 k) (Int64.mul x (Int64.mul accu accu)) in aux n Int64.one let cantor_pairing x y = let s = x + y in (succ s * s)/2 + y let read_input () = let rec parse acc input = match Stream.next input with | '\n' -> acc | c -> parse (Printf.sprintf "%s%c" acc c) input in try let user_input = Stream.of_channel stdin in parse "" user_input with | Stream.Failure -> invalid_arg "Tools.Read_input: cannot read stream" let not_an_id s = (String.length s = 0) || let i = int_of_char s.[0] in (i < 65 || i > 122 || (i > 90 && (i <> 95 || String.length s = 1) && i < 97)) || try String.iter (fun c -> let i = int_of_char c in if i < 48 || i > 122 || (i > 57 && (i < 65 || (i > 90 && i <> 95 && i < 97))) then raise Not_found) s; false with Not_found -> true let array_fold_left_mapi f x a = let y = ref x in let o = Array.init (Array.length a) (fun i -> let (y',out) = f i !y a.(i) in let () = y := y' in out) in (!y,o) let array_map_of_list = let rec fill f i v = function | [] -> () | x :: l -> Array.unsafe_set v i (f x); fill f (succ i) v l in fun f -> function | [] -> [||] | x :: l -> let len = succ (List.length l) in let ans = Array.make len (f x) in let () = fill f 1 ans l in ans let array_rev_of_list = let rec fill out i = function | [] -> assert (i= -1) | h' :: t' -> let () = Array.unsafe_set out i h' in fill out (pred i) t' in function | [] -> [||] | h :: t -> let l = succ (List.length t) in let out = Array.make l h in let () = fill out (l - 2) t in out let array_rev_map_of_list = let rec fill f out i = function | [] -> assert (i= -1) | h' :: t' -> let () = Array.unsafe_set out i (f h') in fill f out (pred i) t' in fun f -> function | [] -> [||] | h :: t -> let l = succ (List.length t) in let out = Array.make l (f h) in let () = fill f out (l - 2) t in out let array_fold_lefti f x a = let y = ref x in let () = Array.iteri (fun i e -> y := f i !y e) a in !y let rec aux_fold_righti i f a x = if i < 0 then x else aux_fold_righti (pred i) f a (f i a.(i) x) let array_fold_righti f a x = aux_fold_righti (Array.length a - 1) f a x let array_fold_left2i f x a1 a2 = let l = Array.length a1 in if l <> Array.length a2 then raise (Invalid_argument "array_fold_left2i") else array_fold_lefti (fun i x e -> f i x e a2.(i)) x a1 let array_filter f a = array_fold_lefti (fun i acc x -> if f i x then i :: acc else acc) [] a let array_min_equal_not_null l1 l2 = if Array.length l1 <> Array.length l2 then None else let rec f j = if j = Array.length l1 then Some ([],[]) else let (nb1,ag1) = l1.(j) in let (nb2,ag2) = l2.(j) in if nb1 <> nb2 then None else if nb1 = 0 then f (succ j) else let rec aux i va out = if i = Array.length l1 then Some out else let (nb1,ag1) = l1.(i) in let (nb2,ag2) = l2.(i) in if nb1 <> nb2 then None else if nb1 > 0 && nb1 < va then aux (succ i) nb1 (ag1,ag2) else aux (succ i) va out in aux (succ j) nb1 (ag1,ag2) in f 0 let array_compare compare a b = let l = Array.length a in let l' = Array.length b in let d = Stdlib.compare l l' in let rec aux_array_compare k = if k >= l then 0 else let o = compare a.(k) b.(k) in if o <> 0 then o else aux_array_compare (succ k) in if d <> 0 then d else aux_array_compare 0 let iteri f i = let rec aux j = if j < i then let () = f j in aux (succ j) in aux 0 let rec recti f x i = if 0 < i then let i' = pred i in recti f (f x i') i' else x let min_pos_int_not_zero (keya,dataa) (keyb,datab) = if keya = 0 then keyb,datab else if keyb = 0 then keya,dataa else if compare keya keyb > 0 then keyb,datab else keya,dataa let max_pos_int_not_zero (keya,dataa) (keyb,datab) = if compare keya keyb > 0 then keya,dataa else keyb,datab let fold_over_permutations f l accu = let rec aux to_do discarded permutation accu = match to_do,discarded with | [],[] -> f permutation accu | [],_::_ -> accu | h::t,_ -> let to_do1 = List.fold_left (fun list a -> a::list) t discarded in let accu = aux to_do1 [] (h::permutation) accu in let accu = aux t (h::discarded) permutation accu in accu in aux l [] [] accu let gcd_2 a b = let rec aux a b = if b = 0 then a else aux b (a mod b) in let a = abs a in let b = abs b in if a < b then aux b a else aux a b let lcm_2 a b = (abs a)*(abs b)/(gcd_2 a b) let lcm list = match list with | [] -> 0 | h::t -> List.fold_left lcm_2 h t let get_interval_list p i j = let add current output = match current with | None -> output | Some p -> p::output in let insert k current = match current with | None -> Some (k,k) | Some (_,j) -> Some (k,j) in let rec aux p k current output = if k<i then add current output else if p k then aux p (k-1) (insert k current) output else aux p (k-1) None (add current output) in aux p j None [] let lowercase = String.lowercase_ascii let capitalize = String.capitalize_ascii let string_split_on_char (delimiter : char) (s : string) : (string * string option) = try let index = String.index s delimiter in let length = String.length s in (String.sub s 0 index, Some (String.sub s (index + 1) (length - index - 1) )) with Not_found -> (s,None) let smash_duplicate_in_ordered_list p l = let () = Format.fprintf Format.std_formatter "DUPL \n" in let rec aux tail nocc current accu = match tail with | [] -> (current,nocc)::accu | (h,n)::t when p h current = 0 -> (*let () = Format.fprintf Format.std_formatter "DUPL %i\n" (n+nocc) in*) aux t (n+nocc) current accu | (h,n)::t -> aux t n h ((current,nocc)::accu) in match (List.rev l) with | [] -> [] | (h,n)::t -> aux t n h [] let chop_suffix_or_extension name ext = if Filename.check_suffix name ext then Filename.chop_suffix name ext else Filename.remove_extension name let find_available_name ~already_there name ~facultative ~ext = let ext = match ext with Some e -> e | None -> Filename.extension name in let base = chop_suffix_or_extension name ext in if already_there (base^ext) then let base' = if facultative <> "" then base^"_"^facultative else base in if already_there (base'^ext) then let v = ref 0 in let () = while already_there (base'^"~"^(string_of_int !v)^ext) do incr v; done in base'^"~"^(string_of_int !v)^ext else base'^ext else base^ext let default_message_delimter : char = '\x1e' (* "\t" *) let get_ref ref = let i = !ref in let () = ref := i+1 in i let remove_double_elements l = let l = List.sort compare l in let rec aux l accu old = match l, old with | [], _ -> accu | h::t, Some h' when h=h' -> aux t accu old | h::t, (None | Some _) -> aux t (h::accu) (Some h) in aux l [] None
null
https://raw.githubusercontent.com/Kappa-Dev/KappaTools/eef2337e8688018eda47ccc838aea809cae68de7/core/dataStructures/tools.ml
ocaml
**************************************************************************** _ __ * The Kappa Language | ' / ******************************************************************** | . \ * This file is distributed under the terms of the |_|\_\ * GNU Lesser General Public License Version 3 **************************************************************************** let () = Format.fprintf Format.std_formatter "DUPL %i\n" (n+nocc) in "\t"
| |/ / * Copyright 2010 - 2020 CNRS - Harvard Medical School - INRIA - IRIF let float_is_zero x = match classify_float x with | FP_zero -> true | FP_normal | FP_subnormal |FP_infinite | FP_nan -> false let pow i j = let () = assert (0 <= j) in let rec aux i k accu = if k=0 then accu else if k land 1 = 0 then aux i (k/2) accu*accu else aux i (k/2) (i*accu*accu) in aux i j 1 let fact i = let rec aux i accu = if i<2 then accu else aux (i-1) (i*accu) in aux i 1 let get_product_image_occ start combine f l = let l = List.sort compare l in let rec aux l old occ accu = match l with | h::t when h=old -> aux t old (1+occ) accu | _ -> begin let accu = combine accu (f occ) in match l with | h::t -> aux t h 1 accu | [] -> accu end in match l with | [] -> 1 | h::t -> aux t h 1 start let get_product_image_occ_2 start combine f l1 l2 = let l1 = List.sort compare l1 in let l2 = List.sort compare l2 in let count_head_and_get_tail l = match l with | [] -> [],0 | h::t -> let rec aux l h occ = match l with | [] -> [],occ | h'::t when h=h' -> aux t h (occ+1) | _ -> l,occ in aux t h 1 in let rec aux l1 l2 accu = match l1,l2 with | h1::_,h2::_ when h1=h2 -> let l1,occ1 = count_head_and_get_tail l1 in let l2,occ2 = count_head_and_get_tail l2 in aux l1 l2 (combine accu (f occ1 occ2)) | h1::_,h2::_ when compare h1 h2 < 0 -> let l1,occ1 = count_head_and_get_tail l1 in aux l1 l2 (combine accu (f occ1 0)) | _::_,_::_ -> let l2,occ2 = count_head_and_get_tail l2 in aux l1 l2 (combine accu (f 0 occ2)) | [],_ | _,[] -> accu in aux l1 l2 start let div2 x = Int64.div x (Int64.add Int64.one Int64.one) let pow64 x n = assert (n >= Int64.zero); let rec aux k accu = if k=Int64.zero then accu else if Int64.logand k Int64.one = Int64.zero then aux (div2 k) (Int64.mul accu accu) else aux (div2 k) (Int64.mul x (Int64.mul accu accu)) in aux n Int64.one let cantor_pairing x y = let s = x + y in (succ s * s)/2 + y let read_input () = let rec parse acc input = match Stream.next input with | '\n' -> acc | c -> parse (Printf.sprintf "%s%c" acc c) input in try let user_input = Stream.of_channel stdin in parse "" user_input with | Stream.Failure -> invalid_arg "Tools.Read_input: cannot read stream" let not_an_id s = (String.length s = 0) || let i = int_of_char s.[0] in (i < 65 || i > 122 || (i > 90 && (i <> 95 || String.length s = 1) && i < 97)) || try String.iter (fun c -> let i = int_of_char c in if i < 48 || i > 122 || (i > 57 && (i < 65 || (i > 90 && i <> 95 && i < 97))) then raise Not_found) s; false with Not_found -> true let array_fold_left_mapi f x a = let y = ref x in let o = Array.init (Array.length a) (fun i -> let (y',out) = f i !y a.(i) in let () = y := y' in out) in (!y,o) let array_map_of_list = let rec fill f i v = function | [] -> () | x :: l -> Array.unsafe_set v i (f x); fill f (succ i) v l in fun f -> function | [] -> [||] | x :: l -> let len = succ (List.length l) in let ans = Array.make len (f x) in let () = fill f 1 ans l in ans let array_rev_of_list = let rec fill out i = function | [] -> assert (i= -1) | h' :: t' -> let () = Array.unsafe_set out i h' in fill out (pred i) t' in function | [] -> [||] | h :: t -> let l = succ (List.length t) in let out = Array.make l h in let () = fill out (l - 2) t in out let array_rev_map_of_list = let rec fill f out i = function | [] -> assert (i= -1) | h' :: t' -> let () = Array.unsafe_set out i (f h') in fill f out (pred i) t' in fun f -> function | [] -> [||] | h :: t -> let l = succ (List.length t) in let out = Array.make l (f h) in let () = fill f out (l - 2) t in out let array_fold_lefti f x a = let y = ref x in let () = Array.iteri (fun i e -> y := f i !y e) a in !y let rec aux_fold_righti i f a x = if i < 0 then x else aux_fold_righti (pred i) f a (f i a.(i) x) let array_fold_righti f a x = aux_fold_righti (Array.length a - 1) f a x let array_fold_left2i f x a1 a2 = let l = Array.length a1 in if l <> Array.length a2 then raise (Invalid_argument "array_fold_left2i") else array_fold_lefti (fun i x e -> f i x e a2.(i)) x a1 let array_filter f a = array_fold_lefti (fun i acc x -> if f i x then i :: acc else acc) [] a let array_min_equal_not_null l1 l2 = if Array.length l1 <> Array.length l2 then None else let rec f j = if j = Array.length l1 then Some ([],[]) else let (nb1,ag1) = l1.(j) in let (nb2,ag2) = l2.(j) in if nb1 <> nb2 then None else if nb1 = 0 then f (succ j) else let rec aux i va out = if i = Array.length l1 then Some out else let (nb1,ag1) = l1.(i) in let (nb2,ag2) = l2.(i) in if nb1 <> nb2 then None else if nb1 > 0 && nb1 < va then aux (succ i) nb1 (ag1,ag2) else aux (succ i) va out in aux (succ j) nb1 (ag1,ag2) in f 0 let array_compare compare a b = let l = Array.length a in let l' = Array.length b in let d = Stdlib.compare l l' in let rec aux_array_compare k = if k >= l then 0 else let o = compare a.(k) b.(k) in if o <> 0 then o else aux_array_compare (succ k) in if d <> 0 then d else aux_array_compare 0 let iteri f i = let rec aux j = if j < i then let () = f j in aux (succ j) in aux 0 let rec recti f x i = if 0 < i then let i' = pred i in recti f (f x i') i' else x let min_pos_int_not_zero (keya,dataa) (keyb,datab) = if keya = 0 then keyb,datab else if keyb = 0 then keya,dataa else if compare keya keyb > 0 then keyb,datab else keya,dataa let max_pos_int_not_zero (keya,dataa) (keyb,datab) = if compare keya keyb > 0 then keya,dataa else keyb,datab let fold_over_permutations f l accu = let rec aux to_do discarded permutation accu = match to_do,discarded with | [],[] -> f permutation accu | [],_::_ -> accu | h::t,_ -> let to_do1 = List.fold_left (fun list a -> a::list) t discarded in let accu = aux to_do1 [] (h::permutation) accu in let accu = aux t (h::discarded) permutation accu in accu in aux l [] [] accu let gcd_2 a b = let rec aux a b = if b = 0 then a else aux b (a mod b) in let a = abs a in let b = abs b in if a < b then aux b a else aux a b let lcm_2 a b = (abs a)*(abs b)/(gcd_2 a b) let lcm list = match list with | [] -> 0 | h::t -> List.fold_left lcm_2 h t let get_interval_list p i j = let add current output = match current with | None -> output | Some p -> p::output in let insert k current = match current with | None -> Some (k,k) | Some (_,j) -> Some (k,j) in let rec aux p k current output = if k<i then add current output else if p k then aux p (k-1) (insert k current) output else aux p (k-1) None (add current output) in aux p j None [] let lowercase = String.lowercase_ascii let capitalize = String.capitalize_ascii let string_split_on_char (delimiter : char) (s : string) : (string * string option) = try let index = String.index s delimiter in let length = String.length s in (String.sub s 0 index, Some (String.sub s (index + 1) (length - index - 1) )) with Not_found -> (s,None) let smash_duplicate_in_ordered_list p l = let () = Format.fprintf Format.std_formatter "DUPL \n" in let rec aux tail nocc current accu = match tail with | [] -> (current,nocc)::accu | (h,n)::t when p h current = 0 -> aux t (n+nocc) current accu | (h,n)::t -> aux t n h ((current,nocc)::accu) in match (List.rev l) with | [] -> [] | (h,n)::t -> aux t n h [] let chop_suffix_or_extension name ext = if Filename.check_suffix name ext then Filename.chop_suffix name ext else Filename.remove_extension name let find_available_name ~already_there name ~facultative ~ext = let ext = match ext with Some e -> e | None -> Filename.extension name in let base = chop_suffix_or_extension name ext in if already_there (base^ext) then let base' = if facultative <> "" then base^"_"^facultative else base in if already_there (base'^ext) then let v = ref 0 in let () = while already_there (base'^"~"^(string_of_int !v)^ext) do incr v; done in base'^"~"^(string_of_int !v)^ext else base'^ext else base^ext let get_ref ref = let i = !ref in let () = ref := i+1 in i let remove_double_elements l = let l = List.sort compare l in let rec aux l accu old = match l, old with | [], _ -> accu | h::t, Some h' when h=h' -> aux t accu old | h::t, (None | Some _) -> aux t (h::accu) (Some h) in aux l [] None
f13354c1c8049ac1c1c81065489f7037dbd2f29a2b148df481f803a4c1d30c57
HaskellZhangSong/Introduction_to_Haskell_2ed_source
TypeFamily2.hs
# LANGUAGE TypeFamilies , MultiParamTypeClasses , FlexibleInstances # type family Elem a :: * type instance Elem [e] = e class (Elem ce ~ e) => Collection e ce where empty :: ce insert :: e -> ce -> ce member :: e -> ce -> Bool
null
https://raw.githubusercontent.com/HaskellZhangSong/Introduction_to_Haskell_2ed_source/140c50fdccfe608fe499ecf2d8a3732f531173f5/C16/TypeFamily2.hs
haskell
# LANGUAGE TypeFamilies , MultiParamTypeClasses , FlexibleInstances # type family Elem a :: * type instance Elem [e] = e class (Elem ce ~ e) => Collection e ce where empty :: ce insert :: e -> ce -> ce member :: e -> ce -> Bool
96bd3cb7e64419dfb350ec270c4a138b70713b05a95e1e3e9cfa18c0415934aa
Clozure/ccl-tests
disassemble.lsp
;-*- Mode: Lisp -*- Author : Created : Sun May 18 20:47:58 2003 Contains : Tests of DISASSEMBLE (in-package :cl-test) (defun disassemble-it (fn) (let (val) (values (notnot (stringp (with-output-to-string (*standard-output*) (setf val (disassemble fn))))) val))) (deftest disassemble.1 (disassemble-it 'car) t nil) (deftest disassemble.2 (disassemble-it (symbol-function 'car)) t nil) (deftest disassemble.3 (disassemble-it '(lambda (x y) (cons y x))) t nil) (deftest disassemble.4 (disassemble-it (eval '(function (lambda (x y) (cons x y))))) t nil) (deftest disassemble.5 (disassemble-it (funcall (compile nil '(lambda () (let ((x 0)) #'(lambda () (incf x))))))) t nil) (deftest disassemble.6 (let ((name 'disassemble.fn.1)) (fmakunbound name) (eval `(defun ,name (x) x)) (disassemble-it name)) t nil) (deftest disassemble.7 (let ((name 'disassemble.fn.2)) (fmakunbound name) (eval `(defun ,name (x) x)) (compile name) (disassemble-it name)) t nil) (deftest disassemble.8 (progn (eval '(defun (setf disassemble-example-fn) (val arg) (setf (car arg) val))) (disassemble-it '(setf disassemble-example-fn))) t nil) (deftest disassemble.9 (progn (eval '(defgeneric disassemble-example-fn2 (x y z))) (disassemble-it 'disassemble-example-fn2)) t nil) (deftest disassemble.10 (progn (eval '(defgeneric disassemble-example-fn3 (x y z))) (eval '(defmethod disassemble-example-fn3 ((x t)(y t)(z t)) (list x y z))) (disassemble-it 'disassemble-example-fn3)) t nil) (deftest disassemble.11 (let ((fn 'disassemble-example-fn4)) (when (fboundp fn) (fmakunbound fn)) (eval `(defun ,fn (x) x)) (let ((is-compiled? (typep (symbol-function fn) 'compiled-function))) (multiple-value-call #'values (disassemble-it fn) (if is-compiled? (notnot (typep (symbol-function fn) 'compiled-function)) (not (typep (symbol-function fn) 'compiled-function)))))) t nil t) ;;; Error tests (deftest disassemble.error.1 (signals-error (disassemble) program-error) t) (deftest disassemble.error.2 (signals-error (disassemble 'car nil) program-error) t) (deftest disassemble.error.3 (check-type-error #'disassemble (typef '(or function symbol (cons (eql setf) (cons symbol null))))) nil)
null
https://raw.githubusercontent.com/Clozure/ccl-tests/0478abddb34dbc16487a1975560d8d073a988060/ansi-tests/disassemble.lsp
lisp
-*- Mode: Lisp -*- Error tests
Author : Created : Sun May 18 20:47:58 2003 Contains : Tests of DISASSEMBLE (in-package :cl-test) (defun disassemble-it (fn) (let (val) (values (notnot (stringp (with-output-to-string (*standard-output*) (setf val (disassemble fn))))) val))) (deftest disassemble.1 (disassemble-it 'car) t nil) (deftest disassemble.2 (disassemble-it (symbol-function 'car)) t nil) (deftest disassemble.3 (disassemble-it '(lambda (x y) (cons y x))) t nil) (deftest disassemble.4 (disassemble-it (eval '(function (lambda (x y) (cons x y))))) t nil) (deftest disassemble.5 (disassemble-it (funcall (compile nil '(lambda () (let ((x 0)) #'(lambda () (incf x))))))) t nil) (deftest disassemble.6 (let ((name 'disassemble.fn.1)) (fmakunbound name) (eval `(defun ,name (x) x)) (disassemble-it name)) t nil) (deftest disassemble.7 (let ((name 'disassemble.fn.2)) (fmakunbound name) (eval `(defun ,name (x) x)) (compile name) (disassemble-it name)) t nil) (deftest disassemble.8 (progn (eval '(defun (setf disassemble-example-fn) (val arg) (setf (car arg) val))) (disassemble-it '(setf disassemble-example-fn))) t nil) (deftest disassemble.9 (progn (eval '(defgeneric disassemble-example-fn2 (x y z))) (disassemble-it 'disassemble-example-fn2)) t nil) (deftest disassemble.10 (progn (eval '(defgeneric disassemble-example-fn3 (x y z))) (eval '(defmethod disassemble-example-fn3 ((x t)(y t)(z t)) (list x y z))) (disassemble-it 'disassemble-example-fn3)) t nil) (deftest disassemble.11 (let ((fn 'disassemble-example-fn4)) (when (fboundp fn) (fmakunbound fn)) (eval `(defun ,fn (x) x)) (let ((is-compiled? (typep (symbol-function fn) 'compiled-function))) (multiple-value-call #'values (disassemble-it fn) (if is-compiled? (notnot (typep (symbol-function fn) 'compiled-function)) (not (typep (symbol-function fn) 'compiled-function)))))) t nil t) (deftest disassemble.error.1 (signals-error (disassemble) program-error) t) (deftest disassemble.error.2 (signals-error (disassemble 'car nil) program-error) t) (deftest disassemble.error.3 (check-type-error #'disassemble (typef '(or function symbol (cons (eql setf) (cons symbol null))))) nil)
fece7fdaa0ef436efc975384787fcb427a6677a5f1c2db7e3637cb0fc83009bf
Gabriella439/suns-search
Index.hs
Copyright 2013 This file is part of the Suns Search Engine The Suns Search Engine is free software : you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation , either version 2 of the License , or ( at your option ) any later version . The Suns Search Engine is distributed in the hope that it will be useful , but WITHOUT ANY WARRANTY ; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the GNU General Public License for more details . You should have received a copy of the GNU General Public License along with the Suns Search Engine . If not , see < / > . This file is part of the Suns Search Engine The Suns Search Engine is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 2 of the License, or (at your option) any later version. The Suns Search Engine is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with the Suns Search Engine. If not, see </>. -} | Top - level module for the @suns - index@ program module Main ( -- * Main main ) where import Control.Applicative ((<$>), (<*>)) import qualified Control.Exception as Ex import Data.Monoid (mconcat) import HSerialize (encodeFile) import Log (initLog, emergency) import Motif (numMotifs, motifsFromDir) import qualified Options.Applicative as O import Indices (primaryIndex, secondaryIndex) options :: O.Parser (String, String, String) options = (,,) <$> (O.strOption $ mconcat [ O.short 'm' , O.long "motifs" , O.metavar "MOTIFDIR" , O.value "motif/" , O.showDefaultWith id , O.completer (O.bashCompleter "directory") , O.help "Input motif directory" ] ) <*> (O.strOption $ mconcat [ O.short 'p' , O.long "pdbs" , O.metavar "PDBDIR" , O.value "pdb/" , O.showDefaultWith id , O.help "Input PDB directory" ] ) <*> (O.strOption $ mconcat [ O.short 'i' , O.long "index" , O.metavar "INDEXDIR" , O.value "index/" , O.showDefaultWith id , O.completer (O.bashCompleter "directory") , O.help "Output index directory" ] ) | Assembles the index , using the motif directory to specify the motifs to recognize and the pdb directory to specify the structures to make searchable . Stores the result in the index directory . recognize and the pdb directory to specify the structures to make searchable. Stores the result in the index directory. -} main :: IO () main = (do (motifDir, pdbDir, indexDir) <- O.execParser $ O.info (O.helper <*> options) $ mconcat [ O.fullDesc , O.header "The Suns structural search engine" , O.progDesc "Indexes PDB structures using the provided motifs" , O.footer "Report bugs to " ] initLog motifs <- motifsFromDir motifDir i2 <- secondaryIndex 0 pdbDir motifs let i1 = primaryIndex (numMotifs motifs) i2 encodeFile (indexDir ++ "/index_primary.dat" ) i1 encodeFile (indexDir ++ "/index_secondary.dat") i2 encodeFile (indexDir ++ "/motifs.dat" ) motifs ) `Ex.catch` (\e -> do emergency $ show (e :: Ex.IOException) Ex.throwIO e )
null
https://raw.githubusercontent.com/Gabriella439/suns-search/59c4cbf109c8d93b3170c3da529121f2b589900c/src/Index.hs
haskell
* Main
Copyright 2013 This file is part of the Suns Search Engine The Suns Search Engine is free software : you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation , either version 2 of the License , or ( at your option ) any later version . The Suns Search Engine is distributed in the hope that it will be useful , but WITHOUT ANY WARRANTY ; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the GNU General Public License for more details . You should have received a copy of the GNU General Public License along with the Suns Search Engine . If not , see < / > . This file is part of the Suns Search Engine The Suns Search Engine is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 2 of the License, or (at your option) any later version. The Suns Search Engine is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with the Suns Search Engine. If not, see </>. -} | Top - level module for the @suns - index@ program module Main main ) where import Control.Applicative ((<$>), (<*>)) import qualified Control.Exception as Ex import Data.Monoid (mconcat) import HSerialize (encodeFile) import Log (initLog, emergency) import Motif (numMotifs, motifsFromDir) import qualified Options.Applicative as O import Indices (primaryIndex, secondaryIndex) options :: O.Parser (String, String, String) options = (,,) <$> (O.strOption $ mconcat [ O.short 'm' , O.long "motifs" , O.metavar "MOTIFDIR" , O.value "motif/" , O.showDefaultWith id , O.completer (O.bashCompleter "directory") , O.help "Input motif directory" ] ) <*> (O.strOption $ mconcat [ O.short 'p' , O.long "pdbs" , O.metavar "PDBDIR" , O.value "pdb/" , O.showDefaultWith id , O.help "Input PDB directory" ] ) <*> (O.strOption $ mconcat [ O.short 'i' , O.long "index" , O.metavar "INDEXDIR" , O.value "index/" , O.showDefaultWith id , O.completer (O.bashCompleter "directory") , O.help "Output index directory" ] ) | Assembles the index , using the motif directory to specify the motifs to recognize and the pdb directory to specify the structures to make searchable . Stores the result in the index directory . recognize and the pdb directory to specify the structures to make searchable. Stores the result in the index directory. -} main :: IO () main = (do (motifDir, pdbDir, indexDir) <- O.execParser $ O.info (O.helper <*> options) $ mconcat [ O.fullDesc , O.header "The Suns structural search engine" , O.progDesc "Indexes PDB structures using the provided motifs" , O.footer "Report bugs to " ] initLog motifs <- motifsFromDir motifDir i2 <- secondaryIndex 0 pdbDir motifs let i1 = primaryIndex (numMotifs motifs) i2 encodeFile (indexDir ++ "/index_primary.dat" ) i1 encodeFile (indexDir ++ "/index_secondary.dat") i2 encodeFile (indexDir ++ "/motifs.dat" ) motifs ) `Ex.catch` (\e -> do emergency $ show (e :: Ex.IOException) Ex.throwIO e )
997f5fe11bf0bab180952dadd7180ab90969e7662178678ba64baeee7514f861
craigfe/diff
diff.ml
open Sink type index = int type 'a command = | Insert of { expected : index; actual : index } * Insert the element [ actual.(actual ) ] at [ expected.(expected ) ] . | Delete of { expected : index } (** Delete the element at [expected.(expected)]. *) | Substitute of { expected : index; actual : index } (** Set [expected.(expected)) := actual.(actual)]. *) let pp_command ppf = function | Insert { expected; actual } -> Format.fprintf ppf "Insert { expected = %d; actual = %d }" expected actual | Delete { expected } -> Format.fprintf ppf "Delete { expected = %d }" expected | Substitute { expected; actual } -> Format.fprintf ppf "Substitute { expected = %d; actual = %d }" expected actual let map_expected f = function | Insert i -> Insert { i with expected = f i.expected } | Delete d -> Delete { expected = f d.expected } | Substitute s -> Substitute { s with expected = f s.expected } let map_actual f = function | Insert i -> Insert { i with actual = f i.actual } | Substitute s -> Substitute { s with actual = f s.actual } | Delete _ as d -> d let insert expected actual = Insert { expected; actual } let delete expected = Delete { expected } let substitute expected actual = Substitute { expected; actual } type ('a, _) typ = | Array : ('a, 'a array) typ | List : ('a, 'a list) typ | String : (char, string) typ module Subarray : sig type 'a t (** Read-only wrapper around an array or a string. Can be {!truncate}d in [O(1)] time. *) val truncate : origin:int -> length:int -> 'a t -> 'a t (** Return a new subarray with smaller bounds than the previous one. *) val empty : _ t val get : 'a t -> int -> 'a val length : 'a t -> int val of_container : ('a, 'container) typ -> 'container -> 'a t end = struct type 'a t = { get : int -> 'a; origin : int; length : int } let truncate ~origin ~length { get; origin = prev_origin; length = prev_length } = if origin < prev_origin || length > prev_length then Fmt.invalid_arg "Cannot expand array during truncation ({ origin = %d; length = %d } \ -> { origin = %d; length = %d })" prev_origin prev_length origin length; { get; origin; length } let index_oob = Format.ksprintf invalid_arg "index out of bounds: %d" let empty = { get = index_oob; origin = 0; length = 0 } let get { get; origin; length } i = if i >= length then index_oob i; get (i + origin) let length { length; _ } = length let of_array a = { get = Array.get a; origin = 0; length = Array.length a } let of_list l = Array.of_list l |> of_array let of_string s = { get = String.get s; origin = 0; length = String.length s } let of_container (type a container) : (a, container) typ -> container -> a t = function | Array -> of_array | List -> of_list | String -> of_string end module Edit_script = struct type 'a t = 'a command list let insert n v t = let rec inner acc n t = match (n, t) with | 0, t -> List.rev_append acc (v :: t) | _, [] -> List.rev (v :: acc) | n, x :: xs -> inner (x :: acc) (n - 1) xs in inner [] n t let delete n t = let rec inner acc n t = match (n, t) with | 0, _ :: xs -> List.rev_append acc xs | n, x :: xs -> inner (x :: acc) (n - 1) xs | _ -> assert false in inner [] n t let substitute n v t = let rec inner acc n t = match (n, t) with | 0, _ :: xs -> List.rev acc @ (v :: xs) | n, x :: xs -> inner (x :: acc) (n - 1) xs | _ -> assert false in inner [] n t let apply (type a container) (typ : (a, container) typ) ~actual:(t_actual : int -> a) (script : a t) (initial : container) : a list = let initial : a list = match typ with | List -> initial | Array -> Array.to_list initial | String -> String.to_list initial in List.fold_left (fun (i, acc) -> function | Insert { expected; actual } -> (i + 1, insert (expected + i) (t_actual actual) acc) | Delete { expected } -> (i - 1, delete (expected + i) acc) | Substitute { expected; actual } -> (i, substitute (expected + i) (t_actual actual) acc)) (0, initial) script |> snd end * Standard dynamic programming algorithm for edit scripts . This works in two phases : 1 . construct a { i cost matrix } of edit distances for each _ prefix _ of the two strings ; 2 . reconstruct an edit script from the cost matrix . The standard algorithm uses a cost matrix of size [ n * m ] . If we only care about edit scripts up to some maximum length [ b ] , the space and time complexity can be reduced to [ O(max ( n , m ) * b ) ] ( assuming an [ O(1 ) ] equality function ) . works in two phases: 1. construct a {i cost matrix} of edit distances for each _prefix_ of the two strings; 2. reconstruct an edit script from the cost matrix. The standard algorithm uses a cost matrix of size [n * m]. If we only care about edit scripts up to some maximum length [b], the space and time complexity can be reduced to [O(max (n, m) * b)] (assuming an [O(1)] equality function). *) * Phase 1 : compute the cost matrix , bottom - up . let construct_grid (type a) ~(equal : a -> a -> bool) (a : a Subarray.t) (b : a Subarray.t) : int Array.Matrix.t = let grid_x_length = Subarray.length a + 1 and grid_y_length = Subarray.length b + 1 in let grid = Array.Matrix.make grid_x_length grid_y_length 0 in let get_grid = Array.Matrix.get grid in for i = 0 to grid_x_length - 1 do for j = 0 to grid_y_length - 1 do let cost = if min i j = 0 then max i j else if equal (Subarray.get a (i - 1)) (Subarray.get b (j - 1)) then get_grid (i - 1, j - 1) else ((i - 1, j), (i, j - 1), (i - 1, j - 1)) |> Triple.map get_grid |> Triple.minimum ~ord:Int.ord |> ( + ) 1 in Array.Matrix.set grid (i, j) cost done done; grid * Phase 2 : reconstruct the edit script from the cost matrix . let reconstruct_edit_script a b grid = Fmt.pr "%a\n" (Array.Matrix.pp (fun ppf -> Format.fprintf ppf "%d")) grid; let get_grid = Array.Matrix.get grid in (* Reverse-engineer the direction and action towards a given cell *) let backtrack (i, j) = let p_sub = (i - 1, j - 1) and p_ins = (i, j - 1) and p_del = (i - 1, j) in if Subarray.get a (i - 1) = Subarray.get b (j - 1) then (p_sub, []) else ( (`Substitute, get_grid p_sub + 1), (`Insert, get_grid p_ins), (`Delete, get_grid p_del) ) |> Triple.minimum_on ~ord:Int.ord snd |> function | `Substitute, _ -> (p_sub, [ substitute (fst p_sub) (snd p_sub) ]) | `Insert, _ -> (p_ins, [ insert (fst p_ins) (snd p_ins) ]) | `Delete, _ -> (p_del, [ delete (fst p_del) ]) in let rec aux acc (x, y) = match (x, y) with | 0, 0 -> acc | i, 0 -> List.init i delete @ acc | 0, j -> List.init j (insert 0) @ acc | pos -> let next_coord, action = backtrack pos in Logs.debug (fun f -> f "%a: %a" Fmt.(Dump.pair int int) pos (Fmt.Dump.list pp_command) action); (aux [@tailcall]) (action @ acc) next_coord in let x_len, y_len = Array.Matrix.dimensions grid in aux [] (x_len - 1, y_len - 1) let levenshtein_dp ~equal (a_origin, b_origin) a b = let grid = construct_grid ~equal a b in reconstruct_edit_script a b grid (* Map the command indices to the true coordinates *) |> List.map (map_expected (( + ) a_origin) >> map_actual (( + ) b_origin)) (** Strip common prefixes and suffixes of the input sequences can be stripped (in linear time) to avoid running the full dynamic programming algorithm on them. *) let strip_common_outer (type a) ~equal ((a : a Subarray.t), (b : a Subarray.t)) = let len_a = Subarray.length a and len_b = Subarray.length b in (* Shift the lower indices upwards until they point to non-equal values in the arrays (or we scan an entire array). *) let rec raise_lower_bound (i, j) = match (i >= len_a, j >= len_b) with | true, true -> `Equal | false, false when equal (Subarray.get a i) (Subarray.get b j) -> raise_lower_bound (i + 1, j + 1) | a_oob, b_oob -> let i = if a_oob then None else Some i in let j = if b_oob then None else Some j in `Non_equal (i, j) in match raise_lower_bound (0, 0) with | `Equal -> `Equal (* The arrays are equal *) One array is a prefix of the other | `Non_equal (None, None) -> `Non_equal ((0, 0), (Subarray.empty, Subarray.empty)) | `Non_equal (None, Some j) -> `Non_equal ( (j, j), (Subarray.empty, Subarray.truncate ~origin:j ~length:(len_b - j) b) ) | `Non_equal (Some i, None) -> `Non_equal ( (i, i), (Subarray.truncate ~origin:i ~length:(len_a - i) a, Subarray.empty) ) | `Non_equal (Some i_origin, Some j_origin) -> ( let rec lower_upper_bound (i, j) = match (i < i_origin, j < j_origin) with | true, true -> `Equal | false, false when equal (Subarray.get a i) (Subarray.get b j) -> lower_upper_bound (i - 1, j - 1) | _ -> `Non_equal (i, j) in match lower_upper_bound (len_a - 1, len_b - 1) with | `Equal -> assert false (* We already decided that the arrays are non-equal *) | `Non_equal (i_last, j_last) -> `Non_equal ( (i_origin, j_origin), ( Subarray.truncate ~origin:i_origin ~length:(i_last - i_origin + 1) a, Subarray.truncate ~origin:j_origin ~length:(j_last - j_origin + 1) b ) ) ) let levenshtein_script (type a container) (typ : (a, container) typ) ~(equal : a -> a -> bool) (a : container) (b : container) : a Edit_script.t = let a, b = (Subarray.of_container typ a, Subarray.of_container typ b) in match strip_common_outer ~equal (a, b) with | `Equal -> [] | `Non_equal (origin, (a, b)) -> levenshtein_dp ~equal origin a b
null
https://raw.githubusercontent.com/craigfe/diff/81c28ef5009bafc65cda762f2382ae3b5037e063/src/diff.ml
ocaml
* Delete the element at [expected.(expected)]. * Set [expected.(expected)) := actual.(actual)]. * Read-only wrapper around an array or a string. Can be {!truncate}d in [O(1)] time. * Return a new subarray with smaller bounds than the previous one. Reverse-engineer the direction and action towards a given cell Map the command indices to the true coordinates * Strip common prefixes and suffixes of the input sequences can be stripped (in linear time) to avoid running the full dynamic programming algorithm on them. Shift the lower indices upwards until they point to non-equal values in the arrays (or we scan an entire array). The arrays are equal We already decided that the arrays are non-equal
open Sink type index = int type 'a command = | Insert of { expected : index; actual : index } * Insert the element [ actual.(actual ) ] at [ expected.(expected ) ] . | Delete of { expected : index } | Substitute of { expected : index; actual : index } let pp_command ppf = function | Insert { expected; actual } -> Format.fprintf ppf "Insert { expected = %d; actual = %d }" expected actual | Delete { expected } -> Format.fprintf ppf "Delete { expected = %d }" expected | Substitute { expected; actual } -> Format.fprintf ppf "Substitute { expected = %d; actual = %d }" expected actual let map_expected f = function | Insert i -> Insert { i with expected = f i.expected } | Delete d -> Delete { expected = f d.expected } | Substitute s -> Substitute { s with expected = f s.expected } let map_actual f = function | Insert i -> Insert { i with actual = f i.actual } | Substitute s -> Substitute { s with actual = f s.actual } | Delete _ as d -> d let insert expected actual = Insert { expected; actual } let delete expected = Delete { expected } let substitute expected actual = Substitute { expected; actual } type ('a, _) typ = | Array : ('a, 'a array) typ | List : ('a, 'a list) typ | String : (char, string) typ module Subarray : sig type 'a t val truncate : origin:int -> length:int -> 'a t -> 'a t val empty : _ t val get : 'a t -> int -> 'a val length : 'a t -> int val of_container : ('a, 'container) typ -> 'container -> 'a t end = struct type 'a t = { get : int -> 'a; origin : int; length : int } let truncate ~origin ~length { get; origin = prev_origin; length = prev_length } = if origin < prev_origin || length > prev_length then Fmt.invalid_arg "Cannot expand array during truncation ({ origin = %d; length = %d } \ -> { origin = %d; length = %d })" prev_origin prev_length origin length; { get; origin; length } let index_oob = Format.ksprintf invalid_arg "index out of bounds: %d" let empty = { get = index_oob; origin = 0; length = 0 } let get { get; origin; length } i = if i >= length then index_oob i; get (i + origin) let length { length; _ } = length let of_array a = { get = Array.get a; origin = 0; length = Array.length a } let of_list l = Array.of_list l |> of_array let of_string s = { get = String.get s; origin = 0; length = String.length s } let of_container (type a container) : (a, container) typ -> container -> a t = function | Array -> of_array | List -> of_list | String -> of_string end module Edit_script = struct type 'a t = 'a command list let insert n v t = let rec inner acc n t = match (n, t) with | 0, t -> List.rev_append acc (v :: t) | _, [] -> List.rev (v :: acc) | n, x :: xs -> inner (x :: acc) (n - 1) xs in inner [] n t let delete n t = let rec inner acc n t = match (n, t) with | 0, _ :: xs -> List.rev_append acc xs | n, x :: xs -> inner (x :: acc) (n - 1) xs | _ -> assert false in inner [] n t let substitute n v t = let rec inner acc n t = match (n, t) with | 0, _ :: xs -> List.rev acc @ (v :: xs) | n, x :: xs -> inner (x :: acc) (n - 1) xs | _ -> assert false in inner [] n t let apply (type a container) (typ : (a, container) typ) ~actual:(t_actual : int -> a) (script : a t) (initial : container) : a list = let initial : a list = match typ with | List -> initial | Array -> Array.to_list initial | String -> String.to_list initial in List.fold_left (fun (i, acc) -> function | Insert { expected; actual } -> (i + 1, insert (expected + i) (t_actual actual) acc) | Delete { expected } -> (i - 1, delete (expected + i) acc) | Substitute { expected; actual } -> (i, substitute (expected + i) (t_actual actual) acc)) (0, initial) script |> snd end * Standard dynamic programming algorithm for edit scripts . This works in two phases : 1 . construct a { i cost matrix } of edit distances for each _ prefix _ of the two strings ; 2 . reconstruct an edit script from the cost matrix . The standard algorithm uses a cost matrix of size [ n * m ] . If we only care about edit scripts up to some maximum length [ b ] , the space and time complexity can be reduced to [ O(max ( n , m ) * b ) ] ( assuming an [ O(1 ) ] equality function ) . works in two phases: 1. construct a {i cost matrix} of edit distances for each _prefix_ of the two strings; 2. reconstruct an edit script from the cost matrix. The standard algorithm uses a cost matrix of size [n * m]. If we only care about edit scripts up to some maximum length [b], the space and time complexity can be reduced to [O(max (n, m) * b)] (assuming an [O(1)] equality function). *) * Phase 1 : compute the cost matrix , bottom - up . let construct_grid (type a) ~(equal : a -> a -> bool) (a : a Subarray.t) (b : a Subarray.t) : int Array.Matrix.t = let grid_x_length = Subarray.length a + 1 and grid_y_length = Subarray.length b + 1 in let grid = Array.Matrix.make grid_x_length grid_y_length 0 in let get_grid = Array.Matrix.get grid in for i = 0 to grid_x_length - 1 do for j = 0 to grid_y_length - 1 do let cost = if min i j = 0 then max i j else if equal (Subarray.get a (i - 1)) (Subarray.get b (j - 1)) then get_grid (i - 1, j - 1) else ((i - 1, j), (i, j - 1), (i - 1, j - 1)) |> Triple.map get_grid |> Triple.minimum ~ord:Int.ord |> ( + ) 1 in Array.Matrix.set grid (i, j) cost done done; grid * Phase 2 : reconstruct the edit script from the cost matrix . let reconstruct_edit_script a b grid = Fmt.pr "%a\n" (Array.Matrix.pp (fun ppf -> Format.fprintf ppf "%d")) grid; let get_grid = Array.Matrix.get grid in let backtrack (i, j) = let p_sub = (i - 1, j - 1) and p_ins = (i, j - 1) and p_del = (i - 1, j) in if Subarray.get a (i - 1) = Subarray.get b (j - 1) then (p_sub, []) else ( (`Substitute, get_grid p_sub + 1), (`Insert, get_grid p_ins), (`Delete, get_grid p_del) ) |> Triple.minimum_on ~ord:Int.ord snd |> function | `Substitute, _ -> (p_sub, [ substitute (fst p_sub) (snd p_sub) ]) | `Insert, _ -> (p_ins, [ insert (fst p_ins) (snd p_ins) ]) | `Delete, _ -> (p_del, [ delete (fst p_del) ]) in let rec aux acc (x, y) = match (x, y) with | 0, 0 -> acc | i, 0 -> List.init i delete @ acc | 0, j -> List.init j (insert 0) @ acc | pos -> let next_coord, action = backtrack pos in Logs.debug (fun f -> f "%a: %a" Fmt.(Dump.pair int int) pos (Fmt.Dump.list pp_command) action); (aux [@tailcall]) (action @ acc) next_coord in let x_len, y_len = Array.Matrix.dimensions grid in aux [] (x_len - 1, y_len - 1) let levenshtein_dp ~equal (a_origin, b_origin) a b = let grid = construct_grid ~equal a b in reconstruct_edit_script a b grid |> List.map (map_expected (( + ) a_origin) >> map_actual (( + ) b_origin)) let strip_common_outer (type a) ~equal ((a : a Subarray.t), (b : a Subarray.t)) = let len_a = Subarray.length a and len_b = Subarray.length b in let rec raise_lower_bound (i, j) = match (i >= len_a, j >= len_b) with | true, true -> `Equal | false, false when equal (Subarray.get a i) (Subarray.get b j) -> raise_lower_bound (i + 1, j + 1) | a_oob, b_oob -> let i = if a_oob then None else Some i in let j = if b_oob then None else Some j in `Non_equal (i, j) in match raise_lower_bound (0, 0) with One array is a prefix of the other | `Non_equal (None, None) -> `Non_equal ((0, 0), (Subarray.empty, Subarray.empty)) | `Non_equal (None, Some j) -> `Non_equal ( (j, j), (Subarray.empty, Subarray.truncate ~origin:j ~length:(len_b - j) b) ) | `Non_equal (Some i, None) -> `Non_equal ( (i, i), (Subarray.truncate ~origin:i ~length:(len_a - i) a, Subarray.empty) ) | `Non_equal (Some i_origin, Some j_origin) -> ( let rec lower_upper_bound (i, j) = match (i < i_origin, j < j_origin) with | true, true -> `Equal | false, false when equal (Subarray.get a i) (Subarray.get b j) -> lower_upper_bound (i - 1, j - 1) | _ -> `Non_equal (i, j) in match lower_upper_bound (len_a - 1, len_b - 1) with | `Equal -> | `Non_equal (i_last, j_last) -> `Non_equal ( (i_origin, j_origin), ( Subarray.truncate ~origin:i_origin ~length:(i_last - i_origin + 1) a, Subarray.truncate ~origin:j_origin ~length:(j_last - j_origin + 1) b ) ) ) let levenshtein_script (type a container) (typ : (a, container) typ) ~(equal : a -> a -> bool) (a : container) (b : container) : a Edit_script.t = let a, b = (Subarray.of_container typ a, Subarray.of_container typ b) in match strip_common_outer ~equal (a, b) with | `Equal -> [] | `Non_equal (origin, (a, b)) -> levenshtein_dp ~equal origin a b
0261231eeaca0f825e49d8f92cf071c143dd287d3c2500374967377f11042773
bobbae/gosling-emacs
unipress.ml
(defun (exit-emacs-hook (novalue))) (defun (new-exit-emacs (exit-emacs-hook) (exit-emacs))) (defun (new-write-file-exit (write-modified-files) (new-exit-emacs))) (defun (global-rebind new-function old-function default-binding (setq new-function (arg 1 ": new function: ")) (setq old-function (arg 2 ": old function: ")) (if (= (nargs) 3) (setq default-binding (arg 3)) (setq default-binding 0) ) (save-window-excursion did-bind (setq did-bind 0) (temp-use-buffer "Help") (describe-bindings) (beginning-of-file) (set-mark) (next-line) (next-line) (next-line) (erase-region) (end-of-file) (set-mark) (error-occured (search-reverse "Local Bindings") (beginning-of-line) (previous-line) (erase-region) ) (beginning-of-file) (while (! (error-occured (search-forward (concat " " old-function)))) (if (eolp) (save-excursion (beginning-of-line) (set-mark) (search-forward " ") (backward-character) (bind-to-key new-function (region-to-control-string)) (setq did-bind 1) ) ) ) (if (& default-binding (! did-bind)) (bind-to-key new-function default-binding) ) ) ) ) (defun (region-to-control-string return-string (setq return-string "") (save-restriction (narrow-region) (beginning-of-file) (while (! (eobp)) (if (= (following-char) '^') (progn (forward-character) (setq return-string (concat return-string (char-to-string (- (following-char) 64)))) ) (looking-at "ESC") (setq return-string (concat return-string "\e")) (setq return-string (concat return-string (char-to-string (following-char)))) ) (if (error-occured (search-forward "-")) (end-of-file) ) ) return-string ) ) ) (global-rebind "new-exit-emacs" "exit-emacs") (global-rebind "new-write-file-exit" "write-file-exit") (defun (line-to-bottom-of-window (push-mark)(set-mark)(line-to-top-of-window) (provide-prefix-argument (- (window-height) 1) (scroll-one-line-down)) (exchange-dot-and-mark)(pop-mark) ) ) (defun (line-number ln-dot (setq ln-dot (+ (dot))) (save-excursion ln-n (setq ln-n 1) (beginning-of-file) (end-of-line) (while (& (! (eobp)) (< (+ (dot)) ln-dot)) (next-line)(end-of-line) (setq ln-n (+ 1 ln-n)) ) ln-n ) ) ) (defun (goto-line (beginning-of-file) (provide-prefix-argument (- (arg 1) 1) (next-line)) ) ) (declare-buffer-specific mark1 mark2 mark3) (setq-default mark1 -1) (setq-default mark2 -1) (setq-default mark3 -1) (defun (push-mark (setq mark3 mark2) (setq mark2 mark1) (setq mark1 (if (error-occured (mark)) -1 (mark))) ) ) (defun (pop-mark (if (>= mark1 0) (progn (exchange-dot-and-mark) (goto-character mark1) (exchange-dot-and-mark) (setq mark1 mark2) (setq mark2 mark3) ) ) ) ) (defun (buffer-exists (save-window-excursion (! (error-occured (use-old-buffer (arg 1)))) ) ) ) (defun (abs abs-arg (setq abs-arg (arg 1)) (if (< abs-arg 0) (- 0 abs-arg) abs-arg ) ) ) (defun (max max-arg1 max-arg2 (setq max-arg1 (arg 1)) (setq max-arg2 (arg 2)) (if (> max-arg1 max-arg2) max-arg1 max-arg2 ) ) ) (defun (min min-arg1 min-arg2 (setq min-arg1 (arg 1)) (setq min-arg2 (arg 2)) (if (< min-arg1 min-arg2) min-arg1 min-arg2 ) ) ) (defun (push-back-string pbs-n pbs-s (setq pbs-s (arg 1 ": push-back-string ")) (setq pbs-n (length pbs-s)) (while (> pbs-n 0) (push-back-character (string-to-char (substr pbs-s pbs-n 1))) (setq pbs-n (- pbs-n 1)) ) ) ) (defun (is-top-window (= (current-window) 1) ) ) (defun (top-window (while (! (is-top-window)) (next-window) ) (novalue) ) ) (defun (goto-window gw-n (setq gw-n (arg 1 ": goto-window ")) (top-window) (while (> gw-n 1) (next-window) (if (is-top-window) (progn (previous-window) (setq gw-n 1) ) (setq gw-n (- gw-n 1)) ) ) (novalue) ) ) (defun (number-of-windows now-n (save-window-excursion (setq now-n 1) (goto-window 2) (while (! (is-top-window)) (setq now-n (+ now-n 1)) (next-window) ) ) now-n ) ) (defun (path-of dir-name epath po-done po-colon file-name (setq file-name (arg 1 ": path-of ")) (setq epath (concat ".:" (getenv "EPATH") ":")) (setq po-done 0) (while (& (= po-done 0) (!= epath "")) (setq po-colon (index epath ":" 1)) (setq dir-name (substr epath 1 (- po-colon 1))) (setq dir-name (concat dir-name "/" file-name)) (setq epath (substr epath (+ po-colon 1) (- (length epath) po-colon))) (setq po-done (file-exists dir-name)) ) (if (= po-done 0) (error-message ": path-of " file-name " not found") dir-name ) ) )
null
https://raw.githubusercontent.com/bobbae/gosling-emacs/8fdda532abbffb0c952251a0b5a4857e0f27495a/maclib/unipress.ml
ocaml
(defun (exit-emacs-hook (novalue))) (defun (new-exit-emacs (exit-emacs-hook) (exit-emacs))) (defun (new-write-file-exit (write-modified-files) (new-exit-emacs))) (defun (global-rebind new-function old-function default-binding (setq new-function (arg 1 ": new function: ")) (setq old-function (arg 2 ": old function: ")) (if (= (nargs) 3) (setq default-binding (arg 3)) (setq default-binding 0) ) (save-window-excursion did-bind (setq did-bind 0) (temp-use-buffer "Help") (describe-bindings) (beginning-of-file) (set-mark) (next-line) (next-line) (next-line) (erase-region) (end-of-file) (set-mark) (error-occured (search-reverse "Local Bindings") (beginning-of-line) (previous-line) (erase-region) ) (beginning-of-file) (while (! (error-occured (search-forward (concat " " old-function)))) (if (eolp) (save-excursion (beginning-of-line) (set-mark) (search-forward " ") (backward-character) (bind-to-key new-function (region-to-control-string)) (setq did-bind 1) ) ) ) (if (& default-binding (! did-bind)) (bind-to-key new-function default-binding) ) ) ) ) (defun (region-to-control-string return-string (setq return-string "") (save-restriction (narrow-region) (beginning-of-file) (while (! (eobp)) (if (= (following-char) '^') (progn (forward-character) (setq return-string (concat return-string (char-to-string (- (following-char) 64)))) ) (looking-at "ESC") (setq return-string (concat return-string "\e")) (setq return-string (concat return-string (char-to-string (following-char)))) ) (if (error-occured (search-forward "-")) (end-of-file) ) ) return-string ) ) ) (global-rebind "new-exit-emacs" "exit-emacs") (global-rebind "new-write-file-exit" "write-file-exit") (defun (line-to-bottom-of-window (push-mark)(set-mark)(line-to-top-of-window) (provide-prefix-argument (- (window-height) 1) (scroll-one-line-down)) (exchange-dot-and-mark)(pop-mark) ) ) (defun (line-number ln-dot (setq ln-dot (+ (dot))) (save-excursion ln-n (setq ln-n 1) (beginning-of-file) (end-of-line) (while (& (! (eobp)) (< (+ (dot)) ln-dot)) (next-line)(end-of-line) (setq ln-n (+ 1 ln-n)) ) ln-n ) ) ) (defun (goto-line (beginning-of-file) (provide-prefix-argument (- (arg 1) 1) (next-line)) ) ) (declare-buffer-specific mark1 mark2 mark3) (setq-default mark1 -1) (setq-default mark2 -1) (setq-default mark3 -1) (defun (push-mark (setq mark3 mark2) (setq mark2 mark1) (setq mark1 (if (error-occured (mark)) -1 (mark))) ) ) (defun (pop-mark (if (>= mark1 0) (progn (exchange-dot-and-mark) (goto-character mark1) (exchange-dot-and-mark) (setq mark1 mark2) (setq mark2 mark3) ) ) ) ) (defun (buffer-exists (save-window-excursion (! (error-occured (use-old-buffer (arg 1)))) ) ) ) (defun (abs abs-arg (setq abs-arg (arg 1)) (if (< abs-arg 0) (- 0 abs-arg) abs-arg ) ) ) (defun (max max-arg1 max-arg2 (setq max-arg1 (arg 1)) (setq max-arg2 (arg 2)) (if (> max-arg1 max-arg2) max-arg1 max-arg2 ) ) ) (defun (min min-arg1 min-arg2 (setq min-arg1 (arg 1)) (setq min-arg2 (arg 2)) (if (< min-arg1 min-arg2) min-arg1 min-arg2 ) ) ) (defun (push-back-string pbs-n pbs-s (setq pbs-s (arg 1 ": push-back-string ")) (setq pbs-n (length pbs-s)) (while (> pbs-n 0) (push-back-character (string-to-char (substr pbs-s pbs-n 1))) (setq pbs-n (- pbs-n 1)) ) ) ) (defun (is-top-window (= (current-window) 1) ) ) (defun (top-window (while (! (is-top-window)) (next-window) ) (novalue) ) ) (defun (goto-window gw-n (setq gw-n (arg 1 ": goto-window ")) (top-window) (while (> gw-n 1) (next-window) (if (is-top-window) (progn (previous-window) (setq gw-n 1) ) (setq gw-n (- gw-n 1)) ) ) (novalue) ) ) (defun (number-of-windows now-n (save-window-excursion (setq now-n 1) (goto-window 2) (while (! (is-top-window)) (setq now-n (+ now-n 1)) (next-window) ) ) now-n ) ) (defun (path-of dir-name epath po-done po-colon file-name (setq file-name (arg 1 ": path-of ")) (setq epath (concat ".:" (getenv "EPATH") ":")) (setq po-done 0) (while (& (= po-done 0) (!= epath "")) (setq po-colon (index epath ":" 1)) (setq dir-name (substr epath 1 (- po-colon 1))) (setq dir-name (concat dir-name "/" file-name)) (setq epath (substr epath (+ po-colon 1) (- (length epath) po-colon))) (setq po-done (file-exists dir-name)) ) (if (= po-done 0) (error-message ": path-of " file-name " not found") dir-name ) ) )
2eccff97056aa2ff26c19af39246a05cdfcec42ae23d6759d2965e8d0e4037de
deadcode/Learning-CL--David-Touretzky
6.13.lisp
(format t "~s = ~s~%" '(INTERSECTION '(LET US SEE) nil) (INTERSECTION '(LET US SEE) nil))
null
https://raw.githubusercontent.com/deadcode/Learning-CL--David-Touretzky/b4557c33f58e382f765369971e6a4747c27ca692/Chapter%206/6.13.lisp
lisp
(format t "~s = ~s~%" '(INTERSECTION '(LET US SEE) nil) (INTERSECTION '(LET US SEE) nil))
f544e3fc6be9af4a8f7040ebd63aa0fb10fc9da649ee9c57c3917c885e00091d
ageneau/clchess
views.cljs
(ns clchess.views (:require [reagent.core :as reagent :refer [atom]] [re-frame.core :refer [subscribe dispatch dispatch-sync]] [clchess.utils :as utils] [clchess.board :as board] [clchess.theme :as theme] [clchess.widgets :as widgets] [clchess.specs.theme :as stheme] [taoensso.timbre :as log])) (defn open-file [] (let [selector (utils/by-id "file-selector")] (log/debug "Selector: " selector) (.click selector))) (defn file-input [] (let [selector @(subscribe [:file-selector/changed]) accept (:accept selector) action (:action selector) value (reagent/atom "")] (log/debug "file-input: " selector) [:input { ;; FIXME: Unknown prop `field` on <input> tag ;; :field :file :type :file :accept accept :id "file-selector" :value @value :on-click #(reset! value "") :on-change #(dispatch [:file/changed action (-> % .-target .-value)]) }])) (defn study-overboard [] [:div.lichess_overboard.study_overboard [:a.close.icon {:data-icon "L"}] [:h2 "Edit study"] [:form.material.form [:div.game.form-group [:input#study-name {:required "", :minlength "3", :maxlength "100"}] [:label.control-label {:for "study-name"} "Name"] [:i.bar]] [:div.game.form-group [:select#study-visibility [:option {:value "public"} "Public"] [:option {:value "private"} "Invite only"]] [:label.control-label {:for "study-visibility"} "Visibility"] [:i.bar]] [:div [:div.game.form-group.half [:select#study-computer [:option {:value "everyone"} "Everyone"] [:option {:value "nobody"} "Nobody"] [:option {:value "owner"} "Only me"] [:option {:value "contributor"} "Contributors"]] [:label.control-label {:for "study-computer"} "Computer analysis"] [:i.bar]] [:div.game.form-group.half [:select#study-explorer [:option {:value "everyone"} "Everyone"] [:option {:value "nobody"} "Nobody"] [:option {:value "owner"} "Only me"] [:option {:value "contributor"} "Contributors"]] [:label.control-label {:for "study-explorer"} "Opening explorer"] [:i.bar]]] [:div.button-container [:button.submit.button {:type "submit"} "Save"]]] [:form.delete_study {:action "/study/JsKHdGfK/delete", :method "post"} [:button.button.frameless "Delete study"]]]) (defn chessboard [] [:div {:class "lichess_board_wrap cg-512"} [:div {:class "lichess_board standard"} [:div {:id "chessground-container"}] ;; [study-overboard] ]]) (defn top-menu [] [:div {:class "hover" :id "topmenu"} [:section [:a "File"] [:div [:a {:on-click #(dispatch [:menu/open-db])} "Open database"] [:a {:on-click #(dispatch [:menu/load-pgn])} "Load pgn"] [:a {:on-click #(dispatch [:menu/quit])} "Quit"]]] [:section [:a "View"] [:div [:a {:on-click #(dispatch-sync [:view/toggle-fullscreen])} "Full screen"]]] [:section [:a "Board"] [:div [:a {:on-click #(dispatch [:menu/reset-board])} "Reset board"]]]]) (defn top-section [theme] (log/debug "top section:" (::stheme/is-2d theme)) [:div {:class (if (::stheme/is-2d theme) "is2d" "is3d") :id "top"} [top-menu] [widgets/hamburger] [theme/theme-selector theme] [widgets/volume-control 80 false]]) (defn clchess-app [] (let [theme (subscribe [:theme]) moves (subscribe [:game/moves])] [:div {:id "page-container"} [top-section @theme] [:div {:class (if (::stheme/is-2d @theme) "is2d" "is3d") :id "content"} [:div.lichess_game [board/board-outer] [:div.lichess_ground [widgets/ceval-box] [:div.areplay [widgets/opening-box] [widgets/replay @moves]] [widgets/explorer-box] [widgets/game-controls]]]] [file-input] ;; [widgets/tip] ;; [widgets/context-menu] ]))
null
https://raw.githubusercontent.com/ageneau/clchess/4680d47d2bd919f5bf5eb820deaf97b402de3592/src/cljs/clchess/views.cljs
clojure
FIXME: Unknown prop `field` on <input> tag :field :file [study-overboard] [widgets/tip] [widgets/context-menu]
(ns clchess.views (:require [reagent.core :as reagent :refer [atom]] [re-frame.core :refer [subscribe dispatch dispatch-sync]] [clchess.utils :as utils] [clchess.board :as board] [clchess.theme :as theme] [clchess.widgets :as widgets] [clchess.specs.theme :as stheme] [taoensso.timbre :as log])) (defn open-file [] (let [selector (utils/by-id "file-selector")] (log/debug "Selector: " selector) (.click selector))) (defn file-input [] (let [selector @(subscribe [:file-selector/changed]) accept (:accept selector) action (:action selector) value (reagent/atom "")] (log/debug "file-input: " selector) [:input { :type :file :accept accept :id "file-selector" :value @value :on-click #(reset! value "") :on-change #(dispatch [:file/changed action (-> % .-target .-value)]) }])) (defn study-overboard [] [:div.lichess_overboard.study_overboard [:a.close.icon {:data-icon "L"}] [:h2 "Edit study"] [:form.material.form [:div.game.form-group [:input#study-name {:required "", :minlength "3", :maxlength "100"}] [:label.control-label {:for "study-name"} "Name"] [:i.bar]] [:div.game.form-group [:select#study-visibility [:option {:value "public"} "Public"] [:option {:value "private"} "Invite only"]] [:label.control-label {:for "study-visibility"} "Visibility"] [:i.bar]] [:div [:div.game.form-group.half [:select#study-computer [:option {:value "everyone"} "Everyone"] [:option {:value "nobody"} "Nobody"] [:option {:value "owner"} "Only me"] [:option {:value "contributor"} "Contributors"]] [:label.control-label {:for "study-computer"} "Computer analysis"] [:i.bar]] [:div.game.form-group.half [:select#study-explorer [:option {:value "everyone"} "Everyone"] [:option {:value "nobody"} "Nobody"] [:option {:value "owner"} "Only me"] [:option {:value "contributor"} "Contributors"]] [:label.control-label {:for "study-explorer"} "Opening explorer"] [:i.bar]]] [:div.button-container [:button.submit.button {:type "submit"} "Save"]]] [:form.delete_study {:action "/study/JsKHdGfK/delete", :method "post"} [:button.button.frameless "Delete study"]]]) (defn chessboard [] [:div {:class "lichess_board_wrap cg-512"} [:div {:class "lichess_board standard"} [:div {:id "chessground-container"}] ]]) (defn top-menu [] [:div {:class "hover" :id "topmenu"} [:section [:a "File"] [:div [:a {:on-click #(dispatch [:menu/open-db])} "Open database"] [:a {:on-click #(dispatch [:menu/load-pgn])} "Load pgn"] [:a {:on-click #(dispatch [:menu/quit])} "Quit"]]] [:section [:a "View"] [:div [:a {:on-click #(dispatch-sync [:view/toggle-fullscreen])} "Full screen"]]] [:section [:a "Board"] [:div [:a {:on-click #(dispatch [:menu/reset-board])} "Reset board"]]]]) (defn top-section [theme] (log/debug "top section:" (::stheme/is-2d theme)) [:div {:class (if (::stheme/is-2d theme) "is2d" "is3d") :id "top"} [top-menu] [widgets/hamburger] [theme/theme-selector theme] [widgets/volume-control 80 false]]) (defn clchess-app [] (let [theme (subscribe [:theme]) moves (subscribe [:game/moves])] [:div {:id "page-container"} [top-section @theme] [:div {:class (if (::stheme/is-2d @theme) "is2d" "is3d") :id "content"} [:div.lichess_game [board/board-outer] [:div.lichess_ground [widgets/ceval-box] [:div.areplay [widgets/opening-box] [widgets/replay @moves]] [widgets/explorer-box] [widgets/game-controls]]]] [file-input] ]))
c7b7fb02586df155f41620ca3d442edfd66a81c824399da615f110729688496d
iovxw/tg-rss-bot
core.clj
(ns tg-rss-bot.core (:require [tg-rss-bot.tgapi :as tgapi] [clojure.tools.logging :as log] [clojure.java.jdbc :as jdbc] [clojure.string :as string] [clj-http.client :as client] [clojure.core.match :refer [match]] [feedparser-clj.core :as feedparser]) (:import [java.io InputStreamReader BufferedReader ByteArrayInputStream] [java.net URLEncoder]) (:gen-class)) (def db {:classname "org.sqlite.JDBC" :subprotocol "sqlite" :subname "database.db"}) (defn init-db [db] (jdbc/execute! db ["CREATE TABLE IF NOT EXISTS rss ( url VARCHAR, title VARCHAR, hash_list VARCHAR, err_count INTEGER)"]) (jdbc/execute! db ["CREATE TABLE IF NOT EXISTS subscribers ( rss VARCHAR, subscriber INTEGER)"])) (defn updates-seq ([bot] (updates-seq bot 0)) ([bot offset] (let [updates (try (tgapi/get-updates bot :offset offset :timeout 120) (catch Exception e (log/warnf "Get updates fail: %s" (.getMessage e)) [])) new-offset (if (not= (count updates) 0) (-> updates last :update_id inc) updates 数量为 0,可能获取失败,使用旧的 offset (lazy-cat updates (updates-seq bot new-offset))))) (defn has-row? [db table query & value] (let [query (format "SELECT COUNT(*) FROM %s WHERE %s" table query) result (jdbc/query db (cons query value))] result like ( { : count ( * ) 1 } ) (not (zero? ((keyword "count(*)") (first result)))))) (defn split-message [text max-len] (let [text-len (count text)] (loop [begin 0, offset 0, result []] (let [n (if-let [n (string/index-of text "\n" offset)] n text-len) line-len (- n offset) now-len (- n begin)] ; 当前所选定的长度 (if (<= (- text-len begin) max-len) ; 剩下的长度小于最大长度 (conj result (subs text begin text-len)) ; DONE (if (> line-len max-len) ; 单行大于最大长度,进行行内切分 (let [split-len (- max-len (- offset begin)) split-point (+ offset split-len)] (recur split-point split-point (conj result (subs text begin split-point)))) (if (> now-len max-len) 这里的 ( dec offset ) 是为了去掉最后一个换行 (conj result (subs text begin (dec offset)))) (recur begin (inc n) result)))))))) (defn send-message [bot chat-id text & opts] (if (<= (count text) 4096) (apply tgapi/send-message bot chat-id text opts) (let [messages (split-message text 1024)] (doseq [msg messages] (apply tgapi/send-message bot chat-id msg opts))))) (def status-code {100 "Continue" 101 "Switching Protocols" 102 "Processing" 200 "OK" 201 "Created" 202 "Accepted" 203 "Non-Authoritative Information" 204 "No Content" 205 "Reset Content" 206 "Partial Content" 207 "Multi-Status" 208 "Already Reported" 226 "IM Used" 300 "Multiple Choices" 301 "Moved Permanently" 302 "Found" 303 "See Other" 304 "Not Modified" 305 "Use Proxy" 306 "Switch Proxy" 307 "Temporary Redirect" 308 "Permanent Redirect" 400 "Bad Request" 401 "Unauthorized" 402 "Payment Required" 403 "Forbidden" 404 "Not Found" 405 "Method Not Allowed" 406 "Not Acceptable" 407 "Proxy Authentication Required" 408 "Request Timeout" 409 "Conflict" 410 "Gone" 411 "Length Required" 412 "Precondition Failed" 413 "Payload Too Large" 414 "URI Too Long" 415 "Unsupported Media Type" 416 "Range Not Satisfiable" 417 "Expectation Failed" 418 "I'm a teapot" 421 "Misdirected Request" 422 "Unprocessable Entity" 423 "Locked" 424 "Failed Dependency" 426 "Upgrade Required" 428 "Precondition Required" 429 "Too Many Requests" 431 "Request Header Fields Too Large" 451 "Unavailable For Legal Reasons" 500 "Internal Server Error" 501 "Not Implemented" 502 "Bad Gateway" 503 "Service Unavailable" 504 "Gateway Timeout" 505 "HTTP Version Not Supported" 506 "Variant Also Negotiates" 507 "Insufficient Storage" 508 "Loop Detected" 510 "Not Extended" 511 "Network Authentication Required" ; nginx 444 "No Response" 495 "SSL Certificate Error" 496 "SSL Certificate Required" 497 "HTTP Request Sent to HTTPS Port" 499 "Client Closed Request" CloudFlare 520 "Unknown Error" 521 "Web Server Is Down" 522 "Connection Timed Out" 523 "Origin Is Unreachable" 524 "A Timeout Occurred" 525 "SSL Handshake Failed" 526 "Invalid SSL Certificate"}) (defn remove-unserializable-chars [b] (let [declaration (.readLine (BufferedReader. (InputStreamReader. (ByteArrayInputStream. b) "UTF-8"))) encoding (or (second (re-find #"^<\?[^>]*encoding=[\'\"]([^\"\'>]+)[\'\"][^>]*\?>" declaration)) "UTF-8") s (String. b encoding) r (string/replace s #"[\x00-\x08\x0B-\x0C\x0E-\x1F]" "") b (.getBytes r encoding)] (ByteArrayInputStream. b))) (defn parse-feed [url] (try fix ParsingFeedException ;; (let [resp (client/get url {:as :byte-array :headers {"User-Agent" (str "Mozilla/5.0 (X11; Linux x86_64) " "AppleWebKit/537.36 (KHTML, like Gecko) " "Chrome/52.0.2743.82 Safari/537.36")}})] (with-open [stream (remove-unserializable-chars (:body resp))] (feedparser/parse-feed stream))) (catch java.net.UnknownHostException _ (throw (ex-info "未知服务器地址" {:type :rss-exception}))) (catch clojure.lang.ExceptionInfo e (throw (ex-info (let [code (:status (ex-data e))] (if code (format "HTTP %s: %s" code (get status-code code)) (.getMessage e))) {:type :rss-exception}))) (catch Exception e (throw (ex-info (.getMessage e) {:type :rss-exception}))))) (defn format-title [title] (when title (string/replace title #"(?:^[\s\n]*)|(?:[\s\n]*$)" ""))) (defn escape-title [title] (when title (string/escape title {\< "&lt;", \> "&gt;", \& "&amp;"}))) (defn entry-hash [entry] (hash (str (:link entry) (:title entry)))) (defn gen-rss-hash-list [rss] (string/join " " (map entry-hash (:entries rss)))) (defn sub-rss [bot db chat-id url subscriber] (if-not (has-row? db "subscribers" "rss = ? AND subscriber = ?" url subscriber) (let [msg (tgapi/send-message bot chat-id "拉取 RSS 信息中,请稍候") msg-id (:message_id msg) rss (try (parse-feed url) (catch Exception e (tgapi/edit-message-text bot chat-id msg-id (format (str "订阅失败: %s\n" "请 [检查 RSS 合法性]() " "(更多帮助请查看 /start)") (.getMessage e) (URLEncoder/encode url "UTF-8")) :parse-mode "Markdown" :disable-web-page-preview true) (log/warnf "sub-rss: %s, %s" url (.getMessage e)))) title (format-title (:title rss))] (when rss (jdbc/insert! db :subscribers {:rss url :subscriber subscriber}) (tgapi/edit-message-text bot chat-id msg-id (format "《<a href=\"%s\">%s</a>》订阅成功" url (escape-title title)) :parse-mode "HTML" :disable-web-page-preview true) ;; 检查是否为第一次订阅 (when-not (has-row? db "rss" "url = ?" url) (jdbc/insert! db :rss {:url url :title title :hash_list (gen-rss-hash-list rss) :err_count 0})))) (tgapi/send-message bot chat-id "订阅失败,已经订阅过的 RSS"))) (defn get-rss-title [db url] (-> (jdbc/query db ["SELECT title FROM rss WHERE url = ?" url]) (first) (:title))) (defn unsub-rss [bot db chat-id url subscriber] (let [result (jdbc/execute! db ["DELETE FROM subscribers WHERE rss = ? AND subscriber = ?" url subscriber])] (if (>= (first result) 1) (let [title (get-rss-title db url)] (when-not (has-row? db "subscribers" "rss = ?" url) ;; 最后一个订阅者退订,删除这个 RSS (jdbc/delete! db :rss ["url = ?" url])) (tgapi/send-message bot chat-id (format "《<a href=\"%s\">%s</a>》退订成功" url (escape-title title)) :parse-mode "HTML" :disable-web-page-preview true)) (tgapi/send-message bot chat-id "退订失败,没有订阅过的 RSS")))) (defn get-sub-list [bot db chat-id subscriber raw?] (let [result (jdbc/query db ["SELECT rss FROM subscribers WHERE subscriber = ?" subscriber])] (if-not (= (count result) 0) (if raw? (send-message bot chat-id (reduce #(format "%s\n%s: %s" %1 (get-rss-title db (:rss %2)) (:rss %2)) "订阅列表:" result) :disable-web-page-preview true) (send-message bot chat-id (reduce #(format "%s\n<a href=\"%s\">%s</a>" %1 (:rss %2) (escape-title (get-rss-title db (:rss %2)))) "订阅列表:" result) :parse-mode "HTML" :disable-web-page-preview true)) (tgapi/send-message bot chat-id "订阅列表为空")))) (defmacro match-args [args & body] `(match (when ~args (string/split ~args #" ")) ~@body)) (defmacro if-not-let ([bindings then] `(if-not-let ~bindings nil ~then)) ([bindings then else & oldform] `(if-let ~bindings ~else ~then ~@oldform))) (defn parse-int [s] (try (Integer. s) (catch Exception _ nil))) (defn verify-channel [bot chat-id channel-id user-id] (let [msg (tgapi/send-message bot chat-id "正在验证 Channel") msg-id (:message_id msg) channel-id (if (parse-int channel-id) (if (not (string/starts-with? channel-id "-100")) (str "-100" channel-id) channel-id) (if (not (string/starts-with? channel-id "@")) (str "@" channel-id) channel-id))] (if-not-let [channel-info (try (tgapi/get-chat bot channel-id) (catch Exception e ; Bad Request: chat not found (when (-> (ex-data e) :status (not= 400)) (throw e))))] (do (tgapi/edit-message-text bot chat-id msg-id "无法找到目标 Channel") nil) (if-not (= (:type channel-info) "channel") (do (tgapi/edit-message-text bot chat-id msg-id "目标需为 Channel") nil) (if-not-let [channel-admins (try (tgapi/get-chat-admins bot channel-id) (catch Exception e ; Bad Request: Channel members are unavailable (when (-> (ex-data e) :status (not= 400)) (throw e))))] (do (tgapi/edit-message-text bot chat-id msg-id "请先将本 Bot 加入目标 Channel 并设为管理员") nil) (if-not (some #(= (get-in % [:user :id]) (:id bot)) channel-admins) (do (tgapi/edit-message-text bot chat-id msg-id "请将本 Bot 设为目标 Channel 管理员") nil) (if-not (some #(= (get-in % [:user :id]) user-id) channel-admins) (do (tgapi/edit-message-text bot chat-id msg-id "该命令只能由 Channel 管理员使用") nil) (:id channel-info)))))))) (defn handle-update [bot db update] (try (when-let [message (:message update)] (when-let [text (:text message)] (let [[cmd args] (tgapi/parse-cmd bot text)] (case cmd "start" (tgapi/send-message bot (get-in message [:chat :id]) (str "命令列表:\n" "/rss - 显示当前订阅的 RSS 列表,可以加 raw 参数显示原始链接\n" "/sub - 命令后加要订阅的 RSS 链接,订阅一条 RSS\n" "/unsub - 命令后加要退订的 RSS 链接,退订一条 RSS\n" "本项目源码:\n" "-rss-bot\n" "注: 可使用 [Feedburner](/) 之类服务来解决网络问题\n" "如有任何疑问请联系作者 @iovxw") :parse-mode "Markdown") "rss" (match-args args nil (get-sub-list bot db (get-in message [:chat :id]) (get-in message [:chat :id]) false) ["raw"] (get-sub-list bot db (get-in message [:chat :id]) (get-in message [:chat :id]) true) [channel-id] (if-let [channel-id (verify-channel bot (get-in message [:chat :id]) channel-id (get-in message [:from :id]))] (get-sub-list bot db (get-in message [:chat :id]) channel-id false)) [channel-id "raw"] (if-let [channel-id (verify-channel bot (get-in message [:chat :id]) channel-id (get-in message [:from :id]))] (get-sub-list bot db (get-in message [:chat :id]) channel-id true)) :else (tgapi/send-message bot (get-in message [:chat :id]) "使用方法: /rss <Channel ID> <raw>")) "sub" (match-args args [url] (sub-rss bot db (get-in message [:chat :id]) url (get-in message [:chat :id])) [channel-id url] (if-let [channel-id (verify-channel bot (get-in message [:chat :id]) channel-id (get-in message [:from :id]))] (sub-rss bot db (get-in message [:chat :id]) url channel-id)) :else (tgapi/send-message bot (get-in message [:chat :id]) "使用方法: /sub <Channel ID> [RSS URL]")) "unsub" (match-args args [url] (unsub-rss bot db (get-in message [:chat :id]) url (get-in message [:chat :id])) [channel-id url] (if-let [channel-id (verify-channel bot (get-in message [:chat :id]) channel-id (get-in message [:from :id]))] (unsub-rss bot db (get-in message [:chat :id]) url channel-id)) :else (tgapi/send-message bot (get-in message [:chat :id]) "使用方法: /unsub <Channel ID> [RSS URL]")) (log/warnf "Unknown command: %s, args: %s" cmd args))))) (catch Exception e (log/error "Unexpected error" e)))) (defn get-all-rss [db] (jdbc/query db ["SELECT * FROM rss"])) (defn get-subscribers [db rss] (let [result (jdbc/query db ["SELECT subscriber FROM subscribers WHERE rss = ?" rss])] (map #(:subscriber %) result))) (defn fix-relative-url [host link] (condp #(string/starts-with? %2 %1) link "//" (str "http:" link) "/" (str host link) "./" (str host (string/replace-first link "." "")) (if-not (string/blank? link) link host))) (defn get-host [url] (subs url 0 (string/index-of url "/" 8))) (defn make-rss-update-msg [url title updates] (reduce #(format "%s\n<a href=\"%s\">%s</a>" %1 (fix-relative-url (get-host url) (format-title (cond (not (string/blank? (:link %2))) (:link %2) (not (string/blank? (:uri %2))) (:uri %2) :else ""))) (-> (:title %2) (format-title) (escape-title))) (format "<b>%s</b>" (escape-title title)) updates)) (defn filter-updates [hash-list entries] (let [hash-list (apply hash-set hash-list)] ; convert to hash-set for (contains?) (remove #(contains? hash-list (entry-hash %)) entries))) (defn update-rss-hash-list [old-hash-list new-entries rss] (let [hash-list (map entry-hash new-entries) max-size (* (count (:entries rss)) 2) result (concat hash-list old-hash-list) result (if (> (count result) max-size) (take max-size result) result)] (string/join " " result))) (defn fetch-rss-updates [bot db] (future (loop [] (doseq [row (get-all-rss db)] (future (try (let [url (:url row) hash-list (keep parse-int (string/split (:hash_list row) #" ")) rss (parse-feed url) title (format-title (:title rss)) updates (filter-updates hash-list (:entries rss))] (if (not= (count updates) 0) (do (jdbc/update! db :rss {:title title :hash_list (update-rss-hash-list hash-list updates rss) :err_count 0} ["url = ?" url]) (let [message (make-rss-update-msg url title updates)] (doseq [subscriber (get-subscribers db url)] (try (send-message bot subscriber message :parse-mode "HTML" :disable-web-page-preview true) (catch Exception e (if (-> e ex-data :status (#(or (= % 400) (= % 403)))) (do (log/errorf e "Send RSS updates to %s failed" subscriber) (try (unsub-rss bot db subscriber url subscriber))) ; 强制退订 (log/errorf e "Unexpected message sending error %s" subscriber))))))) (when (> (:err_count row) 0) reset err_count (jdbc/update! db :rss {:err_count 0} ["url = ?" url])))) (catch Exception e (let [msg (.getMessage e) url (:url row) title (:title row) err-count (inc (:err_count row))] (log/errorf e "Fetch RSS updates failed: %s" url) (when (= (:type (ex-data e)) :rss-exception) (if (< err-count 1440) (jdbc/update! db :rss {:err_count err-count} ["url = ?" url]) (do (doseq [subscriber (get-subscribers db url)] (try (send-message bot subscriber (format "《<a href=\"%s\">%s</a>》已经连续五天拉取出错(%s),可能已经关闭,请取消订阅" url (escape-title title) msg) :parse-mode "HTML" :disable-web-page-preview true) (catch Exception e (if (-> e ex-data :status (#(or (= % 400) (= % 403)))) (do (log/errorf e "Send RSS fetch error to %s failed" subscriber) (try (unsub-rss bot db subscriber url subscriber))) ; 强制退订 (log/errorf e "Unexpected message sending error %s" subscriber))))) (jdbc/update! db :rss {:err_count 0} ["url = ?" url]))))))))) 5min (recur)))) (defn -main [bot-key] (init-db db) (let [bot (tgapi/new-bot bot-key)] (fetch-rss-updates bot db) (loop [updates (updates-seq bot)] (future (handle-update bot db (first updates))) (recur (rest updates)))))
null
https://raw.githubusercontent.com/iovxw/tg-rss-bot/52be6d971095cb7ec1ab0d4ddb4394fa4adb606f/src/tg_rss_bot/core.clj
clojure
当前所选定的长度 剩下的长度小于最大长度 DONE 单行大于最大长度,进行行内切分 nginx 检查是否为第一次订阅 最后一个订阅者退订,删除这个 RSS Bad Request: chat not found Bad Request: Channel members are unavailable convert to hash-set for (contains?) 强制退订 强制退订
(ns tg-rss-bot.core (:require [tg-rss-bot.tgapi :as tgapi] [clojure.tools.logging :as log] [clojure.java.jdbc :as jdbc] [clojure.string :as string] [clj-http.client :as client] [clojure.core.match :refer [match]] [feedparser-clj.core :as feedparser]) (:import [java.io InputStreamReader BufferedReader ByteArrayInputStream] [java.net URLEncoder]) (:gen-class)) (def db {:classname "org.sqlite.JDBC" :subprotocol "sqlite" :subname "database.db"}) (defn init-db [db] (jdbc/execute! db ["CREATE TABLE IF NOT EXISTS rss ( url VARCHAR, title VARCHAR, hash_list VARCHAR, err_count INTEGER)"]) (jdbc/execute! db ["CREATE TABLE IF NOT EXISTS subscribers ( rss VARCHAR, subscriber INTEGER)"])) (defn updates-seq ([bot] (updates-seq bot 0)) ([bot offset] (let [updates (try (tgapi/get-updates bot :offset offset :timeout 120) (catch Exception e (log/warnf "Get updates fail: %s" (.getMessage e)) [])) new-offset (if (not= (count updates) 0) (-> updates last :update_id inc) updates 数量为 0,可能获取失败,使用旧的 offset (lazy-cat updates (updates-seq bot new-offset))))) (defn has-row? [db table query & value] (let [query (format "SELECT COUNT(*) FROM %s WHERE %s" table query) result (jdbc/query db (cons query value))] result like ( { : count ( * ) 1 } ) (not (zero? ((keyword "count(*)") (first result)))))) (defn split-message [text max-len] (let [text-len (count text)] (loop [begin 0, offset 0, result []] (let [n (if-let [n (string/index-of text "\n" offset)] n text-len) line-len (- n offset) (let [split-len (- max-len (- offset begin)) split-point (+ offset split-len)] (recur split-point split-point (conj result (subs text begin split-point)))) (if (> now-len max-len) 这里的 ( dec offset ) 是为了去掉最后一个换行 (conj result (subs text begin (dec offset)))) (recur begin (inc n) result)))))))) (defn send-message [bot chat-id text & opts] (if (<= (count text) 4096) (apply tgapi/send-message bot chat-id text opts) (let [messages (split-message text 1024)] (doseq [msg messages] (apply tgapi/send-message bot chat-id msg opts))))) (def status-code {100 "Continue" 101 "Switching Protocols" 102 "Processing" 200 "OK" 201 "Created" 202 "Accepted" 203 "Non-Authoritative Information" 204 "No Content" 205 "Reset Content" 206 "Partial Content" 207 "Multi-Status" 208 "Already Reported" 226 "IM Used" 300 "Multiple Choices" 301 "Moved Permanently" 302 "Found" 303 "See Other" 304 "Not Modified" 305 "Use Proxy" 306 "Switch Proxy" 307 "Temporary Redirect" 308 "Permanent Redirect" 400 "Bad Request" 401 "Unauthorized" 402 "Payment Required" 403 "Forbidden" 404 "Not Found" 405 "Method Not Allowed" 406 "Not Acceptable" 407 "Proxy Authentication Required" 408 "Request Timeout" 409 "Conflict" 410 "Gone" 411 "Length Required" 412 "Precondition Failed" 413 "Payload Too Large" 414 "URI Too Long" 415 "Unsupported Media Type" 416 "Range Not Satisfiable" 417 "Expectation Failed" 418 "I'm a teapot" 421 "Misdirected Request" 422 "Unprocessable Entity" 423 "Locked" 424 "Failed Dependency" 426 "Upgrade Required" 428 "Precondition Required" 429 "Too Many Requests" 431 "Request Header Fields Too Large" 451 "Unavailable For Legal Reasons" 500 "Internal Server Error" 501 "Not Implemented" 502 "Bad Gateway" 503 "Service Unavailable" 504 "Gateway Timeout" 505 "HTTP Version Not Supported" 506 "Variant Also Negotiates" 507 "Insufficient Storage" 508 "Loop Detected" 510 "Not Extended" 511 "Network Authentication Required" 444 "No Response" 495 "SSL Certificate Error" 496 "SSL Certificate Required" 497 "HTTP Request Sent to HTTPS Port" 499 "Client Closed Request" CloudFlare 520 "Unknown Error" 521 "Web Server Is Down" 522 "Connection Timed Out" 523 "Origin Is Unreachable" 524 "A Timeout Occurred" 525 "SSL Handshake Failed" 526 "Invalid SSL Certificate"}) (defn remove-unserializable-chars [b] (let [declaration (.readLine (BufferedReader. (InputStreamReader. (ByteArrayInputStream. b) "UTF-8"))) encoding (or (second (re-find #"^<\?[^>]*encoding=[\'\"]([^\"\'>]+)[\'\"][^>]*\?>" declaration)) "UTF-8") s (String. b encoding) r (string/replace s #"[\x00-\x08\x0B-\x0C\x0E-\x1F]" "") b (.getBytes r encoding)] (ByteArrayInputStream. b))) (defn parse-feed [url] (try fix ParsingFeedException (let [resp (client/get url {:as :byte-array :headers {"User-Agent" (str "Mozilla/5.0 (X11; Linux x86_64) " "AppleWebKit/537.36 (KHTML, like Gecko) " "Chrome/52.0.2743.82 Safari/537.36")}})] (with-open [stream (remove-unserializable-chars (:body resp))] (feedparser/parse-feed stream))) (catch java.net.UnknownHostException _ (throw (ex-info "未知服务器地址" {:type :rss-exception}))) (catch clojure.lang.ExceptionInfo e (throw (ex-info (let [code (:status (ex-data e))] (if code (format "HTTP %s: %s" code (get status-code code)) (.getMessage e))) {:type :rss-exception}))) (catch Exception e (throw (ex-info (.getMessage e) {:type :rss-exception}))))) (defn format-title [title] (when title (string/replace title #"(?:^[\s\n]*)|(?:[\s\n]*$)" ""))) (defn escape-title [title] (when title (string/escape title {\< "&lt;", \> "&gt;", \& "&amp;"}))) (defn entry-hash [entry] (hash (str (:link entry) (:title entry)))) (defn gen-rss-hash-list [rss] (string/join " " (map entry-hash (:entries rss)))) (defn sub-rss [bot db chat-id url subscriber] (if-not (has-row? db "subscribers" "rss = ? AND subscriber = ?" url subscriber) (let [msg (tgapi/send-message bot chat-id "拉取 RSS 信息中,请稍候") msg-id (:message_id msg) rss (try (parse-feed url) (catch Exception e (tgapi/edit-message-text bot chat-id msg-id (format (str "订阅失败: %s\n" "请 [检查 RSS 合法性]() " "(更多帮助请查看 /start)") (.getMessage e) (URLEncoder/encode url "UTF-8")) :parse-mode "Markdown" :disable-web-page-preview true) (log/warnf "sub-rss: %s, %s" url (.getMessage e)))) title (format-title (:title rss))] (when rss (jdbc/insert! db :subscribers {:rss url :subscriber subscriber}) (tgapi/edit-message-text bot chat-id msg-id (format "《<a href=\"%s\">%s</a>》订阅成功" url (escape-title title)) :parse-mode "HTML" :disable-web-page-preview true) (when-not (has-row? db "rss" "url = ?" url) (jdbc/insert! db :rss {:url url :title title :hash_list (gen-rss-hash-list rss) :err_count 0})))) (tgapi/send-message bot chat-id "订阅失败,已经订阅过的 RSS"))) (defn get-rss-title [db url] (-> (jdbc/query db ["SELECT title FROM rss WHERE url = ?" url]) (first) (:title))) (defn unsub-rss [bot db chat-id url subscriber] (let [result (jdbc/execute! db ["DELETE FROM subscribers WHERE rss = ? AND subscriber = ?" url subscriber])] (if (>= (first result) 1) (let [title (get-rss-title db url)] (when-not (has-row? db "subscribers" "rss = ?" url) (jdbc/delete! db :rss ["url = ?" url])) (tgapi/send-message bot chat-id (format "《<a href=\"%s\">%s</a>》退订成功" url (escape-title title)) :parse-mode "HTML" :disable-web-page-preview true)) (tgapi/send-message bot chat-id "退订失败,没有订阅过的 RSS")))) (defn get-sub-list [bot db chat-id subscriber raw?] (let [result (jdbc/query db ["SELECT rss FROM subscribers WHERE subscriber = ?" subscriber])] (if-not (= (count result) 0) (if raw? (send-message bot chat-id (reduce #(format "%s\n%s: %s" %1 (get-rss-title db (:rss %2)) (:rss %2)) "订阅列表:" result) :disable-web-page-preview true) (send-message bot chat-id (reduce #(format "%s\n<a href=\"%s\">%s</a>" %1 (:rss %2) (escape-title (get-rss-title db (:rss %2)))) "订阅列表:" result) :parse-mode "HTML" :disable-web-page-preview true)) (tgapi/send-message bot chat-id "订阅列表为空")))) (defmacro match-args [args & body] `(match (when ~args (string/split ~args #" ")) ~@body)) (defmacro if-not-let ([bindings then] `(if-not-let ~bindings nil ~then)) ([bindings then else & oldform] `(if-let ~bindings ~else ~then ~@oldform))) (defn parse-int [s] (try (Integer. s) (catch Exception _ nil))) (defn verify-channel [bot chat-id channel-id user-id] (let [msg (tgapi/send-message bot chat-id "正在验证 Channel") msg-id (:message_id msg) channel-id (if (parse-int channel-id) (if (not (string/starts-with? channel-id "-100")) (str "-100" channel-id) channel-id) (if (not (string/starts-with? channel-id "@")) (str "@" channel-id) channel-id))] (if-not-let [channel-info (try (tgapi/get-chat bot channel-id) (when (-> (ex-data e) :status (not= 400)) (throw e))))] (do (tgapi/edit-message-text bot chat-id msg-id "无法找到目标 Channel") nil) (if-not (= (:type channel-info) "channel") (do (tgapi/edit-message-text bot chat-id msg-id "目标需为 Channel") nil) (if-not-let [channel-admins (try (tgapi/get-chat-admins bot channel-id) (when (-> (ex-data e) :status (not= 400)) (throw e))))] (do (tgapi/edit-message-text bot chat-id msg-id "请先将本 Bot 加入目标 Channel 并设为管理员") nil) (if-not (some #(= (get-in % [:user :id]) (:id bot)) channel-admins) (do (tgapi/edit-message-text bot chat-id msg-id "请将本 Bot 设为目标 Channel 管理员") nil) (if-not (some #(= (get-in % [:user :id]) user-id) channel-admins) (do (tgapi/edit-message-text bot chat-id msg-id "该命令只能由 Channel 管理员使用") nil) (:id channel-info)))))))) (defn handle-update [bot db update] (try (when-let [message (:message update)] (when-let [text (:text message)] (let [[cmd args] (tgapi/parse-cmd bot text)] (case cmd "start" (tgapi/send-message bot (get-in message [:chat :id]) (str "命令列表:\n" "/rss - 显示当前订阅的 RSS 列表,可以加 raw 参数显示原始链接\n" "/sub - 命令后加要订阅的 RSS 链接,订阅一条 RSS\n" "/unsub - 命令后加要退订的 RSS 链接,退订一条 RSS\n" "本项目源码:\n" "-rss-bot\n" "注: 可使用 [Feedburner](/) 之类服务来解决网络问题\n" "如有任何疑问请联系作者 @iovxw") :parse-mode "Markdown") "rss" (match-args args nil (get-sub-list bot db (get-in message [:chat :id]) (get-in message [:chat :id]) false) ["raw"] (get-sub-list bot db (get-in message [:chat :id]) (get-in message [:chat :id]) true) [channel-id] (if-let [channel-id (verify-channel bot (get-in message [:chat :id]) channel-id (get-in message [:from :id]))] (get-sub-list bot db (get-in message [:chat :id]) channel-id false)) [channel-id "raw"] (if-let [channel-id (verify-channel bot (get-in message [:chat :id]) channel-id (get-in message [:from :id]))] (get-sub-list bot db (get-in message [:chat :id]) channel-id true)) :else (tgapi/send-message bot (get-in message [:chat :id]) "使用方法: /rss <Channel ID> <raw>")) "sub" (match-args args [url] (sub-rss bot db (get-in message [:chat :id]) url (get-in message [:chat :id])) [channel-id url] (if-let [channel-id (verify-channel bot (get-in message [:chat :id]) channel-id (get-in message [:from :id]))] (sub-rss bot db (get-in message [:chat :id]) url channel-id)) :else (tgapi/send-message bot (get-in message [:chat :id]) "使用方法: /sub <Channel ID> [RSS URL]")) "unsub" (match-args args [url] (unsub-rss bot db (get-in message [:chat :id]) url (get-in message [:chat :id])) [channel-id url] (if-let [channel-id (verify-channel bot (get-in message [:chat :id]) channel-id (get-in message [:from :id]))] (unsub-rss bot db (get-in message [:chat :id]) url channel-id)) :else (tgapi/send-message bot (get-in message [:chat :id]) "使用方法: /unsub <Channel ID> [RSS URL]")) (log/warnf "Unknown command: %s, args: %s" cmd args))))) (catch Exception e (log/error "Unexpected error" e)))) (defn get-all-rss [db] (jdbc/query db ["SELECT * FROM rss"])) (defn get-subscribers [db rss] (let [result (jdbc/query db ["SELECT subscriber FROM subscribers WHERE rss = ?" rss])] (map #(:subscriber %) result))) (defn fix-relative-url [host link] (condp #(string/starts-with? %2 %1) link "//" (str "http:" link) "/" (str host link) "./" (str host (string/replace-first link "." "")) (if-not (string/blank? link) link host))) (defn get-host [url] (subs url 0 (string/index-of url "/" 8))) (defn make-rss-update-msg [url title updates] (reduce #(format "%s\n<a href=\"%s\">%s</a>" %1 (fix-relative-url (get-host url) (format-title (cond (not (string/blank? (:link %2))) (:link %2) (not (string/blank? (:uri %2))) (:uri %2) :else ""))) (-> (:title %2) (format-title) (escape-title))) (format "<b>%s</b>" (escape-title title)) updates)) (defn filter-updates [hash-list entries] (remove #(contains? hash-list (entry-hash %)) entries))) (defn update-rss-hash-list [old-hash-list new-entries rss] (let [hash-list (map entry-hash new-entries) max-size (* (count (:entries rss)) 2) result (concat hash-list old-hash-list) result (if (> (count result) max-size) (take max-size result) result)] (string/join " " result))) (defn fetch-rss-updates [bot db] (future (loop [] (doseq [row (get-all-rss db)] (future (try (let [url (:url row) hash-list (keep parse-int (string/split (:hash_list row) #" ")) rss (parse-feed url) title (format-title (:title rss)) updates (filter-updates hash-list (:entries rss))] (if (not= (count updates) 0) (do (jdbc/update! db :rss {:title title :hash_list (update-rss-hash-list hash-list updates rss) :err_count 0} ["url = ?" url]) (let [message (make-rss-update-msg url title updates)] (doseq [subscriber (get-subscribers db url)] (try (send-message bot subscriber message :parse-mode "HTML" :disable-web-page-preview true) (catch Exception e (if (-> e ex-data :status (#(or (= % 400) (= % 403)))) (do (log/errorf e "Send RSS updates to %s failed" subscriber) (log/errorf e "Unexpected message sending error %s" subscriber))))))) (when (> (:err_count row) 0) reset err_count (jdbc/update! db :rss {:err_count 0} ["url = ?" url])))) (catch Exception e (let [msg (.getMessage e) url (:url row) title (:title row) err-count (inc (:err_count row))] (log/errorf e "Fetch RSS updates failed: %s" url) (when (= (:type (ex-data e)) :rss-exception) (if (< err-count 1440) (jdbc/update! db :rss {:err_count err-count} ["url = ?" url]) (do (doseq [subscriber (get-subscribers db url)] (try (send-message bot subscriber (format "《<a href=\"%s\">%s</a>》已经连续五天拉取出错(%s),可能已经关闭,请取消订阅" url (escape-title title) msg) :parse-mode "HTML" :disable-web-page-preview true) (catch Exception e (if (-> e ex-data :status (#(or (= % 400) (= % 403)))) (do (log/errorf e "Send RSS fetch error to %s failed" subscriber) (log/errorf e "Unexpected message sending error %s" subscriber))))) (jdbc/update! db :rss {:err_count 0} ["url = ?" url]))))))))) 5min (recur)))) (defn -main [bot-key] (init-db db) (let [bot (tgapi/new-bot bot-key)] (fetch-rss-updates bot db) (loop [updates (updates-seq bot)] (future (handle-update bot db (first updates))) (recur (rest updates)))))
a0565d5db299f39165ceae58eb81018e31be18728c0104fef4a379f26b4da294
acl2/acl2
lift-r1cs-common@useless-runes.lsp
(SYMBOL<-OF-CARS) (CONSP-AND-SYMBOLP-CAR) (ALL-CONSP-AND-SYMBOLP-CAR) (ALL-CONSP-AND-SYMBOLP-CAR-OF-CONS-FOR-DEFMERGESORT (70 7 (:REWRITE CONSP-FROM-LEN-CHEAP)) (35 35 (:TYPE-PRESCRIPTION LEN)) (14 7 (:REWRITE DEFAULT-<-2)) (10 5 (:REWRITE SYMBOLP-OF-CAR-WHEN-SYMBOL-LISTP-CHEAP)) (8 8 (:REWRITE DEFAULT-CAR)) (7 7 (:REWRITE LEN-WHEN-NOT-CONSP-CHEAP)) (7 7 (:REWRITE DEFAULT-<-1)) (7 7 (:REWRITE CONSP-WHEN-LEN-GREATER)) (7 7 (:REWRITE CONSP-WHEN-LEN-EQUAL-CONSTANT)) (7 7 (:LINEAR LEN-POSITIVE-WHEN-CONSP-LINEAR-CHEAP)) (5 5 (:TYPE-PRESCRIPTION SYMBOL-LISTP)) (4 2 (:REWRITE SYMBOLP-OF-CAR-OF-CAR-WHEN-SYMBOL-ALISTP-CHEAP)) (3 3 (:REWRITE DEFAULT-CDR)) (2 2 (:TYPE-PRESCRIPTION SYMBOL-ALISTP)) ) (USE-ALL-CONSP-AND-SYMBOLP-CAR-FOR-CAR-FOR-DEFMERGESORT (39 4 (:REWRITE CONSP-FROM-LEN-CHEAP)) (9 6 (:LINEAR LEN-POSITIVE-WHEN-CONSP-LINEAR-CHEAP)) (8 4 (:REWRITE DEFAULT-<-2)) (7 7 (:REWRITE LEN-WHEN-NOT-CONSP-CHEAP)) (7 7 (:REWRITE DEFAULT-CAR)) (4 4 (:REWRITE DEFAULT-<-1)) (4 4 (:REWRITE CONSP-WHEN-LEN-GREATER)) (4 4 (:REWRITE CONSP-WHEN-LEN-EQUAL-CONSTANT)) (4 2 (:REWRITE SYMBOLP-OF-CAR-WHEN-SYMBOL-LISTP-CHEAP)) (4 2 (:REWRITE SYMBOLP-OF-CAR-OF-CAR-WHEN-SYMBOL-ALISTP-CHEAP)) (2 2 (:TYPE-PRESCRIPTION SYMBOL-LISTP)) (2 2 (:TYPE-PRESCRIPTION SYMBOL-ALISTP)) (1 1 (:REWRITE DEFAULT-CDR)) ) (ALL-CONSP-AND-SYMBOLP-CAR-OF-CDR-FOR-DEFMERGESORT (20 2 (:REWRITE CONSP-FROM-LEN-CHEAP)) (10 10 (:TYPE-PRESCRIPTION LEN)) (4 2 (:REWRITE DEFAULT-<-2)) (4 1 (:REWRITE USE-ALL-CONSP-AND-SYMBOLP-CAR-FOR-CAR-FOR-DEFMERGESORT)) (2 2 (:REWRITE LEN-WHEN-NOT-CONSP-CHEAP)) (2 2 (:REWRITE DEFAULT-CAR)) (2 2 (:REWRITE DEFAULT-<-1)) (2 2 (:REWRITE CONSP-WHEN-LEN-GREATER)) (2 2 (:REWRITE CONSP-WHEN-LEN-EQUAL-CONSTANT)) (2 2 (:LINEAR LEN-POSITIVE-WHEN-CONSP-LINEAR-CHEAP)) (2 1 (:REWRITE SYMBOLP-OF-CAR-WHEN-SYMBOL-LISTP-CHEAP)) (2 1 (:REWRITE SYMBOLP-OF-CAR-OF-CAR-WHEN-SYMBOL-ALISTP-CHEAP)) (1 1 (:TYPE-PRESCRIPTION SYMBOL-LISTP)) (1 1 (:TYPE-PRESCRIPTION SYMBOL-ALISTP)) ) (ALL-CONSP-AND-SYMBOLP-CAR) (MERGE-SYMBOL<-OF-CARS (296 32 (:REWRITE CONSP-FROM-LEN-CHEAP)) (112 8 (:DEFINITION TRUE-LISTP)) (56 28 (:REWRITE DEFAULT-<-2)) (52 52 (:REWRITE LEN-WHEN-NOT-CONSP-CHEAP)) (48 12 (:REWRITE DEFAULT-CAR)) (32 32 (:REWRITE CONSP-WHEN-LEN-EQUAL-CONSTANT)) (28 28 (:REWRITE DEFAULT-<-1)) (28 28 (:REWRITE CONSP-WHEN-LEN-GREATER)) (28 14 (:TYPE-PRESCRIPTION TRUE-LISTP-REVAPPEND-TYPE-PRESCRIPTION)) (8 8 (:REWRITE DEFAULT-CDR)) (8 4 (:REWRITE SYMBOLP-OF-CAR-WHEN-SYMBOL-LISTP-CHEAP)) (8 4 (:REWRITE SYMBOLP-OF-CAR-OF-CAR-WHEN-SYMBOL-ALISTP-CHEAP)) (4 4 (:TYPE-PRESCRIPTION SYMBOL-LISTP)) (4 4 (:TYPE-PRESCRIPTION SYMBOL-ALISTP)) ) (CONSP-OF-MERGE-SYMBOL<-OF-CARS (127 16 (:REWRITE CONSP-FROM-LEN-CHEAP)) (25 25 (:REWRITE LEN-WHEN-NOT-CONSP-CHEAP)) (25 13 (:REWRITE DEFAULT-<-2)) (16 16 (:REWRITE CONSP-WHEN-LEN-GREATER)) (16 16 (:REWRITE CONSP-WHEN-LEN-EQUAL-CONSTANT)) (13 13 (:REWRITE DEFAULT-<-1)) (8 8 (:REWRITE DEFAULT-CAR)) (5 3 (:REWRITE DEFAULT-+-2)) (5 1 (:REWRITE LEN-OF-CDR)) (4 2 (:TYPE-PRESCRIPTION TRUE-LISTP-REVAPPEND-TYPE-PRESCRIPTION)) (4 1 (:REWRITE <-OF-+-ARG2-WHEN-NEGATIVE-CONSTANT)) (3 3 (:REWRITE DEFAULT-+-1)) (2 2 (:TYPE-PRESCRIPTION TRUE-LISTP)) (2 2 (:REWRITE DEFAULT-CDR)) (1 1 (:REWRITE CONSP-OF-CDR-WHEN-LEN-KNOWN)) ) (MERGE-SORT-SYMBOL<-OF-CARS) (CONSP-OF-MERGE-SORT-SYMBOL<-OF-CARS (72 7 (:REWRITE DEFAULT-CDR)) (38 38 (:REWRITE LEN-WHEN-NOT-CONSP-CHEAP)) (38 19 (:REWRITE DEFAULT-<-2)) (31 31 (:REWRITE CONSP-WHEN-LEN-EQUAL-CONSTANT)) (25 25 (:REWRITE CONSP-WHEN-LEN-GREATER)) (19 19 (:REWRITE DEFAULT-<-1)) (12 6 (:TYPE-PRESCRIPTION TRUE-LISTP-OF-MV-NTH-1-OF-SPLIT-LIST-FAST)) (12 6 (:REWRITE DEFAULT-+-2)) (6 6 (:TYPE-PRESCRIPTION TRUE-LISTP)) (6 6 (:REWRITE DEFAULT-+-1)) (6 1 (:LINEAR LEN-OF-CDR-LINEAR-STRONG)) (4 4 (:REWRITE CONSP-OF-CDR-WHEN-LEN-KNOWN)) ) (ALL-CONSP-AND-SYMBOLP-CAR-OF-MV-NTH-0-OF-SPLIT-LIST-FAST-AUX) (ALL-CONSP-AND-SYMBOLP-CAR-OF-MV-NTH-0-OF-SPLIT-LIST-FAST) (ALL-CONSP-AND-SYMBOLP-CAR-OF-MV-NTH-1-OF-SPLIT-LIST-FAST-AUX) (ALL-CONSP-AND-SYMBOLP-CAR-OF-MV-NTH-1-OF-SPLIT-LIST-FAST) (ALL-CONSP-AND-SYMBOLP-CAR-OF-MERGE-SYMBOL<-OF-CARS) (TRUE-LISTP-OF-MERGE-SYMBOL<-OF-CARS) (TRUE-LISTP-OF-MERGE-SORT-SYMBOL<-OF-CARS) (ALL-CONSP-AND-SYMBOLP-CAR-OF-MERGE-SORT-SYMBOL<-OF-CARS) (MERGE-SORT-SYMBOL<-OF-CARS) (PERM-OF-MERGE-SYMBOL<-OF-CARS) (PERM-OF-MERGE-SORT-SYMBOL<-OF-CARS) (R1CS::CONSP-OF-NTH-WHEN-SYMBOL-ALISTP (158 16 (:REWRITE CONSP-FROM-LEN-CHEAP)) (44 26 (:REWRITE DEFAULT-<-2)) (26 26 (:REWRITE DEFAULT-<-1)) (25 25 (:REWRITE LEN-WHEN-NOT-CONSP-CHEAP)) (18 18 (:REWRITE DEFAULT-CAR)) (16 16 (:REWRITE CONSP-WHEN-LEN-GREATER)) (16 16 (:REWRITE CONSP-WHEN-LEN-EQUAL-CONSTANT)) (10 5 (:REWRITE SYMBOLP-OF-CAR-WHEN-SYMBOL-LISTP-CHEAP)) (10 5 (:REWRITE SYMBOLP-OF-CAR-OF-CAR-WHEN-SYMBOL-ALISTP-CHEAP)) (8 2 (:REWRITE SYMBOL-ALISTP-OF-CDR)) (5 5 (:TYPE-PRESCRIPTION SYMBOL-LISTP)) (5 5 (:REWRITE DEFAULT-CDR)) (5 5 (:REWRITE DEFAULT-+-2)) (5 5 (:REWRITE DEFAULT-+-1)) (3 3 (:REWRITE ZP-OPEN)) ) (R1CS::ALL-CONSP-AND-SYMBOLP-CAR-WHEN-SYMBOL-ALISTP (130 16 (:REWRITE CONSP-FROM-LEN-CHEAP)) (26 13 (:REWRITE DEFAULT-<-2)) (21 21 (:REWRITE DEFAULT-CAR)) (16 16 (:REWRITE LEN-WHEN-NOT-CONSP-CHEAP)) (16 16 (:REWRITE CONSP-WHEN-LEN-GREATER)) (16 16 (:REWRITE CONSP-WHEN-LEN-EQUAL-CONSTANT)) (14 7 (:REWRITE SYMBOLP-OF-CAR-WHEN-SYMBOL-LISTP-CHEAP)) (13 13 (:REWRITE DEFAULT-<-1)) (8 2 (:REWRITE SYMBOL-ALISTP-OF-CDR)) (7 7 (:TYPE-PRESCRIPTION SYMBOL-LISTP)) (4 4 (:REWRITE DEFAULT-CDR)) ) (R1CS::SYMBOL-ALISTP-OF-MERGE-SYMBOL<-OF-CARS (1158 127 (:REWRITE CONSP-FROM-LEN-CHEAP)) (253 149 (:REWRITE DEFAULT-CAR)) (223 116 (:REWRITE DEFAULT-<-2)) (177 39 (:REWRITE DEFAULT-CDR)) (149 149 (:REWRITE LEN-WHEN-NOT-CONSP-CHEAP)) (127 127 (:REWRITE CONSP-WHEN-LEN-GREATER)) (127 127 (:REWRITE CONSP-WHEN-LEN-EQUAL-CONSTANT)) (116 116 (:REWRITE DEFAULT-<-1)) (90 6 (:DEFINITION REVAPPEND)) (62 31 (:REWRITE SYMBOLP-OF-CAR-WHEN-SYMBOL-LISTP-CHEAP)) (45 9 (:REWRITE LEN-OF-CDR)) (36 9 (:REWRITE <-OF-+-ARG2-WHEN-NEGATIVE-CONSTANT)) (31 31 (:TYPE-PRESCRIPTION SYMBOL-LISTP)) (14 14 (:REWRITE CONSP-OF-CDR-WHEN-LEN-KNOWN)) (9 9 (:REWRITE DEFAULT-+-2)) (9 9 (:REWRITE DEFAULT-+-1)) (2 2 (:REWRITE TRUE-LIST-FIX-WHEN-NOT-CONS-CHEAP)) ) (R1CS::SYMBOL-ALISTP-OF-MV-NTH-0-OF-SPLIT-LIST-FAST-AUX (1630 168 (:REWRITE CONSP-FROM-LEN-CHEAP)) (299 173 (:REWRITE DEFAULT-CAR)) (296 154 (:REWRITE DEFAULT-<-2)) (168 168 (:REWRITE CONSP-WHEN-LEN-EQUAL-CONSTANT)) (166 166 (:REWRITE CONSP-WHEN-LEN-GREATER)) (160 154 (:REWRITE DEFAULT-<-1)) (100 50 (:REWRITE SYMBOLP-OF-CAR-WHEN-SYMBOL-LISTP-CHEAP)) (79 52 (:REWRITE DEFAULT-+-2)) (78 15 (:REWRITE <-OF-+-ARG2-WHEN-NEGATIVE-CONSTANT)) (52 52 (:REWRITE DEFAULT-+-1)) (50 50 (:TYPE-PRESCRIPTION SYMBOL-LISTP)) (29 29 (:REWRITE CONSP-OF-CDR-WHEN-LEN-KNOWN)) (13 13 (:REWRITE LEN-OF-CDDR-WHEN-EQUAL-OF-LEN)) ) (R1CS::SYMBOL-ALISTP-OF-MV-NTH-0-OF-SPLIT-LIST-FAST (57 4 (:REWRITE CONSP-FROM-LEN-CHEAP)) (48 1 (:DEFINITION SPLIT-LIST-FAST-AUX)) (37 1 (:DEFINITION SYMBOL-ALISTP)) (11 5 (:LINEAR LEN-POSITIVE-WHEN-CONSP-LINEAR-CHEAP)) (11 1 (:REWRITE <-OF-+-ARG2-WHEN-NEGATIVE-CONSTANT)) (9 9 (:REWRITE LEN-WHEN-NOT-CONSP-CHEAP)) (8 4 (:REWRITE DEFAULT-<-2)) (8 1 (:REWRITE LEN-OF-CDR)) (5 5 (:REWRITE DEFAULT-CDR)) (4 4 (:REWRITE DEFAULT-CAR)) (4 4 (:REWRITE DEFAULT-<-1)) (4 4 (:REWRITE CONSP-WHEN-LEN-GREATER)) (4 4 (:REWRITE CONSP-WHEN-LEN-EQUAL-CONSTANT)) (4 1 (:REWRITE SYMBOL-ALISTP-OF-CDR)) (2 1 (:REWRITE SYMBOLP-OF-CAR-WHEN-SYMBOL-LISTP-CHEAP)) (2 1 (:REWRITE SYMBOLP-OF-CAR-OF-CAR-WHEN-SYMBOL-ALISTP-CHEAP)) (2 1 (:REWRITE DEFAULT-+-2)) (1 1 (:TYPE-PRESCRIPTION SYMBOL-LISTP)) (1 1 (:REWRITE EQUAL-OF-LEN-AND-0)) (1 1 (:REWRITE DEFAULT-+-1)) (1 1 (:REWRITE CONSP-OF-CDR-WHEN-LEN-KNOWN)) ) (R1CS::SYMBOL-ALISTP-OF-MV-NTH-1-OF-SPLIT-LIST-FAST-AUX (366 75 (:REWRITE DEFAULT-CDR)) (297 297 (:REWRITE LEN-WHEN-NOT-CONSP-CHEAP)) (215 134 (:REWRITE DEFAULT-+-2)) (165 91 (:REWRITE DEFAULT-<-2)) (134 134 (:REWRITE DEFAULT-+-1)) (113 91 (:REWRITE DEFAULT-<-1)) (109 109 (:REWRITE CONSP-WHEN-LEN-EQUAL-CONSTANT)) (91 91 (:REWRITE CONSP-WHEN-LEN-GREATER)) (44 22 (:REWRITE SYMBOLP-OF-CAR-WHEN-SYMBOL-LISTP-CHEAP)) (38 23 (:REWRITE DEFAULT-*-2)) (30 30 (:REWRITE LEN-OF-CDDR-WHEN-EQUAL-OF-LEN)) (30 3 (:LINEAR LEN-OF-CDR-LINEAR-STRONG)) (24 3 (:LINEAR LEN-OF-CDR-LINEAR)) (23 23 (:REWRITE DEFAULT-*-1)) (23 23 (:REWRITE CONSP-OF-CDR-WHEN-LEN-KNOWN)) (22 22 (:TYPE-PRESCRIPTION SYMBOL-LISTP)) (3 3 (:REWRITE <-OF-+-COMBINE-CONSTANTS-2)) (3 3 (:REWRITE <-OF-+-ARG1-WHEN-NEGATIVE-CONSTANT)) ) (R1CS::SYMBOL-ALISTP-OF-MV-NTH-1-OF-SPLIT-LIST-FAST (57 4 (:REWRITE CONSP-FROM-LEN-CHEAP)) (48 1 (:DEFINITION SPLIT-LIST-FAST-AUX)) (37 1 (:DEFINITION SYMBOL-ALISTP)) (28 28 (:TYPE-PRESCRIPTION LEN)) (11 5 (:LINEAR LEN-POSITIVE-WHEN-CONSP-LINEAR-CHEAP)) (11 1 (:REWRITE <-OF-+-ARG2-WHEN-NEGATIVE-CONSTANT)) (8 4 (:REWRITE DEFAULT-<-2)) (8 1 (:REWRITE LEN-OF-CDR)) (7 7 (:REWRITE LEN-WHEN-NOT-CONSP-CHEAP)) (5 5 (:REWRITE DEFAULT-CDR)) (4 4 (:REWRITE DEFAULT-CAR)) (4 4 (:REWRITE DEFAULT-<-1)) (4 4 (:REWRITE CONSP-WHEN-LEN-GREATER)) (4 4 (:REWRITE CONSP-WHEN-LEN-EQUAL-CONSTANT)) (4 1 (:REWRITE SYMBOL-ALISTP-OF-CDR)) (2 1 (:REWRITE SYMBOLP-OF-CAR-WHEN-SYMBOL-LISTP-CHEAP)) (2 1 (:REWRITE SYMBOLP-OF-CAR-OF-CAR-WHEN-SYMBOL-ALISTP-CHEAP)) (2 1 (:REWRITE DEFAULT-+-2)) (1 1 (:TYPE-PRESCRIPTION SYMBOL-LISTP)) (1 1 (:REWRITE EQUAL-OF-LEN-AND-0)) (1 1 (:REWRITE DEFAULT-+-1)) (1 1 (:REWRITE CONSP-OF-CDR-WHEN-LEN-KNOWN)) ) (R1CS::SYMBOL-ALISTP-OF-MERGE-SORT-SYMBOL<-OF-CARS (90 19 (:REWRITE DEFAULT-CDR)) (81 13 (:REWRITE CONSP-OF-MERGE-SORT-SYMBOL<-OF-CARS)) (72 36 (:REWRITE DEFAULT-CAR)) (54 28 (:REWRITE DEFAULT-<-2)) (51 51 (:REWRITE LEN-WHEN-NOT-CONSP-CHEAP)) (48 12 (:REWRITE SYMBOL-ALISTP-OF-CDR)) (42 42 (:REWRITE CONSP-WHEN-LEN-EQUAL-CONSTANT)) (32 32 (:REWRITE CONSP-WHEN-LEN-GREATER)) (28 28 (:REWRITE DEFAULT-<-1)) (22 11 (:REWRITE SYMBOLP-OF-CAR-WHEN-SYMBOL-LISTP-CHEAP)) (22 11 (:REWRITE SYMBOLP-OF-CAR-OF-CAR-WHEN-SYMBOL-ALISTP-CHEAP)) (22 4 (:REWRITE CONSP-OF-MV-NTH-1-OF-SPLIT-LIST-FAST)) (15 3 (:REWRITE CONSP-OF-MV-NTH-0-OF-SPLIT-LIST-FAST)) (12 6 (:REWRITE DEFAULT-+-2)) (11 11 (:TYPE-PRESCRIPTION SYMBOL-LISTP)) (6 6 (:REWRITE DEFAULT-+-1)) (6 1 (:LINEAR LEN-OF-CDR-LINEAR-STRONG)) (4 4 (:TYPE-PRESCRIPTION TRUE-LISTP-OF-MV-NTH-1-OF-SPLIT-LIST-FAST)) (4 4 (:REWRITE CONSP-OF-CDR-WHEN-LEN-KNOWN)) (3 3 (:TYPE-PRESCRIPTION TRUE-LISTP-OF-MV-NTH-0-OF-SPLIT-LIST-FAST)) ) (R1CS::MAKE-VALUATION-FROM-KEYWORD-VARS-AUX (9 1 (:REWRITE CONSP-FROM-LEN-CHEAP)) (2 2 (:REWRITE SYMBOL-LISTP-WHEN-SUBSETP-EQUAL-1)) (2 2 (:REWRITE LEN-WHEN-NOT-CONSP-CHEAP)) (2 1 (:REWRITE DEFAULT-SYMBOL-NAME)) (2 1 (:REWRITE DEFAULT-<-2)) (2 1 (:LINEAR LEN-POSITIVE-WHEN-CONSP-LINEAR-CHEAP)) (1 1 (:REWRITE DEFAULT-CDR)) (1 1 (:REWRITE DEFAULT-CAR)) (1 1 (:REWRITE DEFAULT-<-1)) (1 1 (:REWRITE CONSP-WHEN-LEN-GREATER)) (1 1 (:REWRITE CONSP-WHEN-LEN-EQUAL-CONSTANT)) ) (R1CS::MAKE-VALUATION-FROM-KEYWORD-VARS) (R1CS::MAKE-VALUATION-FROM-KEYWORD-VARS2-AUX (157 1 (:REWRITE TAKE-DOES-NOTHING)) (149 1 (:REWRITE NTHCDR-WHEN-NOT-POSP)) (133 1 (:DEFINITION POSP)) (109 109 (:TYPE-PRESCRIPTION <=-OF-FLOOR-AND-0-WHEN-NONPOSITIVE-AND-NONNEGATIVE-TYPE)) (109 109 (:TYPE-PRESCRIPTION <=-OF-FLOOR-AND-0-WHEN-NONNEGATIVE-AND-NONPOSITIVE-TYPE)) (109 109 (:TYPE-PRESCRIPTION <=-OF-0-AND-FLOOR-WHEN-BOTH-NONPOSITIVE-TYPE)) (109 109 (:TYPE-PRESCRIPTION <-OF-FLOOR-AND-0-WHEN-POSITIVE-AND-NEGATIVE-TYPE)) (109 109 (:TYPE-PRESCRIPTION <-OF-FLOOR-AND-0-WHEN-NEGATIVE-AND-POSITIVE-TYPE)) (39 13 (:REWRITE DEFAULT-<-1)) (35 2 (:LINEAR FLOOR-WEAK-MONOTONE-LINEAR-1)) (18 18 (:REWRITE FLOOR-WHEN-NOT-RATIONALP-OF-QUOTIENT)) (18 18 (:REWRITE FLOOR-WHEN-NOT-RATIONALP-ARG1)) (18 18 (:REWRITE FLOOR-WHEN-NEGATIVE-AND-SMALL-CHEAP)) (18 18 (:REWRITE FLOOR-WHEN-I-IS-NOT-AN-ACL2-NUMBERP)) (18 18 (:REWRITE FLOOR-WHEN-<)) (18 18 (:REWRITE FLOOR-MINUS-NEGATIVE-CONSTANT)) (13 13 (:REWRITE DEFAULT-<-2)) (12 12 (:REWRITE DEFAULT-*-2)) (12 12 (:REWRITE DEFAULT-*-1)) (11 11 (:REWRITE LEN-WHEN-NOT-CONSP-CHEAP)) (11 4 (:REWRITE DEFAULT-+-2)) (8 1 (:REWRITE DEFAULT-UNARY-MINUS)) (6 6 (:TYPE-PRESCRIPTION TRUE-LISTP)) (6 6 (:LINEAR LEN-POSITIVE-WHEN-CONSP-LINEAR-CHEAP)) (6 1 (:REWRITE <-OF-0-AND-FLOOR)) (4 4 (:REWRITE SYMBOL-LISTP-WHEN-SUBSETP-EQUAL-1)) (4 4 (:REWRITE DEFAULT-+-1)) (2 2 (:LINEAR FLOOR-WEAK-MONOTONE-LINEAR=-2)) (1 1 (:TYPE-PRESCRIPTION POSP)) (1 1 (:REWRITE NTHCDR-WHEN-NOT-CONSP-CHEAP)) (1 1 (:REWRITE NTHCDR-WHEN-EQUAL-OF-LEN)) (1 1 (:REWRITE EQUAL-OF-FLOOR-SAME)) (1 1 (:REWRITE <-OF-+-COMBINE-CONSTANTS-2)) (1 1 (:REWRITE <-OF-+-ARG1-WHEN-NEGATIVE-CONSTANT)) ) (R1CS::MAKE-VALUATION-FROM-KEYWORD-VARS2) (R1CS::MAKE-FEP-ASSUMPTIONS-FROM-KEYWORD-VARS-AUX (9 1 (:REWRITE CONSP-FROM-LEN-CHEAP)) (2 2 (:REWRITE SYMBOL-LISTP-WHEN-SUBSETP-EQUAL-1)) (2 2 (:REWRITE LEN-WHEN-NOT-CONSP-CHEAP)) (2 1 (:REWRITE DEFAULT-SYMBOL-NAME)) (2 1 (:REWRITE DEFAULT-<-2)) (2 1 (:LINEAR LEN-POSITIVE-WHEN-CONSP-LINEAR-CHEAP)) (1 1 (:REWRITE DEFAULT-CDR)) (1 1 (:REWRITE DEFAULT-CAR)) (1 1 (:REWRITE DEFAULT-<-1)) (1 1 (:REWRITE CONSP-WHEN-LEN-GREATER)) (1 1 (:REWRITE CONSP-WHEN-LEN-EQUAL-CONSTANT)) ) (R1CS::MAKE-FEP-ASSUMPTIONS-FROM-KEYWORD-VARS) (R1CS::MAKE-BITP-ASSUMPTIONS-FROM-KEYWORD-VARS-AUX (9 1 (:REWRITE CONSP-FROM-LEN-CHEAP)) (2 2 (:REWRITE SYMBOL-LISTP-WHEN-SUBSETP-EQUAL-1)) (2 2 (:REWRITE LEN-WHEN-NOT-CONSP-CHEAP)) (2 1 (:REWRITE DEFAULT-SYMBOL-NAME)) (2 1 (:REWRITE DEFAULT-<-2)) (2 1 (:LINEAR LEN-POSITIVE-WHEN-CONSP-LINEAR-CHEAP)) (1 1 (:REWRITE DEFAULT-CDR)) (1 1 (:REWRITE DEFAULT-CAR)) (1 1 (:REWRITE DEFAULT-<-1)) (1 1 (:REWRITE CONSP-WHEN-LEN-GREATER)) (1 1 (:REWRITE CONSP-WHEN-LEN-EQUAL-CONSTANT)) ) (R1CS::MAKE-BITP-ASSUMPTIONS-FROM-KEYWORD-VARS) (R1CS::MAKE-SYMBOLIC-VALUATION-FOR-ALIST-AUX (29 3 (:REWRITE CONSP-FROM-LEN-CHEAP)) (6 4 (:LINEAR LEN-POSITIVE-WHEN-CONSP-LINEAR-CHEAP)) (6 3 (:REWRITE DEFAULT-<-2)) (5 5 (:REWRITE LEN-WHEN-NOT-CONSP-CHEAP)) (5 5 (:REWRITE DEFAULT-CAR)) (3 3 (:REWRITE DEFAULT-<-1)) (3 3 (:REWRITE CONSP-WHEN-LEN-GREATER)) (3 3 (:REWRITE CONSP-WHEN-LEN-EQUAL-CONSTANT)) (2 2 (:REWRITE DEFAULT-CDR)) (2 1 (:REWRITE SYMBOLP-OF-CAR-WHEN-SYMBOL-LISTP-CHEAP)) (2 1 (:REWRITE SYMBOLP-OF-CAR-OF-CAR-WHEN-SYMBOL-ALISTP-CHEAP)) (1 1 (:TYPE-PRESCRIPTION SYMBOL-LISTP)) ) (R1CS::MAKE-SYMBOLIC-VALUATION-FOR-ALIST (495 49 (:REWRITE CONSP-FROM-LEN-CHEAP)) (276 20 (:DEFINITION NTH)) (181 13 (:REWRITE R1CS::CONSP-OF-NTH-WHEN-SYMBOL-ALISTP)) (154 144 (:REWRITE LEN-WHEN-NOT-CONSP-CHEAP)) (153 10 (:REWRITE TAKE-DOES-NOTHING)) (141 81 (:REWRITE DEFAULT-CAR)) (138 15 (:REWRITE SYMBOL-ALISTP-OF-CDR)) (132 20 (:REWRITE ZP-OPEN)) (114 70 (:REWRITE DEFAULT-<-2)) (114 36 (:REWRITE <-OF-+-ARG2-WHEN-NEGATIVE-CONSTANT)) (112 90 (:REWRITE DEFAULT-+-2)) (110 22 (:REWRITE LEN-OF-CDR)) (90 90 (:REWRITE DEFAULT-+-1)) (87 29 (:REWRITE +-COMBINE-CONSTANTS)) (76 17 (:REWRITE EQUAL-OF-+-WHEN-NEGATIVE-CONSTANT)) (72 70 (:REWRITE DEFAULT-<-1)) (66 10 (:REWRITE <-OF-+-ARG1-WHEN-NEGATIVE-CONSTANT)) (64 8 (:DEFINITION NATP)) (49 49 (:REWRITE CONSP-WHEN-LEN-EQUAL-CONSTANT)) (46 46 (:REWRITE CONSP-WHEN-LEN-GREATER)) (44 22 (:REWRITE SYMBOLP-OF-CAR-WHEN-SYMBOL-LISTP-CHEAP)) (36 36 (:REWRITE DEFAULT-CDR)) (32 10 (:REWRITE LEN-OF-REVERSE-LIST)) (22 22 (:TYPE-PRESCRIPTION SYMBOL-LISTP)) (21 3 (:REWRITE EQUAL-OF-+-AND-+-CANCEL-CONSTANTS)) (14 10 (:DEFINITION FIX)) (10 10 (:REWRITE EQUAL-OF-+-COMBINE-CONSTANTS)) (10 10 (:REWRITE EQUAL-OF-+-CANCEL-SAME-2)) (8 8 (:TYPE-PRESCRIPTION NATP)) (8 8 (:REWRITE NATP-OF-+-WHEN-NATP-AND-NATP)) (7 7 (:REWRITE CONSP-OF-CDR-WHEN-LEN-KNOWN)) (6 6 (:REWRITE <-OF-+-COMBINE-CONSTANTS-1)) (6 6 (:REWRITE <-OF-+-CANCEL-1-2)) (2 1 (:REWRITE TRUE-LIST-FIX-WHEN-NOT-CONS-CHEAP)) (2 1 (:REWRITE APPEND-WHEN-NOT-CONSP-ARG1-CHEAP)) ) (R1CS::MAKE-EFFICIENT-SYMBOLIC-VALUATION-FOR-ALIST-AUX (157 1 (:REWRITE TAKE-DOES-NOTHING)) (149 1 (:REWRITE NTHCDR-WHEN-NOT-POSP)) (133 1 (:DEFINITION POSP)) (109 109 (:TYPE-PRESCRIPTION <=-OF-FLOOR-AND-0-WHEN-NONPOSITIVE-AND-NONNEGATIVE-TYPE)) (109 109 (:TYPE-PRESCRIPTION <=-OF-FLOOR-AND-0-WHEN-NONNEGATIVE-AND-NONPOSITIVE-TYPE)) (109 109 (:TYPE-PRESCRIPTION <=-OF-0-AND-FLOOR-WHEN-BOTH-NONPOSITIVE-TYPE)) (109 109 (:TYPE-PRESCRIPTION <-OF-FLOOR-AND-0-WHEN-POSITIVE-AND-NEGATIVE-TYPE)) (109 109 (:TYPE-PRESCRIPTION <-OF-FLOOR-AND-0-WHEN-NEGATIVE-AND-POSITIVE-TYPE)) (45 19 (:REWRITE DEFAULT-<-1)) (43 7 (:REWRITE CONSP-FROM-LEN-CHEAP)) (35 2 (:LINEAR FLOOR-WEAK-MONOTONE-LINEAR-1)) (34 1 (:DEFINITION NTH)) (23 19 (:REWRITE DEFAULT-<-2)) (19 5 (:REWRITE DEFAULT-+-2)) (18 18 (:REWRITE LEN-WHEN-NOT-CONSP-CHEAP)) (18 18 (:REWRITE FLOOR-WHEN-NOT-RATIONALP-OF-QUOTIENT)) (18 18 (:REWRITE FLOOR-WHEN-NOT-RATIONALP-ARG1)) (18 18 (:REWRITE FLOOR-WHEN-NEGATIVE-AND-SMALL-CHEAP)) (18 18 (:REWRITE FLOOR-WHEN-I-IS-NOT-AN-ACL2-NUMBERP)) (18 18 (:REWRITE FLOOR-WHEN-<)) (18 18 (:REWRITE FLOOR-MINUS-NEGATIVE-CONSTANT)) (12 12 (:REWRITE DEFAULT-*-2)) (12 12 (:REWRITE DEFAULT-*-1)) (12 11 (:LINEAR LEN-POSITIVE-WHEN-CONSP-LINEAR-CHEAP)) (12 1 (:REWRITE ZP-OPEN)) (10 2 (:REWRITE <-OF-0-AND-FLOOR)) (8 1 (:REWRITE DEFAULT-UNARY-MINUS)) (7 7 (:REWRITE DEFAULT-CAR)) (7 7 (:REWRITE CONSP-WHEN-LEN-EQUAL-CONSTANT)) (6 6 (:TYPE-PRESCRIPTION TRUE-LISTP)) (5 5 (:REWRITE DEFAULT-+-1)) (5 5 (:REWRITE CONSP-WHEN-LEN-GREATER)) (5 3 (:REWRITE DEFAULT-CDR)) (4 2 (:REWRITE SYMBOLP-OF-CAR-WHEN-SYMBOL-LISTP-CHEAP)) (2 2 (:TYPE-PRESCRIPTION SYMBOL-LISTP)) (2 2 (:LINEAR FLOOR-WEAK-MONOTONE-LINEAR=-2)) (1 1 (:TYPE-PRESCRIPTION POSP)) (1 1 (:REWRITE NTHCDR-WHEN-NOT-CONSP-CHEAP)) (1 1 (:REWRITE NTHCDR-WHEN-EQUAL-OF-LEN)) (1 1 (:REWRITE EQUAL-OF-FLOOR-SAME)) (1 1 (:REWRITE <-OF-+-COMBINE-CONSTANTS-2)) (1 1 (:REWRITE <-OF-+-ARG1-WHEN-NEGATIVE-CONSTANT)) ) (R1CS::MAKE-EFFICIENT-SYMBOLIC-VALUATION-FOR-ALIST)
null
https://raw.githubusercontent.com/acl2/acl2/f64742cc6d41c35f9d3f94e154cd5fd409105d34/books/kestrel/axe/r1cs/.sys/lift-r1cs-common%40useless-runes.lsp
lisp
(SYMBOL<-OF-CARS) (CONSP-AND-SYMBOLP-CAR) (ALL-CONSP-AND-SYMBOLP-CAR) (ALL-CONSP-AND-SYMBOLP-CAR-OF-CONS-FOR-DEFMERGESORT (70 7 (:REWRITE CONSP-FROM-LEN-CHEAP)) (35 35 (:TYPE-PRESCRIPTION LEN)) (14 7 (:REWRITE DEFAULT-<-2)) (10 5 (:REWRITE SYMBOLP-OF-CAR-WHEN-SYMBOL-LISTP-CHEAP)) (8 8 (:REWRITE DEFAULT-CAR)) (7 7 (:REWRITE LEN-WHEN-NOT-CONSP-CHEAP)) (7 7 (:REWRITE DEFAULT-<-1)) (7 7 (:REWRITE CONSP-WHEN-LEN-GREATER)) (7 7 (:REWRITE CONSP-WHEN-LEN-EQUAL-CONSTANT)) (7 7 (:LINEAR LEN-POSITIVE-WHEN-CONSP-LINEAR-CHEAP)) (5 5 (:TYPE-PRESCRIPTION SYMBOL-LISTP)) (4 2 (:REWRITE SYMBOLP-OF-CAR-OF-CAR-WHEN-SYMBOL-ALISTP-CHEAP)) (3 3 (:REWRITE DEFAULT-CDR)) (2 2 (:TYPE-PRESCRIPTION SYMBOL-ALISTP)) ) (USE-ALL-CONSP-AND-SYMBOLP-CAR-FOR-CAR-FOR-DEFMERGESORT (39 4 (:REWRITE CONSP-FROM-LEN-CHEAP)) (9 6 (:LINEAR LEN-POSITIVE-WHEN-CONSP-LINEAR-CHEAP)) (8 4 (:REWRITE DEFAULT-<-2)) (7 7 (:REWRITE LEN-WHEN-NOT-CONSP-CHEAP)) (7 7 (:REWRITE DEFAULT-CAR)) (4 4 (:REWRITE DEFAULT-<-1)) (4 4 (:REWRITE CONSP-WHEN-LEN-GREATER)) (4 4 (:REWRITE CONSP-WHEN-LEN-EQUAL-CONSTANT)) (4 2 (:REWRITE SYMBOLP-OF-CAR-WHEN-SYMBOL-LISTP-CHEAP)) (4 2 (:REWRITE SYMBOLP-OF-CAR-OF-CAR-WHEN-SYMBOL-ALISTP-CHEAP)) (2 2 (:TYPE-PRESCRIPTION SYMBOL-LISTP)) (2 2 (:TYPE-PRESCRIPTION SYMBOL-ALISTP)) (1 1 (:REWRITE DEFAULT-CDR)) ) (ALL-CONSP-AND-SYMBOLP-CAR-OF-CDR-FOR-DEFMERGESORT (20 2 (:REWRITE CONSP-FROM-LEN-CHEAP)) (10 10 (:TYPE-PRESCRIPTION LEN)) (4 2 (:REWRITE DEFAULT-<-2)) (4 1 (:REWRITE USE-ALL-CONSP-AND-SYMBOLP-CAR-FOR-CAR-FOR-DEFMERGESORT)) (2 2 (:REWRITE LEN-WHEN-NOT-CONSP-CHEAP)) (2 2 (:REWRITE DEFAULT-CAR)) (2 2 (:REWRITE DEFAULT-<-1)) (2 2 (:REWRITE CONSP-WHEN-LEN-GREATER)) (2 2 (:REWRITE CONSP-WHEN-LEN-EQUAL-CONSTANT)) (2 2 (:LINEAR LEN-POSITIVE-WHEN-CONSP-LINEAR-CHEAP)) (2 1 (:REWRITE SYMBOLP-OF-CAR-WHEN-SYMBOL-LISTP-CHEAP)) (2 1 (:REWRITE SYMBOLP-OF-CAR-OF-CAR-WHEN-SYMBOL-ALISTP-CHEAP)) (1 1 (:TYPE-PRESCRIPTION SYMBOL-LISTP)) (1 1 (:TYPE-PRESCRIPTION SYMBOL-ALISTP)) ) (ALL-CONSP-AND-SYMBOLP-CAR) (MERGE-SYMBOL<-OF-CARS (296 32 (:REWRITE CONSP-FROM-LEN-CHEAP)) (112 8 (:DEFINITION TRUE-LISTP)) (56 28 (:REWRITE DEFAULT-<-2)) (52 52 (:REWRITE LEN-WHEN-NOT-CONSP-CHEAP)) (48 12 (:REWRITE DEFAULT-CAR)) (32 32 (:REWRITE CONSP-WHEN-LEN-EQUAL-CONSTANT)) (28 28 (:REWRITE DEFAULT-<-1)) (28 28 (:REWRITE CONSP-WHEN-LEN-GREATER)) (28 14 (:TYPE-PRESCRIPTION TRUE-LISTP-REVAPPEND-TYPE-PRESCRIPTION)) (8 8 (:REWRITE DEFAULT-CDR)) (8 4 (:REWRITE SYMBOLP-OF-CAR-WHEN-SYMBOL-LISTP-CHEAP)) (8 4 (:REWRITE SYMBOLP-OF-CAR-OF-CAR-WHEN-SYMBOL-ALISTP-CHEAP)) (4 4 (:TYPE-PRESCRIPTION SYMBOL-LISTP)) (4 4 (:TYPE-PRESCRIPTION SYMBOL-ALISTP)) ) (CONSP-OF-MERGE-SYMBOL<-OF-CARS (127 16 (:REWRITE CONSP-FROM-LEN-CHEAP)) (25 25 (:REWRITE LEN-WHEN-NOT-CONSP-CHEAP)) (25 13 (:REWRITE DEFAULT-<-2)) (16 16 (:REWRITE CONSP-WHEN-LEN-GREATER)) (16 16 (:REWRITE CONSP-WHEN-LEN-EQUAL-CONSTANT)) (13 13 (:REWRITE DEFAULT-<-1)) (8 8 (:REWRITE DEFAULT-CAR)) (5 3 (:REWRITE DEFAULT-+-2)) (5 1 (:REWRITE LEN-OF-CDR)) (4 2 (:TYPE-PRESCRIPTION TRUE-LISTP-REVAPPEND-TYPE-PRESCRIPTION)) (4 1 (:REWRITE <-OF-+-ARG2-WHEN-NEGATIVE-CONSTANT)) (3 3 (:REWRITE DEFAULT-+-1)) (2 2 (:TYPE-PRESCRIPTION TRUE-LISTP)) (2 2 (:REWRITE DEFAULT-CDR)) (1 1 (:REWRITE CONSP-OF-CDR-WHEN-LEN-KNOWN)) ) (MERGE-SORT-SYMBOL<-OF-CARS) (CONSP-OF-MERGE-SORT-SYMBOL<-OF-CARS (72 7 (:REWRITE DEFAULT-CDR)) (38 38 (:REWRITE LEN-WHEN-NOT-CONSP-CHEAP)) (38 19 (:REWRITE DEFAULT-<-2)) (31 31 (:REWRITE CONSP-WHEN-LEN-EQUAL-CONSTANT)) (25 25 (:REWRITE CONSP-WHEN-LEN-GREATER)) (19 19 (:REWRITE DEFAULT-<-1)) (12 6 (:TYPE-PRESCRIPTION TRUE-LISTP-OF-MV-NTH-1-OF-SPLIT-LIST-FAST)) (12 6 (:REWRITE DEFAULT-+-2)) (6 6 (:TYPE-PRESCRIPTION TRUE-LISTP)) (6 6 (:REWRITE DEFAULT-+-1)) (6 1 (:LINEAR LEN-OF-CDR-LINEAR-STRONG)) (4 4 (:REWRITE CONSP-OF-CDR-WHEN-LEN-KNOWN)) ) (ALL-CONSP-AND-SYMBOLP-CAR-OF-MV-NTH-0-OF-SPLIT-LIST-FAST-AUX) (ALL-CONSP-AND-SYMBOLP-CAR-OF-MV-NTH-0-OF-SPLIT-LIST-FAST) (ALL-CONSP-AND-SYMBOLP-CAR-OF-MV-NTH-1-OF-SPLIT-LIST-FAST-AUX) (ALL-CONSP-AND-SYMBOLP-CAR-OF-MV-NTH-1-OF-SPLIT-LIST-FAST) (ALL-CONSP-AND-SYMBOLP-CAR-OF-MERGE-SYMBOL<-OF-CARS) (TRUE-LISTP-OF-MERGE-SYMBOL<-OF-CARS) (TRUE-LISTP-OF-MERGE-SORT-SYMBOL<-OF-CARS) (ALL-CONSP-AND-SYMBOLP-CAR-OF-MERGE-SORT-SYMBOL<-OF-CARS) (MERGE-SORT-SYMBOL<-OF-CARS) (PERM-OF-MERGE-SYMBOL<-OF-CARS) (PERM-OF-MERGE-SORT-SYMBOL<-OF-CARS) (R1CS::CONSP-OF-NTH-WHEN-SYMBOL-ALISTP (158 16 (:REWRITE CONSP-FROM-LEN-CHEAP)) (44 26 (:REWRITE DEFAULT-<-2)) (26 26 (:REWRITE DEFAULT-<-1)) (25 25 (:REWRITE LEN-WHEN-NOT-CONSP-CHEAP)) (18 18 (:REWRITE DEFAULT-CAR)) (16 16 (:REWRITE CONSP-WHEN-LEN-GREATER)) (16 16 (:REWRITE CONSP-WHEN-LEN-EQUAL-CONSTANT)) (10 5 (:REWRITE SYMBOLP-OF-CAR-WHEN-SYMBOL-LISTP-CHEAP)) (10 5 (:REWRITE SYMBOLP-OF-CAR-OF-CAR-WHEN-SYMBOL-ALISTP-CHEAP)) (8 2 (:REWRITE SYMBOL-ALISTP-OF-CDR)) (5 5 (:TYPE-PRESCRIPTION SYMBOL-LISTP)) (5 5 (:REWRITE DEFAULT-CDR)) (5 5 (:REWRITE DEFAULT-+-2)) (5 5 (:REWRITE DEFAULT-+-1)) (3 3 (:REWRITE ZP-OPEN)) ) (R1CS::ALL-CONSP-AND-SYMBOLP-CAR-WHEN-SYMBOL-ALISTP (130 16 (:REWRITE CONSP-FROM-LEN-CHEAP)) (26 13 (:REWRITE DEFAULT-<-2)) (21 21 (:REWRITE DEFAULT-CAR)) (16 16 (:REWRITE LEN-WHEN-NOT-CONSP-CHEAP)) (16 16 (:REWRITE CONSP-WHEN-LEN-GREATER)) (16 16 (:REWRITE CONSP-WHEN-LEN-EQUAL-CONSTANT)) (14 7 (:REWRITE SYMBOLP-OF-CAR-WHEN-SYMBOL-LISTP-CHEAP)) (13 13 (:REWRITE DEFAULT-<-1)) (8 2 (:REWRITE SYMBOL-ALISTP-OF-CDR)) (7 7 (:TYPE-PRESCRIPTION SYMBOL-LISTP)) (4 4 (:REWRITE DEFAULT-CDR)) ) (R1CS::SYMBOL-ALISTP-OF-MERGE-SYMBOL<-OF-CARS (1158 127 (:REWRITE CONSP-FROM-LEN-CHEAP)) (253 149 (:REWRITE DEFAULT-CAR)) (223 116 (:REWRITE DEFAULT-<-2)) (177 39 (:REWRITE DEFAULT-CDR)) (149 149 (:REWRITE LEN-WHEN-NOT-CONSP-CHEAP)) (127 127 (:REWRITE CONSP-WHEN-LEN-GREATER)) (127 127 (:REWRITE CONSP-WHEN-LEN-EQUAL-CONSTANT)) (116 116 (:REWRITE DEFAULT-<-1)) (90 6 (:DEFINITION REVAPPEND)) (62 31 (:REWRITE SYMBOLP-OF-CAR-WHEN-SYMBOL-LISTP-CHEAP)) (45 9 (:REWRITE LEN-OF-CDR)) (36 9 (:REWRITE <-OF-+-ARG2-WHEN-NEGATIVE-CONSTANT)) (31 31 (:TYPE-PRESCRIPTION SYMBOL-LISTP)) (14 14 (:REWRITE CONSP-OF-CDR-WHEN-LEN-KNOWN)) (9 9 (:REWRITE DEFAULT-+-2)) (9 9 (:REWRITE DEFAULT-+-1)) (2 2 (:REWRITE TRUE-LIST-FIX-WHEN-NOT-CONS-CHEAP)) ) (R1CS::SYMBOL-ALISTP-OF-MV-NTH-0-OF-SPLIT-LIST-FAST-AUX (1630 168 (:REWRITE CONSP-FROM-LEN-CHEAP)) (299 173 (:REWRITE DEFAULT-CAR)) (296 154 (:REWRITE DEFAULT-<-2)) (168 168 (:REWRITE CONSP-WHEN-LEN-EQUAL-CONSTANT)) (166 166 (:REWRITE CONSP-WHEN-LEN-GREATER)) (160 154 (:REWRITE DEFAULT-<-1)) (100 50 (:REWRITE SYMBOLP-OF-CAR-WHEN-SYMBOL-LISTP-CHEAP)) (79 52 (:REWRITE DEFAULT-+-2)) (78 15 (:REWRITE <-OF-+-ARG2-WHEN-NEGATIVE-CONSTANT)) (52 52 (:REWRITE DEFAULT-+-1)) (50 50 (:TYPE-PRESCRIPTION SYMBOL-LISTP)) (29 29 (:REWRITE CONSP-OF-CDR-WHEN-LEN-KNOWN)) (13 13 (:REWRITE LEN-OF-CDDR-WHEN-EQUAL-OF-LEN)) ) (R1CS::SYMBOL-ALISTP-OF-MV-NTH-0-OF-SPLIT-LIST-FAST (57 4 (:REWRITE CONSP-FROM-LEN-CHEAP)) (48 1 (:DEFINITION SPLIT-LIST-FAST-AUX)) (37 1 (:DEFINITION SYMBOL-ALISTP)) (11 5 (:LINEAR LEN-POSITIVE-WHEN-CONSP-LINEAR-CHEAP)) (11 1 (:REWRITE <-OF-+-ARG2-WHEN-NEGATIVE-CONSTANT)) (9 9 (:REWRITE LEN-WHEN-NOT-CONSP-CHEAP)) (8 4 (:REWRITE DEFAULT-<-2)) (8 1 (:REWRITE LEN-OF-CDR)) (5 5 (:REWRITE DEFAULT-CDR)) (4 4 (:REWRITE DEFAULT-CAR)) (4 4 (:REWRITE DEFAULT-<-1)) (4 4 (:REWRITE CONSP-WHEN-LEN-GREATER)) (4 4 (:REWRITE CONSP-WHEN-LEN-EQUAL-CONSTANT)) (4 1 (:REWRITE SYMBOL-ALISTP-OF-CDR)) (2 1 (:REWRITE SYMBOLP-OF-CAR-WHEN-SYMBOL-LISTP-CHEAP)) (2 1 (:REWRITE SYMBOLP-OF-CAR-OF-CAR-WHEN-SYMBOL-ALISTP-CHEAP)) (2 1 (:REWRITE DEFAULT-+-2)) (1 1 (:TYPE-PRESCRIPTION SYMBOL-LISTP)) (1 1 (:REWRITE EQUAL-OF-LEN-AND-0)) (1 1 (:REWRITE DEFAULT-+-1)) (1 1 (:REWRITE CONSP-OF-CDR-WHEN-LEN-KNOWN)) ) (R1CS::SYMBOL-ALISTP-OF-MV-NTH-1-OF-SPLIT-LIST-FAST-AUX (366 75 (:REWRITE DEFAULT-CDR)) (297 297 (:REWRITE LEN-WHEN-NOT-CONSP-CHEAP)) (215 134 (:REWRITE DEFAULT-+-2)) (165 91 (:REWRITE DEFAULT-<-2)) (134 134 (:REWRITE DEFAULT-+-1)) (113 91 (:REWRITE DEFAULT-<-1)) (109 109 (:REWRITE CONSP-WHEN-LEN-EQUAL-CONSTANT)) (91 91 (:REWRITE CONSP-WHEN-LEN-GREATER)) (44 22 (:REWRITE SYMBOLP-OF-CAR-WHEN-SYMBOL-LISTP-CHEAP)) (38 23 (:REWRITE DEFAULT-*-2)) (30 30 (:REWRITE LEN-OF-CDDR-WHEN-EQUAL-OF-LEN)) (30 3 (:LINEAR LEN-OF-CDR-LINEAR-STRONG)) (24 3 (:LINEAR LEN-OF-CDR-LINEAR)) (23 23 (:REWRITE DEFAULT-*-1)) (23 23 (:REWRITE CONSP-OF-CDR-WHEN-LEN-KNOWN)) (22 22 (:TYPE-PRESCRIPTION SYMBOL-LISTP)) (3 3 (:REWRITE <-OF-+-COMBINE-CONSTANTS-2)) (3 3 (:REWRITE <-OF-+-ARG1-WHEN-NEGATIVE-CONSTANT)) ) (R1CS::SYMBOL-ALISTP-OF-MV-NTH-1-OF-SPLIT-LIST-FAST (57 4 (:REWRITE CONSP-FROM-LEN-CHEAP)) (48 1 (:DEFINITION SPLIT-LIST-FAST-AUX)) (37 1 (:DEFINITION SYMBOL-ALISTP)) (28 28 (:TYPE-PRESCRIPTION LEN)) (11 5 (:LINEAR LEN-POSITIVE-WHEN-CONSP-LINEAR-CHEAP)) (11 1 (:REWRITE <-OF-+-ARG2-WHEN-NEGATIVE-CONSTANT)) (8 4 (:REWRITE DEFAULT-<-2)) (8 1 (:REWRITE LEN-OF-CDR)) (7 7 (:REWRITE LEN-WHEN-NOT-CONSP-CHEAP)) (5 5 (:REWRITE DEFAULT-CDR)) (4 4 (:REWRITE DEFAULT-CAR)) (4 4 (:REWRITE DEFAULT-<-1)) (4 4 (:REWRITE CONSP-WHEN-LEN-GREATER)) (4 4 (:REWRITE CONSP-WHEN-LEN-EQUAL-CONSTANT)) (4 1 (:REWRITE SYMBOL-ALISTP-OF-CDR)) (2 1 (:REWRITE SYMBOLP-OF-CAR-WHEN-SYMBOL-LISTP-CHEAP)) (2 1 (:REWRITE SYMBOLP-OF-CAR-OF-CAR-WHEN-SYMBOL-ALISTP-CHEAP)) (2 1 (:REWRITE DEFAULT-+-2)) (1 1 (:TYPE-PRESCRIPTION SYMBOL-LISTP)) (1 1 (:REWRITE EQUAL-OF-LEN-AND-0)) (1 1 (:REWRITE DEFAULT-+-1)) (1 1 (:REWRITE CONSP-OF-CDR-WHEN-LEN-KNOWN)) ) (R1CS::SYMBOL-ALISTP-OF-MERGE-SORT-SYMBOL<-OF-CARS (90 19 (:REWRITE DEFAULT-CDR)) (81 13 (:REWRITE CONSP-OF-MERGE-SORT-SYMBOL<-OF-CARS)) (72 36 (:REWRITE DEFAULT-CAR)) (54 28 (:REWRITE DEFAULT-<-2)) (51 51 (:REWRITE LEN-WHEN-NOT-CONSP-CHEAP)) (48 12 (:REWRITE SYMBOL-ALISTP-OF-CDR)) (42 42 (:REWRITE CONSP-WHEN-LEN-EQUAL-CONSTANT)) (32 32 (:REWRITE CONSP-WHEN-LEN-GREATER)) (28 28 (:REWRITE DEFAULT-<-1)) (22 11 (:REWRITE SYMBOLP-OF-CAR-WHEN-SYMBOL-LISTP-CHEAP)) (22 11 (:REWRITE SYMBOLP-OF-CAR-OF-CAR-WHEN-SYMBOL-ALISTP-CHEAP)) (22 4 (:REWRITE CONSP-OF-MV-NTH-1-OF-SPLIT-LIST-FAST)) (15 3 (:REWRITE CONSP-OF-MV-NTH-0-OF-SPLIT-LIST-FAST)) (12 6 (:REWRITE DEFAULT-+-2)) (11 11 (:TYPE-PRESCRIPTION SYMBOL-LISTP)) (6 6 (:REWRITE DEFAULT-+-1)) (6 1 (:LINEAR LEN-OF-CDR-LINEAR-STRONG)) (4 4 (:TYPE-PRESCRIPTION TRUE-LISTP-OF-MV-NTH-1-OF-SPLIT-LIST-FAST)) (4 4 (:REWRITE CONSP-OF-CDR-WHEN-LEN-KNOWN)) (3 3 (:TYPE-PRESCRIPTION TRUE-LISTP-OF-MV-NTH-0-OF-SPLIT-LIST-FAST)) ) (R1CS::MAKE-VALUATION-FROM-KEYWORD-VARS-AUX (9 1 (:REWRITE CONSP-FROM-LEN-CHEAP)) (2 2 (:REWRITE SYMBOL-LISTP-WHEN-SUBSETP-EQUAL-1)) (2 2 (:REWRITE LEN-WHEN-NOT-CONSP-CHEAP)) (2 1 (:REWRITE DEFAULT-SYMBOL-NAME)) (2 1 (:REWRITE DEFAULT-<-2)) (2 1 (:LINEAR LEN-POSITIVE-WHEN-CONSP-LINEAR-CHEAP)) (1 1 (:REWRITE DEFAULT-CDR)) (1 1 (:REWRITE DEFAULT-CAR)) (1 1 (:REWRITE DEFAULT-<-1)) (1 1 (:REWRITE CONSP-WHEN-LEN-GREATER)) (1 1 (:REWRITE CONSP-WHEN-LEN-EQUAL-CONSTANT)) ) (R1CS::MAKE-VALUATION-FROM-KEYWORD-VARS) (R1CS::MAKE-VALUATION-FROM-KEYWORD-VARS2-AUX (157 1 (:REWRITE TAKE-DOES-NOTHING)) (149 1 (:REWRITE NTHCDR-WHEN-NOT-POSP)) (133 1 (:DEFINITION POSP)) (109 109 (:TYPE-PRESCRIPTION <=-OF-FLOOR-AND-0-WHEN-NONPOSITIVE-AND-NONNEGATIVE-TYPE)) (109 109 (:TYPE-PRESCRIPTION <=-OF-FLOOR-AND-0-WHEN-NONNEGATIVE-AND-NONPOSITIVE-TYPE)) (109 109 (:TYPE-PRESCRIPTION <=-OF-0-AND-FLOOR-WHEN-BOTH-NONPOSITIVE-TYPE)) (109 109 (:TYPE-PRESCRIPTION <-OF-FLOOR-AND-0-WHEN-POSITIVE-AND-NEGATIVE-TYPE)) (109 109 (:TYPE-PRESCRIPTION <-OF-FLOOR-AND-0-WHEN-NEGATIVE-AND-POSITIVE-TYPE)) (39 13 (:REWRITE DEFAULT-<-1)) (35 2 (:LINEAR FLOOR-WEAK-MONOTONE-LINEAR-1)) (18 18 (:REWRITE FLOOR-WHEN-NOT-RATIONALP-OF-QUOTIENT)) (18 18 (:REWRITE FLOOR-WHEN-NOT-RATIONALP-ARG1)) (18 18 (:REWRITE FLOOR-WHEN-NEGATIVE-AND-SMALL-CHEAP)) (18 18 (:REWRITE FLOOR-WHEN-I-IS-NOT-AN-ACL2-NUMBERP)) (18 18 (:REWRITE FLOOR-WHEN-<)) (18 18 (:REWRITE FLOOR-MINUS-NEGATIVE-CONSTANT)) (13 13 (:REWRITE DEFAULT-<-2)) (12 12 (:REWRITE DEFAULT-*-2)) (12 12 (:REWRITE DEFAULT-*-1)) (11 11 (:REWRITE LEN-WHEN-NOT-CONSP-CHEAP)) (11 4 (:REWRITE DEFAULT-+-2)) (8 1 (:REWRITE DEFAULT-UNARY-MINUS)) (6 6 (:TYPE-PRESCRIPTION TRUE-LISTP)) (6 6 (:LINEAR LEN-POSITIVE-WHEN-CONSP-LINEAR-CHEAP)) (6 1 (:REWRITE <-OF-0-AND-FLOOR)) (4 4 (:REWRITE SYMBOL-LISTP-WHEN-SUBSETP-EQUAL-1)) (4 4 (:REWRITE DEFAULT-+-1)) (2 2 (:LINEAR FLOOR-WEAK-MONOTONE-LINEAR=-2)) (1 1 (:TYPE-PRESCRIPTION POSP)) (1 1 (:REWRITE NTHCDR-WHEN-NOT-CONSP-CHEAP)) (1 1 (:REWRITE NTHCDR-WHEN-EQUAL-OF-LEN)) (1 1 (:REWRITE EQUAL-OF-FLOOR-SAME)) (1 1 (:REWRITE <-OF-+-COMBINE-CONSTANTS-2)) (1 1 (:REWRITE <-OF-+-ARG1-WHEN-NEGATIVE-CONSTANT)) ) (R1CS::MAKE-VALUATION-FROM-KEYWORD-VARS2) (R1CS::MAKE-FEP-ASSUMPTIONS-FROM-KEYWORD-VARS-AUX (9 1 (:REWRITE CONSP-FROM-LEN-CHEAP)) (2 2 (:REWRITE SYMBOL-LISTP-WHEN-SUBSETP-EQUAL-1)) (2 2 (:REWRITE LEN-WHEN-NOT-CONSP-CHEAP)) (2 1 (:REWRITE DEFAULT-SYMBOL-NAME)) (2 1 (:REWRITE DEFAULT-<-2)) (2 1 (:LINEAR LEN-POSITIVE-WHEN-CONSP-LINEAR-CHEAP)) (1 1 (:REWRITE DEFAULT-CDR)) (1 1 (:REWRITE DEFAULT-CAR)) (1 1 (:REWRITE DEFAULT-<-1)) (1 1 (:REWRITE CONSP-WHEN-LEN-GREATER)) (1 1 (:REWRITE CONSP-WHEN-LEN-EQUAL-CONSTANT)) ) (R1CS::MAKE-FEP-ASSUMPTIONS-FROM-KEYWORD-VARS) (R1CS::MAKE-BITP-ASSUMPTIONS-FROM-KEYWORD-VARS-AUX (9 1 (:REWRITE CONSP-FROM-LEN-CHEAP)) (2 2 (:REWRITE SYMBOL-LISTP-WHEN-SUBSETP-EQUAL-1)) (2 2 (:REWRITE LEN-WHEN-NOT-CONSP-CHEAP)) (2 1 (:REWRITE DEFAULT-SYMBOL-NAME)) (2 1 (:REWRITE DEFAULT-<-2)) (2 1 (:LINEAR LEN-POSITIVE-WHEN-CONSP-LINEAR-CHEAP)) (1 1 (:REWRITE DEFAULT-CDR)) (1 1 (:REWRITE DEFAULT-CAR)) (1 1 (:REWRITE DEFAULT-<-1)) (1 1 (:REWRITE CONSP-WHEN-LEN-GREATER)) (1 1 (:REWRITE CONSP-WHEN-LEN-EQUAL-CONSTANT)) ) (R1CS::MAKE-BITP-ASSUMPTIONS-FROM-KEYWORD-VARS) (R1CS::MAKE-SYMBOLIC-VALUATION-FOR-ALIST-AUX (29 3 (:REWRITE CONSP-FROM-LEN-CHEAP)) (6 4 (:LINEAR LEN-POSITIVE-WHEN-CONSP-LINEAR-CHEAP)) (6 3 (:REWRITE DEFAULT-<-2)) (5 5 (:REWRITE LEN-WHEN-NOT-CONSP-CHEAP)) (5 5 (:REWRITE DEFAULT-CAR)) (3 3 (:REWRITE DEFAULT-<-1)) (3 3 (:REWRITE CONSP-WHEN-LEN-GREATER)) (3 3 (:REWRITE CONSP-WHEN-LEN-EQUAL-CONSTANT)) (2 2 (:REWRITE DEFAULT-CDR)) (2 1 (:REWRITE SYMBOLP-OF-CAR-WHEN-SYMBOL-LISTP-CHEAP)) (2 1 (:REWRITE SYMBOLP-OF-CAR-OF-CAR-WHEN-SYMBOL-ALISTP-CHEAP)) (1 1 (:TYPE-PRESCRIPTION SYMBOL-LISTP)) ) (R1CS::MAKE-SYMBOLIC-VALUATION-FOR-ALIST (495 49 (:REWRITE CONSP-FROM-LEN-CHEAP)) (276 20 (:DEFINITION NTH)) (181 13 (:REWRITE R1CS::CONSP-OF-NTH-WHEN-SYMBOL-ALISTP)) (154 144 (:REWRITE LEN-WHEN-NOT-CONSP-CHEAP)) (153 10 (:REWRITE TAKE-DOES-NOTHING)) (141 81 (:REWRITE DEFAULT-CAR)) (138 15 (:REWRITE SYMBOL-ALISTP-OF-CDR)) (132 20 (:REWRITE ZP-OPEN)) (114 70 (:REWRITE DEFAULT-<-2)) (114 36 (:REWRITE <-OF-+-ARG2-WHEN-NEGATIVE-CONSTANT)) (112 90 (:REWRITE DEFAULT-+-2)) (110 22 (:REWRITE LEN-OF-CDR)) (90 90 (:REWRITE DEFAULT-+-1)) (87 29 (:REWRITE +-COMBINE-CONSTANTS)) (76 17 (:REWRITE EQUAL-OF-+-WHEN-NEGATIVE-CONSTANT)) (72 70 (:REWRITE DEFAULT-<-1)) (66 10 (:REWRITE <-OF-+-ARG1-WHEN-NEGATIVE-CONSTANT)) (64 8 (:DEFINITION NATP)) (49 49 (:REWRITE CONSP-WHEN-LEN-EQUAL-CONSTANT)) (46 46 (:REWRITE CONSP-WHEN-LEN-GREATER)) (44 22 (:REWRITE SYMBOLP-OF-CAR-WHEN-SYMBOL-LISTP-CHEAP)) (36 36 (:REWRITE DEFAULT-CDR)) (32 10 (:REWRITE LEN-OF-REVERSE-LIST)) (22 22 (:TYPE-PRESCRIPTION SYMBOL-LISTP)) (21 3 (:REWRITE EQUAL-OF-+-AND-+-CANCEL-CONSTANTS)) (14 10 (:DEFINITION FIX)) (10 10 (:REWRITE EQUAL-OF-+-COMBINE-CONSTANTS)) (10 10 (:REWRITE EQUAL-OF-+-CANCEL-SAME-2)) (8 8 (:TYPE-PRESCRIPTION NATP)) (8 8 (:REWRITE NATP-OF-+-WHEN-NATP-AND-NATP)) (7 7 (:REWRITE CONSP-OF-CDR-WHEN-LEN-KNOWN)) (6 6 (:REWRITE <-OF-+-COMBINE-CONSTANTS-1)) (6 6 (:REWRITE <-OF-+-CANCEL-1-2)) (2 1 (:REWRITE TRUE-LIST-FIX-WHEN-NOT-CONS-CHEAP)) (2 1 (:REWRITE APPEND-WHEN-NOT-CONSP-ARG1-CHEAP)) ) (R1CS::MAKE-EFFICIENT-SYMBOLIC-VALUATION-FOR-ALIST-AUX (157 1 (:REWRITE TAKE-DOES-NOTHING)) (149 1 (:REWRITE NTHCDR-WHEN-NOT-POSP)) (133 1 (:DEFINITION POSP)) (109 109 (:TYPE-PRESCRIPTION <=-OF-FLOOR-AND-0-WHEN-NONPOSITIVE-AND-NONNEGATIVE-TYPE)) (109 109 (:TYPE-PRESCRIPTION <=-OF-FLOOR-AND-0-WHEN-NONNEGATIVE-AND-NONPOSITIVE-TYPE)) (109 109 (:TYPE-PRESCRIPTION <=-OF-0-AND-FLOOR-WHEN-BOTH-NONPOSITIVE-TYPE)) (109 109 (:TYPE-PRESCRIPTION <-OF-FLOOR-AND-0-WHEN-POSITIVE-AND-NEGATIVE-TYPE)) (109 109 (:TYPE-PRESCRIPTION <-OF-FLOOR-AND-0-WHEN-NEGATIVE-AND-POSITIVE-TYPE)) (45 19 (:REWRITE DEFAULT-<-1)) (43 7 (:REWRITE CONSP-FROM-LEN-CHEAP)) (35 2 (:LINEAR FLOOR-WEAK-MONOTONE-LINEAR-1)) (34 1 (:DEFINITION NTH)) (23 19 (:REWRITE DEFAULT-<-2)) (19 5 (:REWRITE DEFAULT-+-2)) (18 18 (:REWRITE LEN-WHEN-NOT-CONSP-CHEAP)) (18 18 (:REWRITE FLOOR-WHEN-NOT-RATIONALP-OF-QUOTIENT)) (18 18 (:REWRITE FLOOR-WHEN-NOT-RATIONALP-ARG1)) (18 18 (:REWRITE FLOOR-WHEN-NEGATIVE-AND-SMALL-CHEAP)) (18 18 (:REWRITE FLOOR-WHEN-I-IS-NOT-AN-ACL2-NUMBERP)) (18 18 (:REWRITE FLOOR-WHEN-<)) (18 18 (:REWRITE FLOOR-MINUS-NEGATIVE-CONSTANT)) (12 12 (:REWRITE DEFAULT-*-2)) (12 12 (:REWRITE DEFAULT-*-1)) (12 11 (:LINEAR LEN-POSITIVE-WHEN-CONSP-LINEAR-CHEAP)) (12 1 (:REWRITE ZP-OPEN)) (10 2 (:REWRITE <-OF-0-AND-FLOOR)) (8 1 (:REWRITE DEFAULT-UNARY-MINUS)) (7 7 (:REWRITE DEFAULT-CAR)) (7 7 (:REWRITE CONSP-WHEN-LEN-EQUAL-CONSTANT)) (6 6 (:TYPE-PRESCRIPTION TRUE-LISTP)) (5 5 (:REWRITE DEFAULT-+-1)) (5 5 (:REWRITE CONSP-WHEN-LEN-GREATER)) (5 3 (:REWRITE DEFAULT-CDR)) (4 2 (:REWRITE SYMBOLP-OF-CAR-WHEN-SYMBOL-LISTP-CHEAP)) (2 2 (:TYPE-PRESCRIPTION SYMBOL-LISTP)) (2 2 (:LINEAR FLOOR-WEAK-MONOTONE-LINEAR=-2)) (1 1 (:TYPE-PRESCRIPTION POSP)) (1 1 (:REWRITE NTHCDR-WHEN-NOT-CONSP-CHEAP)) (1 1 (:REWRITE NTHCDR-WHEN-EQUAL-OF-LEN)) (1 1 (:REWRITE EQUAL-OF-FLOOR-SAME)) (1 1 (:REWRITE <-OF-+-COMBINE-CONSTANTS-2)) (1 1 (:REWRITE <-OF-+-ARG1-WHEN-NEGATIVE-CONSTANT)) ) (R1CS::MAKE-EFFICIENT-SYMBOLIC-VALUATION-FOR-ALIST)
c780eb011a47fbd56acf16f76a3ab01ab83fc25428e8b6ce95b60d5713d4e9ae
sybilant/sybilant
label.clj
(ns sybilant.ast.label (:require [sybilant.ast :as-alias ast] [sybilant.ast.symbol :as ast.symbol])) (def ^:private ^:const +type+ {:kind ::ast/type :name ::ast/label}) (defn make "Make label from name. nil if name is not a valid symbol." [name] (when (ast.symbol/valid? name) {:type +type+ :name name})) (defn type? "True if o is the label type." [o] (= +type+ o)) (defn valid? "True if o is a valid label. A label is valid if it has the label type and its name is a valid symbol." [o] (and (map? o) (type? (:type o)) (ast.symbol/valid? (:name o))))
null
https://raw.githubusercontent.com/sybilant/sybilant/445afcba2ff3d7fb4c4f37526901c2ddedf65c91/src/sybilant/ast/label.clj
clojure
(ns sybilant.ast.label (:require [sybilant.ast :as-alias ast] [sybilant.ast.symbol :as ast.symbol])) (def ^:private ^:const +type+ {:kind ::ast/type :name ::ast/label}) (defn make "Make label from name. nil if name is not a valid symbol." [name] (when (ast.symbol/valid? name) {:type +type+ :name name})) (defn type? "True if o is the label type." [o] (= +type+ o)) (defn valid? "True if o is a valid label. A label is valid if it has the label type and its name is a valid symbol." [o] (and (map? o) (type? (:type o)) (ast.symbol/valid? (:name o))))
e126de470a5b11845d3e193daff1ca04fd5fff7796693006cb914b3a591e4e55
TrustInSoft/tis-interpreter
metrics_parameters.ml
Modified by TrustInSoft (**************************************************************************) (* *) This file is part of Frama - C. (* *) Copyright ( C ) 2007 - 2015 CEA ( Commissariat à l'énergie atomique et aux énergies (* alternatives) *) (* *) (* 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 . (* *) (* It 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. *) (* *) See the GNU Lesser General Public License version 2.1 for more details ( enclosed in the file licenses / LGPLv2.1 ) . (* *) (**************************************************************************) include Plugin.Register (struct let name = "metrics" let shortname = "metrics" let help = "syntactic metrics" end) module Enabled = WithOutput (struct let option_name = "-metrics" let help = "activate metrics computation" let output_by_default = true end) module ByFunction = WithOutput (struct let option_name = "-metrics-by-function" let help = "also compute metrics on a per-function basis" let output_by_default = true end) module OutputFile = Empty_string (struct let option_name = "-metrics-output" let arg_name = "filename" let help = "print some metrics into the specified file; \ the output format is recognized through the extension." end) module ValueCoverage = WithOutput ( struct let option_name = "-metrics-value-cover" let help = "estimate value analysis coverage w.r.t. \ to reachable syntactic definitions" let output_by_default = true end) module AstType = String (struct let option_name = "-metrics-ast" let arg_name = "[cabs | cil | acsl]" let help = "apply metrics to Cabs or CIL AST, or to ACSL specs" let default = "cil" end ) module Libc = False (struct let option_name = "-metrics-libc" let help = "show functions from Frama-C standard C library in the \ results; deactivated by default." end ) let () = AstType.set_possible_values ["cil"; "cabs"; "acsl"] module SyntacticallyReachable = Kernel_function_set (struct let option_name = "-metrics-cover" let arg_name = "f1,..,fn" let help = "compute an overapproximation of the functions reachable from \ f1,..,fn." end ) (* Local Variables: compile-command: "make -C ../../.." End: *)
null
https://raw.githubusercontent.com/TrustInSoft/tis-interpreter/33132ce4a825494ea48bf2dd6fd03a56b62cc5c3/src/plugins/metrics/metrics_parameters.ml
ocaml
************************************************************************ alternatives) you can redistribute it and/or modify it under the terms of the GNU It 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. ************************************************************************ Local Variables: compile-command: "make -C ../../.." End:
Modified by TrustInSoft This file is part of Frama - C. Copyright ( C ) 2007 - 2015 CEA ( Commissariat à l'énergie atomique et aux énergies Lesser General Public License as published by the Free Software Foundation , version 2.1 . See the GNU Lesser General Public License version 2.1 for more details ( enclosed in the file licenses / LGPLv2.1 ) . include Plugin.Register (struct let name = "metrics" let shortname = "metrics" let help = "syntactic metrics" end) module Enabled = WithOutput (struct let option_name = "-metrics" let help = "activate metrics computation" let output_by_default = true end) module ByFunction = WithOutput (struct let option_name = "-metrics-by-function" let help = "also compute metrics on a per-function basis" let output_by_default = true end) module OutputFile = Empty_string (struct let option_name = "-metrics-output" let arg_name = "filename" let help = "print some metrics into the specified file; \ the output format is recognized through the extension." end) module ValueCoverage = WithOutput ( struct let option_name = "-metrics-value-cover" let help = "estimate value analysis coverage w.r.t. \ to reachable syntactic definitions" let output_by_default = true end) module AstType = String (struct let option_name = "-metrics-ast" let arg_name = "[cabs | cil | acsl]" let help = "apply metrics to Cabs or CIL AST, or to ACSL specs" let default = "cil" end ) module Libc = False (struct let option_name = "-metrics-libc" let help = "show functions from Frama-C standard C library in the \ results; deactivated by default." end ) let () = AstType.set_possible_values ["cil"; "cabs"; "acsl"] module SyntacticallyReachable = Kernel_function_set (struct let option_name = "-metrics-cover" let arg_name = "f1,..,fn" let help = "compute an overapproximation of the functions reachable from \ f1,..,fn." end )
3b2b16b8c077d6ca39feae1b41a849a3e7c94f124a2c9090583a240cbcbcf306
haskell-servant/servant-snap
Context.hs
# LANGUAGE CPP # {-# LANGUAGE DataKinds #-} # LANGUAGE FlexibleContexts # # LANGUAGE FlexibleInstances # {-# LANGUAGE GADTs #-} # LANGUAGE KindSignatures # # LANGUAGE MultiParamTypeClasses # #if __GLASGOW_HASKELL__ < 710 # LANGUAGE OverlappingInstances # #endif # LANGUAGE ScopedTypeVariables # {-# LANGUAGE TypeOperators #-} module Servant.Server.Internal.Context where import Data.Proxy import GHC.TypeLits -- | 'Context's are used to pass values to combinators. (They are __not__ meant -- to be used to pass parameters to your handlers, i.e. they should not replace any custom ' Control . . Trans . Reader . ReaderT'-monad - stack that you 're using -- with 'Servant.Utils.Enter'.) If you don't use combinators that -- require any context entries, you can just use 'Servant.Server.serve' as always. -- -- If you are using combinators that require a non-empty 'Context' you have to -- use 'Servant.Server.serveWithContext' and pass it a 'Context' that contains all -- the values your combinators need. A 'Context' is essentially a heterogenous -- list and accessing the elements is being done by type (see 'getContextEntry'). -- The parameter of the type 'Context' is a type-level list reflecting the types -- of the contained context entries. To create a 'Context' with entries, use the operator @(':.')@ : -- > > > : type True : . ( ) : . EmptyContext True : . ( ) : . EmptyContext : : Context ' [ , ( ) ] data Context contextTypes where EmptyContext :: Context '[] (:.) :: x -> Context xs -> Context (x ': xs) infixr 5 :. instance Show (Context '[]) where show EmptyContext = "EmptyContext" instance (Show a, Show (Context as)) => Show (Context (a ': as)) where showsPrec outerPrecedence (a :. as) = showParen (outerPrecedence > 5) $ shows a . showString " :. " . shows as instance Eq (Context '[]) where _ == _ = True instance (Eq a, Eq (Context as)) => Eq (Context (a ': as)) where x1 :. y1 == x2 :. y2 = x1 == x2 && y1 == y2 -- | This class is used to access context entries in 'Context's. 'getContextEntry' returns the first value where the type matches : -- > > > getContextEntry ( True : . False : . EmptyContext ) : : -- True -- -- If the 'Context' does not contain an entry of the requested type, you'll get -- an error: -- > > > getContextEntry ( True : . False : . EmptyContext ) : : String -- ... ... No instance for ( HasContextEntry ' [ ] [ ] ) -- ... class HasContextEntry (context :: [*]) (val :: *) where getContextEntry :: Context context -> val -- TODO OVERLAPPABLE_ instance {-# OVERLAPPABLE #-} HasContextEntry xs val => HasContextEntry (notIt ': xs) val where getContextEntry (_ :. xs) = getContextEntry xs instance {-# OVERLAPPABLE #-} HasContextEntry (val ': xs) val where getContextEntry (x :. _) = x -- * support for named subcontexts -- | Normally context entries are accessed by their types. In case you need -- to have multiple values of the same type in your 'Context' and need to access them , we provide ' NamedContext ' . You can think of it as sub - namespaces for -- 'Context's. data NamedContext (name :: Symbol) (subContext :: [*]) = NamedContext (Context subContext) | ' descendIntoNamedContext ' allows you to access ` NamedContext 's . Usually you -- won't have to use it yourself but instead use a combinator like ' Servant . . WithNamedContext ' . -- This is how ' descendIntoNamedContext ' works : -- -- >>> :set -XFlexibleContexts > > > let subContext = True : . EmptyContext > > > : type subContext -- subContext :: Context '[Bool] > > > let parentContext = False : . ( NamedContext subContext : : NamedContext " subContext " ' [ ] ) : . EmptyContext -- >>> :type parentContext parentContext : : Context ' [ , NamedContext " subContext " ' [ ] ] > > > descendIntoNamedContext ( Proxy : : Proxy " subContext " ) parentContext : : Context ' [ Bool ] True : . EmptyContext descendIntoNamedContext :: forall context name subContext . HasContextEntry context (NamedContext name subContext) => Proxy (name :: Symbol) -> Context context -> Context subContext descendIntoNamedContext Proxy context = let NamedContext subContext = getContextEntry context :: NamedContext name subContext in subContext
null
https://raw.githubusercontent.com/haskell-servant/servant-snap/b54c5da86f2f2ed994e9dfbb0694c72301b5a220/src/Servant/Server/Internal/Context.hs
haskell
# LANGUAGE DataKinds # # LANGUAGE GADTs # # LANGUAGE TypeOperators # | 'Context's are used to pass values to combinators. (They are __not__ meant to be used to pass parameters to your handlers, i.e. they should not replace with 'Servant.Utils.Enter'.) If you don't use combinators that require any context entries, you can just use 'Servant.Server.serve' as always. If you are using combinators that require a non-empty 'Context' you have to use 'Servant.Server.serveWithContext' and pass it a 'Context' that contains all the values your combinators need. A 'Context' is essentially a heterogenous list and accessing the elements is being done by type (see 'getContextEntry'). The parameter of the type 'Context' is a type-level list reflecting the types of the contained context entries. To create a 'Context' with entries, use the | This class is used to access context entries in 'Context's. 'getContextEntry' True If the 'Context' does not contain an entry of the requested type, you'll get an error: ... ... TODO OVERLAPPABLE_ # OVERLAPPABLE # # OVERLAPPABLE # * support for named subcontexts | Normally context entries are accessed by their types. In case you need to have multiple values of the same type in your 'Context' and need to access 'Context's. won't have to use it yourself but instead use a combinator like >>> :set -XFlexibleContexts subContext :: Context '[Bool] >>> :type parentContext
# LANGUAGE CPP # # LANGUAGE FlexibleContexts # # LANGUAGE FlexibleInstances # # LANGUAGE KindSignatures # # LANGUAGE MultiParamTypeClasses # #if __GLASGOW_HASKELL__ < 710 # LANGUAGE OverlappingInstances # #endif # LANGUAGE ScopedTypeVariables # module Servant.Server.Internal.Context where import Data.Proxy import GHC.TypeLits any custom ' Control . . Trans . Reader . ReaderT'-monad - stack that you 're using operator @(':.')@ : > > > : type True : . ( ) : . EmptyContext True : . ( ) : . EmptyContext : : Context ' [ , ( ) ] data Context contextTypes where EmptyContext :: Context '[] (:.) :: x -> Context xs -> Context (x ': xs) infixr 5 :. instance Show (Context '[]) where show EmptyContext = "EmptyContext" instance (Show a, Show (Context as)) => Show (Context (a ': as)) where showsPrec outerPrecedence (a :. as) = showParen (outerPrecedence > 5) $ shows a . showString " :. " . shows as instance Eq (Context '[]) where _ == _ = True instance (Eq a, Eq (Context as)) => Eq (Context (a ': as)) where x1 :. y1 == x2 :. y2 = x1 == x2 && y1 == y2 returns the first value where the type matches : > > > getContextEntry ( True : . False : . EmptyContext ) : : > > > getContextEntry ( True : . False : . EmptyContext ) : : String ... No instance for ( HasContextEntry ' [ ] [ ] ) class HasContextEntry (context :: [*]) (val :: *) where getContextEntry :: Context context -> val HasContextEntry xs val => HasContextEntry (notIt ': xs) val where getContextEntry (_ :. xs) = getContextEntry xs HasContextEntry (val ': xs) val where getContextEntry (x :. _) = x them , we provide ' NamedContext ' . You can think of it as sub - namespaces for data NamedContext (name :: Symbol) (subContext :: [*]) = NamedContext (Context subContext) | ' descendIntoNamedContext ' allows you to access ` NamedContext 's . Usually you ' Servant . . WithNamedContext ' . This is how ' descendIntoNamedContext ' works : > > > let subContext = True : . EmptyContext > > > : type subContext > > > let parentContext = False : . ( NamedContext subContext : : NamedContext " subContext " ' [ ] ) : . EmptyContext parentContext : : Context ' [ , NamedContext " subContext " ' [ ] ] > > > descendIntoNamedContext ( Proxy : : Proxy " subContext " ) parentContext : : Context ' [ Bool ] True : . EmptyContext descendIntoNamedContext :: forall context name subContext . HasContextEntry context (NamedContext name subContext) => Proxy (name :: Symbol) -> Context context -> Context subContext descendIntoNamedContext Proxy context = let NamedContext subContext = getContextEntry context :: NamedContext name subContext in subContext